Professional Documents
Culture Documents
Introduction To C Language
Introduction To C Language
by Supreet Singh
Overview of C
◦ Dennis Ritchie is the creator of C
◦ Created at Bell Laboratories
C is a structured programming language
C supports functions that enables easy
maintainability of code, by breaking large
file into smaller modules
Comments in C provides easy readability
C is a powerful language
Features of C
Portable Language
◦ C language is machine independent. Source Code
written using C can be compiled on any machine
Structured Language
◦ problem is solved using a divide and conquer
approach
Comments
Comments are used to document programs and improve readability
In C a comment will start with /* and ends with */
Syntax: /* Comments */
/*This is a single line comment */
/* This is a multiline
* comment in C */
/************************************************
* This style of commenting is used for functions
************************************************/
The C++ style comments will start with a // and ends at the end of that line
Variables
An identifier for the data in the program
Hold the data in your program
Is a location (or set of locations) in memory where a value can be
stored for use by a program
A quantity that can change during program execution
Declaration
<<Data type>> <<variable name>>;
int a;
Definition
<<varname>>=<<value>>;
a=10;
Usage
<<varname>>
a=a+1; //increments the value of a by 1
Variable names- Rules
A variable name can either begin with an
alphabet or underscore
No other special character except
underscore is allowed
Variable names are case sensitive
Keywords cannot be used as variable
names
Constants
A constant is a named or unnamed value, which does not change
during the program execution.
Named constants are defined by preceding an initialized variable
definition with the keyword const
Example:
#include<stdio.h>
int main()
{
--other statements
}
A complete program
#include <stdio.h>
int main(int argc, char **argv){ Pre processor
printf(“Hello World”); directive
Each instruction in a
C program
terminates with a
semicolon (;)
The main Function
Entry point of any C program
Using
the signature int main (int argc,
char** argv) is a good programming practice
Example:
/* To read an integer */ Common programming error:
printf(“Enter a number: ”);
scanf(“%d”, &iCount);
•
Not including ‘&’ before the
variable name
/* To read a float */
printf(“Enter Amount: ”); •
Missing comma between the
scanf(“%f”, &fAmount);
conversion specifier and variable
name
•Mismatch in the number and type
of conversion specifier for the used
variables
Reading Keyboard Input – scanf function
(2 of 2)
/* Reading multiple input */
short iDay,iMonth,iYear;
printf("Enter day, month and year in
format(dd mm yyyy)");
scanf("%d%d%d",&iDay,&iMonth,&iYear);
/* Reading character input */
char cChoice;
printf(“Want to continue “);
fflush(stdin);
scanf(“%c”,&cChoice);
Code
used to represent English alphabets,
numerical digits and commonly used symbols as
numbers
Other
Character sets: EBCDIC (Mainframes) and
UNICODE (2 byte character set)
◦ Arithmetic operators
◦ Assignment operator
◦ sizeof operator
◦ Logical operators
◦ Relational operators
◦ Increment and Decrement Operators
Type Casting
Temporary conversion of one data type into another
In some situations, the compiler will automatically convert
one data type into another
Type casting is an overhead for the compiler and should be
used only when it is absolutely necessary
Example:
float fResult;
fResult = 7 / 2 ;
They are also called as unary operators because they have only one
operand to operate
Example:
++iValue and -–iValue is called as prefix
iValue++ and iValue-- is called as postfix
Control Structures
A control structure refers to the way in which the
Programmer specifies the order of executing the
statements
if (iDuration >= 3) {
if (iDuration >= 3) {
/* If duration is equal to or
more than 3 years,
Interest rate is 6.0 */
fRateOfInterest = 6.0;
}
else {
/* else, Interest rate is 5.5 */
fRateOfInterest = 5.5;
}
else if Statement (1 of 3)
The ‘else if’ statement is used to check for a
sequence of conditions
if (iDuration > 6 ) {
if (dPrincipalAmount > 25000) {
printf(“Your percentage of incentive is 4%”);
}
else {
printf(“Your percentage of incentive is 2%”);
}
else {
printf(“No incentive”);
}
What is the output of the following
code snippet?
iResult = iNum % 2;
if ( iResult = 0) {
printf("The number is even");
}
else {
printf("The number is odd"); The output is
} "The number is
odd"
The innermost for loop executes once for each iteration of the
outermost loop
Question:
if the iterations in the outermost loop is 3 and the iterations in
the innermost loop is 4, then how many times the statements
in the innermost loop gets executed?
Quitting the Loops – break
Statement
Forces the termination of a loop
Note:
‘break’ statement can be used in an if statement only when the
if statement is written in a loop (while, do while or for)
Just an if statement with ‘break’ (without loops) leads to
compilation error
break Statement Example
for (iLoopIndex = 2; iLoopIndex < iNumber; iLoopIndex++) {
/* It is not a prime if it is divisible by any other
number */
if (iNumber % iLoopIndex == 0) {
cPrime = ‘N’;
break; /* Quit the loop */
}
}
/* After break statement, continue from here */
if (‘Y’ == cPrime) {
printf(“%d is a prime number”,iNumber);
}
else {
printf(“%d is not a prime number”,iNumber);
}
Continuing the Loops - continue Statement
(1 of 2)
‘continue’ statement forces the next iteration of the loop
to take place and skips the code between ‘continue’
statement and the end of the loop
Syntax:
exit(int status);
When an array is declared inside a function without initializing it, the elements
have unknown (garbage) values and outside the function the elements have
zero/default values
Declaring and Initializing arrays (1
of 2)
Arrays can be initialized as they are declared
Example:
int aiEmployeeNumbers[] = {15090, 15091,
15092, 15093,15094, 15095};
A 2-D array should be declared by specifying the row size and the
column size
To access the individual elements, the row and the column should be
supplied
To access the individual elements row index (starts from zero) and the
corresponding column index (starts from zero) should be supplied
Example:
printf(“%d”,aiEmployeeInfo[0][1]);
The above printf references the information at 0th row 1st column
Initializing 2-D Arrays(1 of 2)
A 2-D array can be initialized as given below:
Example:
int aiEmployeeInfo[][3]=
{101,1,102,1,103,2};
Since there are six initial values and the column size is 3, the
number of
rows is taken as 2
8FFE 5
&iNumber
Pointers - Address of Operator(3 of
5)
To print the address of a variable, precede the variable with an
ampersand (&) Since an address is an unsigned integer,
%u is used as a conversion specifier
Example:
int iNumber = 100;
printf(“The value is %d\n”,iNumber);
printf(“The address is %u\n”,&iNumber);
printf(“The address in hexa decimal is
%x\n”,&iNumber);
Example:
/* Initializing pointer to NULL */
int *piCount = NULL;
Strings
Strings (1 of 2)
A string is a series of characters in a group
that occupy contiguous memory
Example:
“CDAC”
“Information Technology”
\n”,iCourseId, pcProg);
strlen() Function
strlen() function is used to count the number of characters in the string
Syntax:
unsigned int strlen (char string[]);
Here string[ ] can be a string constant or a character pointer or a character
array and the function returns unsigned int
Example:
strlen(“Programming Fundamentals”); returns 24
scanf(“%s”, acItemCategory);
scanf(“%s”, &acItemCategory[0]);
Both the input functions are valid. The first one passes the base
address (Address of the first element) implicitly
The second function passes the address of the first element explicitly
gets(acItemCategory);
gets(&acItemCategory[0]);
Syntax:
strcpy (Dest_String , Source_String);
Here Dest_string should always be variable
Source_String can be a variable or a string constant
The previous contents of Dest_String, if any, will be over written
Example:
char acCourseName[40];
strcpy(acCourseName , “C Programming”);
Syntax
strcat( Dest_String_Variable ,
Source_String ) ;
In this, the Destination should be a variable and Source_String can
either be a string constant or a variable.
The contents of Dest_String is concatenated with Source_String
contents and the resultant string is stored into Dest_String variable.
Example:
char acTraineeFpCourse [50] = “The course is
“;
strcat(acTraineeFpCourse,”Oracle 10G”);
Syntax:
int strcmp( String1 ,
String2 );
◦ Here both String1 and String2 can either be a variable or a string
constant
strcmp() Function (2 of 2)
strcmp() function returns an integer value
Example:
strcmp(“My Work”, “My Job”); returns a
positive value
strcmpi() Function
strcmpi() function is same as strcmp()
function but it is case insensitive
Example:
strcmpi(“My WoRk” , “MY work”); returns zero
Functions
Functions
A function is a section of a program that performs a specific task
Function
call
Advantages of Functions
The functions can be developed by different people and can be
combined together as one application
After the function performs the task, it may send back the results to
the calling function
A function can return back only one value to the calling function
through a return statement
Function Definition :
Implementing the function or writing the task of the function
Consists of
• Function Header
• Function Body
Syntax:
Return_data_type FunctionName (data_type arg1,
data_type arg2,...,data_type
argn );
Example:
int fnValidateDate(int iDay,int iMonth, int iYear);
Syntax:
return (expression) ;
Example:
return(iNumber * iNumber);
return 0;
return (3);
return;
return (10 * iNumber);
Calling User-Defined Functions (1
of 2)
A function is called by giving its name and passing the
required arguments
void fnDisplay(){
printf(“Hello World”);
}
Called Function
Function Definition
Formal and Actual Parameters
The variables declared in the function
header are called as formal parameters
Actual Arguments
Functions – Example (2 of 2)
Formal Arguments
Return value
Parameter Passing Techniques
When a function is called and if the
function accepts some parameters, then
there are two ways by which the function
can receive parameters
◦ Pass by value
◦ Pass by reference
Pass by Value (1 of 3)
When parameters are passed from the
called function to a calling function, the
value of the actual argument is copied
onto the formal argument
main() fnUpdateValues()
100 115
200 240
a
main() fnUpdateValues()
115 Address of
iValue1
240 Address of
iValue2
When the problem is solved through recursion the source code looks
elegant
Recursive Functions (2 of 6)
/* Finding the factorial of an integer using a
recursive function */
Output will be 0 1 2 3 4 5
Recursive Functions (5 of 6)
Find the output of the following code snippet when the function is
called as fnReverse();
/* Global Variable Declaration */
int giValue = 5;
void fnReverse(){
if (giValue > 0) {
giValue--;
fnReverse();
}
printf("%d\n",giValue);
}
Examples:
In the date structure, iDay, iMonth and iYear are member variables
Declaring a Structure (4 of 4)
A structure is generally declared globally above
function ‘main’