SlideShare a Scribd company logo
1 of 63
CHAPTER 4
4.1 DECISION MAKING STATEMENTS
C program is a set of statements, which are normally executed sequentially in the order in which they
appear. This happens when no repetitions of certain calculations are needed. But we have a number of
situations where we may have to change the order of execution of statements based on certain conditions.
If condition is satisfied some set of statements will be executed. Else, another set of statements will be
executed.
A simple analogy for decision making
We are all familiar with the concept of making a decision. When driving a car, we have to make decisions
all the time. When we drive up to a light, we decide if it is red to stop the car. Else we can keep on
driving. So here the condition is the color of the traffic light. If red we stop else we drive as usual. Thus in
every action of our life we are making decision based on some situations or conditions.
C language has such decision making capacities and supports the following statements known as
decision-making statements or control statements.
 Simple if
 if else
 Nested if
 Nested else-if ladder
 switch
3.1.1 SIMPLE IF
A simple if statement consists of a boolean expression followed by one or more statements.
Syntax:
if (condition/boolean expression)
{
Statement(s)
}
Flowchart
If the condition or Boolean expression results true then the block of code inside the if statement will be
executed. If Boolean expression results false then the statement or set of statements after if i.e, after the
closing curly brace will be executed.
If the result of boolean expression is 1 then it is assumed as true. Otherwise,the result is assumed as false.
Example:
Output:
pass
Mark is
60
If the variable mark is assigned a value of 40(int mark =40; in the above example), then the output is
Mark is
40
Note:
 More than one condition can be written inside the if statement using logical connectives
&&(AND) and ||(OR).
 If the body of if statement has multiple statements then we can use opening and closing braces to
make it as a block. Otherwise they are not needed.
 But the better practice is to envelop even a single statement within open and close braces for
easing the readability.
4.1.2 IF...ELSE STATEMENT
An if condition followed by else statement makes the programmer to check any condition and depending
on the result of that condition they can take appropriate path. If the condition is true, then true part can be
executed and the false part otherwise.
Syntax
if(condition/boolean expression)
{
True statement(s)
}
else
{
False statement(s)
}
Flowchart
If the condition or Boolean expression results true then the true statements inside the if statement will be
executed. If Boolean expression results false then the false statements inside the else part will be
executed.
Example
The output will be
pass
Mark is
60
If mark is assigned a value of 40(int mark =40; in the above example), then the output will be
fail
Mark is
40
4.1.3 NESTED IF STATEMENT
A if statement can be used within another if statement and this is called as nesting of if statements. When
we want to check more than one condition at a time in a same program, nested if conditional statement
can be used.
Syntax
if(condition)
{
if(condition)
{
statements;
}
else
{
statements;
}
}
else
{
statements;
}
Flowchart
The conditions are executed from top to bottom checking each condition whether it meets the conditional
criteria or not. If it found the condition is true then it executes the block of associated statements of true
part else it goes to next condition to execute.
4.1.4 NESTED ELSE-IF
We can nest else if… else in the similar way as we have nested if statements. This is also known as
else..if ladder.
Syntax
if(condition1)
{
True Statements;
}
else if(condition2)
{
Statement 1;
}
:
:
else if(condition n)
{
Statement n;
}
else
{
Default statements;
}
Flowchart
Example for nested if and else..if ladder in one program
Output
pass & grade II
4.1.5 SWITCH STATEMENT
One of the common problem that we come across nested if else and else if ladder is that problem of
confusion. It occurs when no matching else for if is available. And main reason is that as the number of
alternative increases the complexity of program also extremely increases.
In order to overcome this, C provides a decision making statement called as switch. It is also called as
multi-way decision statement. The switch statement tests the value of a given variable (or expression)
against a list of case values and when a match is found, a block of statements associated with that case is
executed.
Syntax
switch(expression){
case constant 1:
body 1;
break;
case constant 2:
body 2;
break;
case constant 3:
body 3;
break;
default:
default body;
}
Flowchart
How it works?
 Switch case checks the value of expression or a variable against the list of case constants. The
expression could be integer expression or character expression.
 When a match is found, the body of statements associated with that case is executed.
 Each body of case constants is associated with a break statement. The break statement takes
control out of the case.
 After executing the body of case constant, the control goes to the statement after the switch
statement.
 When no match is found default body of statement is executed and control goes to the statement
after the switch statement.
Example
Output:
In case 4
statement next to switch statement
Explanation
Note: follow the arrow marks and number.
 4 is assigned to integer variable a.
 Switch statement is executed.
 Case variable a is first checked against case 1, not matched hence case 2 is checked and it goes on
until case constant 4 is found.
 Block of code specified in 4th
case is executed.
 After executing it comes out of switch with the help of break statement and executes statement
next to the switch statement.
Rules of using switch case
 Case label must be unique.
Example:
int a=2;
switch(a)
{
case 1:
printf(“case 1”);
break;
case2:
printf(“case 2”);
break;
case 2: //not allowed
printf(“case 2 again”);
break;
}
 Case labels must end with colon. Example: case 1:
 Case labels must have constants and constants expression. But it should not include variables as
case labels.
Allowed not allowed
case ‘a’: case var:
case 67: case num:
case 1+1: case a+b:
 Case labels must be integer or character. Example: case ‘a’: case 67:
 Case labels should not be floating point number. Example: case 5.6:
 Default label is optional and can be placed anywhere inside the switch.
int a=2;
switch(a)
{
case 1:
printf(“case 1”);
break;
default:
printf(“default block”);
break;
case2:
printf(“case 2”);
break;
}
 Two or more cases can share a single break.
char a=’a’;
switch(a)
{
case ‘a’:
case ‘A’:
printf(“case 1”);
break;
default:
printf(“default block”);
break;
}
 Switch can be nested i.e., switch statement within another switch statement.
 Relational operators are not allowed. Example: case >15:
Nested Switch Statements
It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case
constants of the inner and outer switch contain common values, no conflicts will arise.
Syntax:
switch(expression) {
case constant 1:
body1
switch(expression) {
case constant 1:
body 1of inner switch;
break
case constant 2:
/* case code */
}
break;
case constant 2: /* case code of outer switch */
}
Example:
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
switch(a) {
case 100:
printf("This is part of outer switchn", a );
switch(b) {
case 200:
printf("This is part of inner switchn", a );
}
}
printf("Exact value of a is : %dn", a );
printf("Exact value of b is : %dn", b );
return 0;
}
When the above code is compiled and executed, it produces following result:
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200
4.2 BRANCHING AND LOOPING STATEMENTS
Sometimes it is necessary to execute some set of statements in a program repeatedly. To handle such
situations C provide looping statements.
A loop is a part of code or set of statements which is executed repeatedly. A loop is always used along
with a condition. The reason is that the repetition is done as long as the condition is true.
A loop declaration and execution can be done in the following steps
1. checking a condition to start a loop
2. Initializing loop variable
3. Executing statements inside the loop
4. Increment or decrement of value of a loop variable.
C supports the following looping statements namely,
 while
 do…while
 for
Types of Looping Statements
Loops are classified normally based on the mode of checking the condition. Condition checking can be
done in two ways 1) before loop and 2) after loop. Based on this loops are broadly classified into two
types
Entry-controlled loops
Exit controlled loops
Entry Controlled Loops
In entry controlled loops, condition is checked before executing the loop. Example include while loop and
for loop
Exit Controlled Loops
In exit controlled loops, the loop is executed at least once. After that only condition is checked. Example
include do…while loop
4.2.1 WHILE LOOP
While loop is entry controlled loop. It checks the conditions first. If the conditions are satisfied the loop is
executed. Otherwise it will not execute the loop at all.
Syntax:
while(condition)
{
statements;
increment/decrement;
}
Flowchart
Example
Output
4.2.2 DO..WHILE LOOP
do.. while loop is exit controlled loop. Here the body of the loop is executed at least once and then the
condition is checked. If the condition is true, the loop is executed again, otherwise loop terminates (not
executed, comes out of the loop) and executes the statement after the while loop.
Syntax
do
{
Statements;
Increment /decrement;
}
while(condition);
Flowchart
Example
Output
Difference Between While and Do-While Looping Statements
While Do…while
Entry controlled loop
Exit controlled loop
If the condition is satisfied only the loop is
executed. Otherwise it is not at all executed
At least for once the loop is executed regardless of
the condition. After execution, the condition is
checked and if it is satisfied the loop is executed.
Otherwise not.
4.2.3 FOR LOOP
For loop is entry controlled loop. The loop is executed until the condition is satisfied.
Syntax:
for (initialization; condition; increment/decrement)
{
Body of the loop
}
Flowchart
For loop consists of the following parts inside the brackets which are separated by semicolons:
1. First part is called initialization part to initialize the loop variable. A loop variable is the one that
controls and counts the number of times the loop is executed.
2. Second part is the condition that must be satisfied for loop execution.
3. Third part is the loop variable increment or decrement. We can increment the loop variable
(adding 1) by step value or we can decrement (subtracting 1) the loop variable by a step value as
needed.
The advantage of for loop is that all initialization, condition checking and increment or decrement can be
done with the help of a single statement. Whereas in while and do..while, all these must be done as a
separate statement.
Program
Output
When to use for loop and while loop?
If the number of iterations the loop should run is known beforehand, then use for construct. While loops
are used when the number of iterations the loop should run will be determined in the future.
4.2.4 BREAK STATEMENT
Break statement is used to exit out of a loop at any time. This is useful when we want a loop to stop
running because a condition has been met other than the loop end condition.
Syntax
break;
Example
Output
Explanation:
Note: Follow the numbers and arrow mark
1. If the condition in for loop is satisfied, first statement in the body of the loop is executed.
2. If statement in the second line is executed.
3. If condition is true, break statement is executed.
4. Break statement terminates the loop and comes out of the loop.
5. If condition is false the control goes to the increment or decrement part of for loop.
4.2.5 CONTINUE STATEMENT
Continue statement is used to skip the rest of the current loop and start from the top again while
incrementing the loop variable again.
Syntax
continue;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
clrscr();
printf("Enter the number of elementsn");
scanf("%d",&n);
for(i=1;i<=n;i++)
{ 1
2 printf("ni never gets printedn");
continue;
printf("nValue of i:%d n",i);
}
getch();
}
Output
Explanation:
Note: Follow the numbers and arrow mark
1. If the condition in for loop is satisfied, first statement in the body of the loop is executed.
2. Continue statement takes control to the increment part of for loop again and hence only ‘i never
gets printed’ is displayed for 5 times. The control does not go to the statement after continue.
4.4 ARRAYS
An array is a collection of variables of similar type of data.
Arrays consist of adjacent memory locations. The lowest address refers to the first element and
the highest address to the last element. We can access a particular or individual element in an
array by using an index. An index is an integer enclosed in a square bracket in the array
declaration followed by array name.
First element is referred by index 0 and last element is referred by index array size-1.
Types of Array
Based on the number of subscript used in an array, two types of arrays exist namely,
 Single dimensional array
 Multi dimensional array
4.4.1 SINGLE DIMENSIONAL ARRAY
An array with only one subscript is known as single dimensional array. Subscript is the value
enclosed within square brackets [] following the arrayname in the syntax.
Syntax
datatype arrayname[subscript/size];
Where
Parameter Description
Datatype Type of each element of the array
Arrayname Name of the array using a valid variable name
Subscript or size Dimension of the array
Example: int a[10]; char text[20]; float b[10];
Initializing arrays
Arrays in C can be initialized one by one or using the following syntax.
datatype arrayname[size]={value1,value2,……….,value n);
Example: int a[5]={1,2,3,4,5};
The number of elements in the braces {} cannot exceed the size specified within []. The elements
are stored in contiguous memory location as show in the following figure
1 2 3 4 5
a[0] a[1] a[2] a[3] a[4]
Accessing Array Elements
Array index normally starts with 0 and hence the first element is stored in 0th index and the last
element in 4th index.
To access array elements use the corresponding array name with index. For example, the
statement int x=a[3]; assigns the value at index 3 to variable x. Now x has the value 4. To access
entire elements of an array, we can use for loop.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5], i;
clrscr();
printf("Enter the elements of the arrayn");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
printf("nthe array elements aren");
for(i=0;i<5;i++)
{
printf("%dn",a[i]);
}
getch();
}
Output
4.3.2 MULTIDIMENSIONAL ARRAY
Arrays with more than one subscript are called as multidimensional arrays.
Syntax:
datatype arrayname[size1][size2]….[sizeN];
Example:
int a[10][10]; and int a[10][10][10];
Two dimensional arrays
Most simple form of multidimensional array is the two dimensional array which comes with two
subscripts. It stores the value in the form of a matrix. The first subscript indicates “row” of a
matrix and the second subscript indicates “column” of a matrix.
Here in the above figure
[0][0] means 0th row and 0th column
[0][1] means 0th row and 1st column and so on
Syntax:
datatype arrayname[size1][size2];
Example: int a[3][3];
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.
int a[3][3] = {
{1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6} , /* initializers for row indexed by 1 */
{7, 8, 9} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
int a[3][3] = {1,2,3,4,5,6,7,8,9};
Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts ie. row index and column
index of the array. For example:
int val = a[2][3];
The above statement will take 3rd element from the 2nd row of the array. For accessing elements
from two dimensional array, we need two for loops (one for accessing row details and the other
for accessing column details).
Example program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3]={1,2,3,4,5,6,7,8,9}, i,j;
clrscr();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("the value of a[%d][%d] =%dn",i,j,a[i][j]);
}
}
getch();
}
Output
Applications of Array
Array can be used in the following applications
1. Sorting problems
2. Performing matrix operations
3. CPU scheduling
4. Recursive Function and so on..
Limitations of Array
1. Array is a static data type. Memory allocated once at compile time cannot be changed at run time.
2. Inserting in an array is difficult. Because before inserting an element in array, a free space must
be created for which other elements are pushed one position ahead. This works faster for array of
small size. But for larger size array, this operation will be time consuming and non-efficient.
3. Likewise delete operation is also difficult to be performed.
4. If large array is declared, but have less elements, then there is wastage of memory.
5. If the size of the array is n, then we can access n-1 elements. If we try to access elements after n-
1, then we will get garbage value as result.
3.4 FUNCTIONS
Function is a segment that groups a number of program statements to perform specific task. A C program
has at least one function main( ). Without main() function, there is technically no C program.
Types of C functions
Basically, there are two types of functions in C on basis of whether it is defined by user or not.
 Library function
 User defined function
Library function
Library functions are the in-built function in C programming system. Following are some of the examples
for library functions in C
 main()
- The execution of every C program starts from this main() function.
 printf()
- prinf() is used for displaying output in C.
 scanf()
- scanf() is used for taking input in C.
User defined function
User defined functions are the own functions written by the programmer/user according to their
requirement. Suppose, a programmer wants to find factorial of a number and as well as check whether it
is prime or not in same program. Then, he/she can create two separate user-defined functions in that
program: one for finding factorial and other for checking whether it is prime or not.
Syntax
void main()
{
Body of the main function
}
return_type function_name(type 1 argument 1,..,type n argument n)function declrator
{
//body of functionfunction body
}
The program given below is an example for creating a user defined function add in order to find sum of
two integer numbers.
Program
Output
Explanation
The function is called and executed in the following order.
Step 1: the function add is called from the main function and hence control goes to the function decalrator
part of the function definition. Then the first line of the body of the function is executed.
Step 2: after execution, the resultant value is returned from the called function(user defined function) to
the calling function(main function).
Advantages of functions/user-defined functions
 User defined functions helps to decompose the large program into small segments which makes
programmar easy to understand, maintain and debug.
 If repeated code occurs in a program. Function can be used to include those codes and execute
when needed by calling that function.
Function prototype (declaration):
Like variables are declared before they are being used, every function in C programming should be
declared before they are used. This type of declaration are also called function prototype. Function
prototype gives compiler information about function name, type of arguments to be passed and return
type.
Syntax
return_type function_name(type1 argument1,....,type n argument n);
Example
In the above example int add (int , int ); is a function prototype which provides following information to
the compiler:
1. name of the function is add()
2. return type of the function is int.
3. two arguments of type int are passed to function.
There is no need of function prototype whenever user-definition function is written before main()
function.
Function call
To transfer the control of the program to user-defined function, it must be called or invoked.
Syntax
function_name(argument 1,....argument n);
Example
In the above example, function call is made using statement add(a,b); from main(). After executing this
statement, the control of program jumps from that statement to function definition and executes the codes
inside that function.
Function definition
Function definition contains programming codes to perform specific task.
Syntax
return_type function_name(type 1 argument 1,..,type n argument n)function declrator
{
//body of functionfunction body
}
Function definition has two major components:
1. Function declaratory
2. Function body
Function declarator is the first line of function definition. When a function is invoked from calling
function, control of the program is transferred to function declarator or called function. Syntax of function
declaration and declarator are almost same except, there is no semicolon at the end of declarator and
function declarator is followed by function body. Function declarator is followed by body of function
which is composed of statements.
Passing arguments/paramters to a function
Argument/parameter is piece of data(variable or a constant value) passed from the main function to the
user defined function. Here the main function is called as calling function and user defined function is
called as called function.
Two types of variables exist namely
 Local variable
 Global variable
Local Variable Global Variable
Variable that is declared inside a function is a local
variable
Variable that is declared outside of all functions is
a local variable
Local variable can only be used in the function
where it is declared
A global variable can be used in all functions
Arguments that are passed in calling function and arguments that are accepted in called function should
have same data type. For example: in the above example program, If argument a was of integer type and
b was of float type then, argument variable x should be of type integer and y should be of type float. A
function can be called with or without an argument.
Two types of parameters exist namely
 Actual parameter-Parameter used in calling function. In the above example parameters a & b are
actual parameters
 Formal parameter-Parameter used in called function. In the above example parameters x & y are
formal parameters.
Return Statement
Return statement is used to return a value from function definition to calling function.
Syntax
return (expression);
OR
return;
Example
return;
return a;
return (a+b);
in the above example program, we use return x+y; to return the value from function definition to calling
function.
4.4.1 TYPES OF USER DEFINED FUNCTION
User defined functions in C are classified into four types namely,
 Functions with no argument and no return value
 Functions with no arguments and with return value
 Functions with arguments and no return value
 Functions with arguments and return value
Functions with no argument and no return value
In this type of function, no argument is passed to the user defined function from the main function and no
value is also returned from the user defined function to the main function. Hence return statement is not
used.
Program
#include<stdio.h>
#include<conio.h>
void add();
void main()
{
clrscr();
add();
getch();
}
void add()
{
int a,b;
printf("enter a nd b");
scanf("%d%d",&a,&b);
printf("sum=%d",a+b);
}
Output
Functions with no arguments and with return value
In this type of user defined function, no argument is passed to the user defined function from the main
function, but resultant value is returned to the main function. Hence return statement is needed.
Program
#include<stdio.h>
#include<conio.h>
int add();
void main()
{
int c;
clrscr();
c=add();
printf("Sum=%d",c);
getch();
}
int add()
{
int a,b;
printf("enter a nd b");
scanf("%d%d",&a,&b);
return (a+b);
}
Output
Functions with arguments and no return value
In this type of user defined function, arguments are passed from main function to user defined function
but no resultant value is returned to main function from the user defined function.
Program
#include<stdio.h>
#include<conio.h>
void add(int, int);
void main()
{
int a,b;
clrscr();
printf("enter a and b");
scanf("%d%d",&a,&b);
add(a,b);
getch();
}
void add(int x, int y)
{
printf("sum=%d",x+y);
}
Output
Functions with arguments and return value
In this type of user defined function, arguments are also passed from the main function to the user defined
function and result of the function is returned from the user defined function to the main function.
Program
#include<stdio.h>
#include<conio.h>
int add(int, int);
void main()
{
int a,b,c;
clrscr();
printf("enter a and b");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("sum=%d",c);
getch();
}
int add(int x, int y)
{
return(x+y);
}
Output
4.4.2 PARAMETER PASSING
While calling a function, C supports two ways of passing parameter or arguments to it namely
 Pass/Call by value
 Pass/Call by reference
Pass/Call by value
This method copies the actual value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the argument. By default, C
programming language uses call by value method to pass arguments.
Program
#include<conio.h>
#include<stdio.h>
void swap(int, int);
void main()
{
int a,b;
clrscr();
printf("enter the value of a and b");
scanf("%d%d",&a,&b);
printf("noriginal value of a=%d",a);
printf("noriginal value of b=%d",b);
swap(a,b);
printf("nafter swap a=%d",a);
printf("nafter swap b=%d",b);
getch();
}
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf("nINSIDE swap a=%d",x);
printf("nINSIDE swap b=%d",y);
}
Output
Pass/Call by reference
This method copies the address of an argument into the formal parameter. Inside the function, the address
is used to access the actual argument used in the call. This means that changes made to the parameter
affect the passed argument.
To pass the value by reference, argument pointers are passed to the functions just like any other value. So
accordingly we need to declare the function parameters as pointer types as in the following function
swap(), which exchanges the values of the two integer variables pointed to by its arguments.
Program
#include<conio.h>
#include<stdio.h>
void swap(int *, int *);
void main()
{
int a,b;
clrscr();
printf("enter the value of a and b");
scanf("%d%d",&a,&b);
printf("noriginal value of a=%d",a);
printf("noriginal value of b=%d",b);
swap(&a,&b);
printf("nafter swap a=%d",a);
printf("nafter swap b=%d",b);
getch();
}
void swap(int * x, int * y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
printf("nINSIDE swap a=%d",*x);
printf("nINSIDE swap b=%d",*y);
}
Output
Difference between call by value and call by reference
Call By Value Call By Reference
Duplicate copy of original parameter is passed Actual copy of original parameter is passed
If any change is done in the user defined function ,
it will not be reflected in main function
If any change is done in the user defined function ,
it will reflected in main function
4.4.3 RECURSIVE FUNCTION
A function that contains a call to itself is called a recursive function. There must be at least one
terminating condition for a recursive function. Otherwise the recursive function will call itself infinitely.
Recursive functions are very useful to solve many mathematical problems like to calculate factorial of a
number, generating Fibonacci series etc.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int n,fact;
clrscr();
printf("enter the number for finding factorial");
scanf("%d",&n);
fact=factorial(n);
printf("factorial=%d",fact);
getch();
}
int factorial(int x)
{
if(x==0)
{
return 1;
}
else
{
return x*factorial(x-1);
}
}
Output
Advantages
 Problems can be solved in easy way
 Size of the code can be reduced
Disadvantages
 Difficult to debug and understand the logic
 Increases space complexity since recursive function consumes more memory if the depth of
recursion is too large.
Applications
 Solving Tower of Hanoi problem
 Solving Mathematical problems like finding LCM, GCD and Factorial of a given number,
Generation of Fibonacci series and so on
 Solving problems that have hierarchical relationship for example trees.
4.4.4 PASSING ARRAYS TO FUNCTIONS
In C programming, a single array element or an entire array can be passed to a function. Also, both one-
dimensional and multi-dimensional array can be passed to function as argument.
Passing single element of an array to a function
Single element of an array can be passed in similar manner as passing variable to a function.
Program
#include<stdio.h>
#include<conio.h>
void display(int);
void main()
{
int a[]={1,2,3};
clrscr();
display(a[2]);
getch();
}
void display(int a)
{
printf("The element to be displayed=%d",a);
}
Output
Passing entire array to the function
To pass entire array as an argument to the function, just pass the name of the array as an argument(,i.e,
starting address of memory area is passed as argument).
Program
#include<stdio.h>
#include<conio.h>
void display(int a[]);
void main()
{
int a[]={1,2,3,4,5};
clrscr();
printf("display the elements of an array");
display(a);
getch();
}
void display(int a[])
{
int i;
for(i=0;i<5;i++)
{
printf("n%dn",a[i]);
}
}
Output
Passing Multi-dimensional Arrays to Function
For passing two dimensional arrays to a function, the starting address of memory area reserved is passed
as argument to function. This is similar to passing one dimensional array.
Program
#include<stdio.h>
#include<conio.h>
void display(int a[2][2]);
void main()
{
int a[2][2]={1,2,3,4};
clrscr();
printf("display the elements of an array");
display(a);
getch();
}
void display(int a[2][2])
{
int i,j;
for(i=0;i<2;i++)
{
printf("n");
for(j=0;j<2;j++)
printf("%dt",a[i][j]);
}
}
Output
4.5 STORAGE CLASSES
A storage class identifies the scope (visibility) and life time of variables, functions declared within a C
program.
Storage class of a variable determines the following
1. Where the variable is stored
2. Scope (visibility) of a variable
3. Default initial value of a variable (if it is not initialized).
4. Life time of a variable.
Where the variable is stored
Storage class determines the location of a variable it is being stored. For example, sometimes variables
can be stored in memory and at times, they are stored in CPU register.
Scope of a variable
Scope of a variable is the visibility of the variable in the block. Visibility means accessibility i.e., up to
which division or area of a program, we can access a variable. There are four types of scopes in C
namely,
 Block scope -If a variable or function has scope only within the area where it has declared then
scope of variable or function is called as block scope.
 Function scope -there is no difference between function block and any other blocks in c. Because,
there is no modifier of storage class group existing, that has function block. Label of goto
statement has function block scope. Label of particular goto statement is not visible in another
function
 File scope - If any variable or function has scope only within a file where it has declared then
scope of variable or function is known file scope.
 Program scope - If any variable or function has scope throughout the whole program, then scope
of variable or function is known program scope.
Default initial value of a variable
Whenever a variable is declared in C, a garbage value is assigned to it automatically. This is considered as
initial value of the variable. Different storage classes have different initial values. For example, global
variables have initial value as 0 whereas local variables have some garbage value.
Life time of a variable
Lifetime of a variable is the extent to which it is active in the program and in which area of the program.
It is given as
Life time of a variable = time of declaration – time of variable destruction.
For example, if we have declared variable inside the main function, then the variable is destroyed only
when the control comes to the end of the program.
4.5.1 TYPES OF STORAGE CLASSES
Four types of storage classes exist in C namely,
 Auto
 extern
 static
 register
4.5.1.1 AUTO
auto storage class is the default storage class for all local variables. They are usually defined inside the
function.
Syntax
auto datatype variable;
Example
auto int a;
Features of this storage class are listed in the following table.
Features Value
Storage Memory
Scope Local and block scope
Life time Exist as long as control remains in that block
Default initial value Garbage value
Program
#include<stdio.h>
#include<conio.h>
void main()
{
auto num=20;
clrscr();
{
auto num=60;
printf("number=%dn", num);
}
printf("nnumber=%d",num);
getch();
}
Output
Note: variable num is declared in two different blocks, hence considered as two different variables.
4.5.1.2 EXTERN
extern storage class is the default storage class for all global variables. They are usually defined outside
the function and are accessible to all functions in the program. A particular extern variable can be
declared many times but we can initialize at only one time. extern variable cannot be initialized locally
i.e. within any block either at the time of declaration or separately. If extern keyword is not used with
global variables then compiler will automatically initialize with default value to extern variable.
Syntax
extern datatype variable;
Example
extern int a;
Features of this storage class are listed in the following table.
Features Value
Storage Memory
Scope Global and file scope
Life time Exist as long as variable is running
Retains value within the function
Default initial value 0
Program
#include<stdio.h>
#include<conio.h>
int num=20;/*all global variables are
considered as extern and hence no need to specify the keyword extern*/
void main()
{
extern int num;
clrscr();
printf("number=%dn",num);
{
extern int num;
printf("number=%dn", num);
}
getch();
}
Output
Note: variable num is treated as local variable and hence considered as to have single value even though,
they are declared in two different blocks.
4.5.1.3 STATIC
Static variable may be either internal or external depending on where it is declared. If declared outside the
function body, then it acts as either static or extern variable. If declared inside the function body, then it
acts as auto variable. The contents of static variable will remain the same throughout the program. Thus
using this property we can count the number of times a function is being called.
Syntax
static datatype variable;
Example
static int a=10;
Features of this storage class is listed in the following table
Features Value
Storage Memory
Scope Global and file scope as well as local and block
scope
Life time Global:
Exist as long as variable is running
Retains value within the function
Local: Exist as long as control remains in that
block
Default initial value 0
Program
#include<stdio.h>
#include<conio.h>
void main()
{
void f1();
clrscr();
f1();
printf("tafter first call.n");
f1();
printf("tafter second call.n");
f1();
printf("tafter third call.n");
getch();
}
void f1()
{
static int i=0;
int j=10;
printf("value of i is %d and j is %d",i,j);
i=i+10;
getch();
}
Output
Function f1 is called for the first time and value 0 is initialized to i and 10 to j. After first call the value of
k and j is printed as output. Then control transfer to the main program. At the second call value of i is not
initialized because of being a static variable. Value of i and j is printed after second call and third call as
output.
4.5.1.4 Register
The register storage class is used to define local variables that should be stored in a register
instead of memory. This means that the variable has a maximum size equal to the register size
(usually one word) and can't have the unary '&' operator applied to it (as it does not have a
memory location). The register should only be used for variables that require quick access such
as counters. It should also be noted that defining 'register' does not mean that the variable will be
stored in a register. It means that it MIGHT be stored in a register depending on hardware and
implementation restrictions.
Syntax
register datatype variable;
Example
register int miles;
Features of this storage class are listed in the following table.
Features Value
Storage CPU register
Scope Local to the block
Life time Exist as long as control remains in that block
Default initial value Garbage
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20;
register int c;
clrscr();
c=a+b;
printf("the value of %d is stored in register c", c);
getch();
}
Output
4.6 STRINGS
The string in C programming language is actually a one-dimensional array of characters
terminated by a null character '0'. Thus a null-terminated string contains the characters that
comprise the string followed by a null.
Actually, it is not compulsory to place the null character at the end of a string constant. The C
compiler automatically places the '0' at the end of the string when it initializes the array. Each
character occupies one byte of memory and hence the last character is always ‘0’.
Thus to hold the null character at the end of the array, the size of the character array containing
the string is always one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char greeting[6]={'H','E','L','L','O'};
clrscr();
printf(" Greetings is %s",greeting);
getch();
}
Output
If size of the character array for the above example is given as exactly 5 as shown below, then
some garbage value will be printed.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
char greeting[5]={'H','E','L','L','O'};
clrscr();
printf(" Greetings is %s",greeting);
getch();
}
Output
If the rule of array initialization is followed, then the above statement can be written as follows:
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++:
Reading and writing strings
Control string ‘%s’ can be used in scanf() statement to read a string from the terminal (keyboard)
as well as in printf() statement to write a string to the terminal(console or monitor).
We can also use gets() and puts() as well as getchar() functions.
4.6.1 STRING FUNCTIONS
C supports a wide range of functions that manipulate null-terminated strings. These functions are
available in the header file <string.h>. If we want to use these functions, this header file can be
included in the program.
Function Description Syntax Example
strlen() Determines the length of the string
strlen(char*
string)
char txt[10]=”hello”;
int length=strlen(txt);
output is 5
strcpy() Copies one string to the another string
strcpy(char *s2,
char *s1);
s1 source string
s2destination
String
char text[10]=”hai”;
char dest[10];
strcpy(dest,text);
Output is dest=hai
strncpy() Concatenates string s2 onto the end of
string s1.
strcpy(char *s1,
char *s2, int n);
s2 source string
s1destination
String
nlength of the
string to be copied
char text[10]=”hai”;
char dest[10]=”hello”
n=2
strcpy(dest,text,2);
Output is dest=hallo
strcmp()
Two strings are compared.
Differentiate between upper and
lower case.
strcmp(char
*s1,char * s2);
char text[10]=”hai”;
char dest[10]=”Hai”
strcmp(dest,text);
Output is strings are
different
stricmp()
Two strings are compared. Does not
differentiate between upper and lower
case.
stricmp(char
*s1,char * s2);
char text[10]=”hai”;
char dest[10]=”Hai”
stricmp(dest,text);
Output is strings are
same.
strncmp()
Two strings are compared up to the
specified length. Differentiate
between upper and lower case.
strncmp(char *s1,
char *s2, int n);
s2 string2
s1 String1
nlength of the
string to be
compared
char text[10]=”hai”;
char dest[10]=”Hai”
n=1
strncmp(dest,text);
Output strings up to 1
character are different
strnicmp()
Two strings are compared up to the
specified length. Does not
differentiate between upper and lower
case.
strnicmp(char *s1,
char *s2, int n);
s2 string2
s1 String1
nlength of the
string to be
char text[10]=”hai”;
char dest[10]=”Hai”
n=2
strnicmp(dest,text);
Output strings up to 2
character are different
compared
strlwr()
Upper case of the string is converted
to lower case
strlwr(char * s) char text[10]=”ABC”;
strlwr(text);
output: abc
strupr()
Lower case of the string is converted
to upper case
strupr(char * s) char text[10]=”abc”;
strlwr(text);
output: ABC
strdup() Given string is duplicated
char * strdup(char
* string)
char text[10]=”abc”;
char * txt=strdup(text);
output: txt=abc
strchr()
First occurrence of a given character
in a string is determined
chp=strchr(char *
String, char ch)
chppointer that
collects the address
returned by the
function
char
text[10]=”beginner”;
char ch=’n’;
chp=strchr(text,ch);
Output character n is
found at address 28270
strrchr()
Last occurrence of a given character
in a string is determined
chp=strrchr(char
* String, char ch)
chppointer that
collects the address
returned by the
function
char
text[10]=”beginner”;
char ch=’n’;
chp=strrchr(text,ch);
Output character n is
found at address 25966
strstr()
Returns a pointer to the first
occurrence of string s2 in string s1
chp= strstr(char *
s1, char * s2);.
char text[10]=”I love
India”;
char text1[10]=”India”;
chp=strstr(text,text1);
Output India is present at
address 25966
strcat() String s2 is concatenated onto the end
of string s1.
strcat(char *
s1,char *s2);
char txt1[10]=”good”;
char
txt2[10]=”morning”;
strcat(txt1,txt2);
output is goodmorning
strncat() String s2 is concatenated onto the end
of string s1upto the specified length
strcat(char *
s1,char *s2,int n);
nno of characters
to append
txt1[10]=”good”;
char
txt2[10]=”morning”;
n=2
strcat(txt1,txt2,n);
output is goodmo
strrev() Reverses the given string
strrev(char *
string)
char txt[10]=”xyz”;
strrev(txt);
Output:zyx
strset() All characters of a string are set with strset(char * s1, char text[10]=”xyz”;
a given argument or symbol char symbol);. char symbol=’$’;
strset(text,symbol);
Output $$$
strnset()
Specified number of characters of a
string are set with a given argument or
symbol
strnset(char * s1,
char symbol,int
n);.
char text[10]=”xyz”;
char symbol=’$’;
N=2
strnset(text,symbol,n);
Output $$
strspn()
Finds up to what length two strings
are identical
int
length=strspn(char
* s1,char *s2);
char
text[10]=”beginner”;
char text1[10]=”begin”;
length=strspn(text,text1);
Output up to 5
characters are same.
strpbrk()
First occurrence of the character in a
given string is searched and then the
string is displayed starting from that
character
chp= strpbrk(char
* s1, char ch);.
char
text[10]=”beginner”;
char ch=’n’;
chp=strpbrk(text,ch);
Output is nner
Among these string library functions, the following are the most widely used. They are namely,
 strlen()
 strcpy()
 strcmp()
 strcat()
 strrev().
The strlen() function
This function determines the length of the string i.e., it counts the number of characters in that particular
string.
Syntax
int var=strlen(char* string);
where
string is the given input string
var is a integer variable in which the number of characters in the given input string is stored
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int length;
char text[10];
clrscr();
printf("enter the input string");
gets(text);
length=strlen(text);
printf("the length of the given string %s is %d",text,length);
getch();
}
Output
The strcpy() function
This function copies one string into another string.
Syntax
strcpy(char *s2, char *s1);
where,
s1 source string
s2destination String
string s1 is copied to string s2.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char src[10],dest[10];
clrscr();
printf("enter the src stringn");
gets(src);
strcpy(dest,src);
printf("nthe source string %sn",src);
printf("nthe destination string %st",dest);
getch();
}
Output
The strmp() function
Using this function, two strings are compared to determine whether they are same or different. It
compares the strings character by character. It considers the difference between upper and lower case. If
two strings are equal, it returns 0, else it returns the numeric difference between the firstnon-matching
characters.
Syntax
strcmp(char *s1,char * s2);
where s1 and s2 are the input strings to be compared.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char text[10],text1[10];
int result;
clrscr();
printf("enter the first string");
gets(text);
printf("enter the second string");
gets(text1);
result=strcmp(text,text1);
if(!result)
{
printf("Two strings are same");
}
else
{
printf("Two strings are different");
}
getch();
}
Output 1
Output 2
The strcat() function
This function concatenates one string onto the end of another string.
Syntax
strcat(char * s1,char *s2);
where string s2 is appended to the end of string 1.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char text[10],text1[10];
clrscr();
printf("enter the first string");
gets(text);
printf("enter the second string");
gets(text1);
strcat(text,text1);
printf("Two strings are CONCATENATED %s",text);
getch();
}
Output
The strrev() function
This function reverses the given string.
Syntax
strrev(char * string)
where string is the input string to be reversed
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char src[10];
clrscr();
printf("enter the src stringn");
gets(src);
printf("the reversed string=%s", strrev(src));
getch();
}
Output
Two mark questions
1. define
Example Programs
C program to find a perfect number. Perfect number is a positive number which sum of all positive
divisors excluding that number is equal to that number. For example 6 is perfect number since divisor of 6
are 1, 2 and 3. Sum of its divisor is 1 + 2+ 3 =6. Other perfect numbers are 28, 496, 8128 etc
#include<stdio.h>
int main(){
int n,i=1,sum=0;
printf("Enter a number: ");
scanf("%d",&n);
while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
printf("%d is a perfect number",i);
else
printf("%d is not a perfect number",i);
return 0;
}
Sample output:
Enter a number: 6
6 is a perfect number
Enter a number: 7
7 is not a perfect number
C program to find whether the given number is an amstrong number
Those numbers which sum of the cube of its digits is equal to that number are known as Armstrong
numbers. For example 153 since 1^3 + 5^3 + 3^3 = 1+ 125 + 9 =153. Other Armstrong numbers:
370,371,407 etc.
#include<stdio.h>
int main(){
int num,r,sum=0,temp;
printf("Enter a number: ");
scanf("%d",&num);
temp=num;
while(num!=0){
r=num%10;
num=num/10;
sum=sum+(r*r*r);
}
if(sum==temp)
printf("%d is an Armstrong number",temp);
else
printf("%d is not an Armstrong number",temp);
return 0;
}
Sample output:
Enter a number: 153
153 is an Armstrong number
C program to check whether a given number is palindrome or not
A number is called palindrome number if it is remain same when its digits are reversed. For example 121
is palindrome number. When we will reverse its digit it will remain same number i.e. 121
Palindrome numbers examples: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111,
121, 131, 141, 151, 161, 171, 181, 191 etc.
#include<stdio.h>
int main(){
int num,r,sum=0,temp;
printf("Enter a number: ");
scanf("%d",&num);
for(temp=num;num!=0;num=num/10){
r=num%10;
sum=sum*10+r;
}
if(temp==sum)
printf("%d is a palindrome",temp);
else
printf("%d is not a palindrome",temp);
return 0;
}
Sample output:
Enter a number: 1221
1221 is a palindrome
C program to check if a number is palindrome using recursion
#include<stdio.h>
int checkPalindrome(int);
int main(){
int num,sum;
printf("Enter a number: ");
scanf("%d",&num);
sum = checkPalindrome(num);
if(num==sum)
printf("%d is a palindrome",num);
else
printf("%d is not a palindrome",num);
return 0;
}
int checkPalindrome(int num){
static int sum=0,r;
if(num!=0){
r=num%10;
sum=sum*10+r;
checkPalindrome(num/10);
}
return sum;
}
Sample output:
Enter a number: 25
25 is not a palindrome
C program to print Floyd’s triangle
Floyd's triangle is a right angled-triangle using the natural numbers. Examples of floyd's triangle:
Example
1
2 3
4 5 6
7 8 9 10
#include<stdio.h>
int main(){
int i,j,r,k=1;
printf("Enter the range: ");
scanf("%d",&r);
printf("FLOYD'S TRIANGLEnn");
for(i=1;i<=r;i++){
for(j=1;j<=i;j++,k++)
printf(" %d",k);
printf("n");
}
return 0;
}
Sample output:
Enter the range: 10
FLOYD'S TRIANGLE
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
C program to print Pascal triangle using for loop
To build the pascal triangle, start with "1" at the top, then continue placing numbers below it in a
triangular pattern. Each number is build just sum of above two number, (except for the edge, which are all
‘1’ and all numbers outside the Triangle are 0's). so
#include<stdio.h>
long fact(int);
int main(){
int line,i,j;
printf("Enter the no. of lines: ");
scanf("%d",&line);
for(i=0;i<line;i++){
for(j=0;j<line-i-1;j++)
printf(" ");
for(j=0;j<=i;j++)
printf("%ld ",fact(i)/(fact(j)*fact(i-j)));
printf("n");
}
return 0;
}
long fact(int num){
long f=1;
int i=1;
while(i<=num){
f=f*i;
i++;
}
return f;
}
Sample output:
Enter the no. of lines: 8
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
A series of numbers in which each sequent number is sum of its two previous numbers is known as
Fibonacci series and each numbers are called Fibonacci numbers. So Fibonacci numbers is
Algorithm for Fibonacci series
Fn = Fn-2 + Fn-1
Example of Fibonacci series:
0 , 1 ,1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 ...
Fibonacci series in c using for loop
#include<stdio.h>
int main(){
int k,r;
long int i=0l,j=1,f;
//Taking maximum numbers form user
printf("Enter the number range:");
scanf("%d",&r);
printf("FIBONACCI SERIES: ");
printf("%ld %ld",i,j); //printing firts two values.
for(k=2;k<r;k++){
f=i+j;
i=j;
j=f;
printf(" %ld",j);
}
return 0;
}
Sample output:
Enter the number range: 15
FIBONACCI SERIES: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
C code which prints initial of any name
#include<stdio.h>
int main(){
char str[20];
int i=0;
printf("Enter a string: ");
gets(str);
printf("%c",*str);
while(str[i]!='0'){
if(str[i]==' '){
i++;
printf("%c",*(str+i));
}
i++;
}
return 0;
}
Sample output:
Enter a string: Robert De Niro
RDN
C program to find factorial using function
#include<stdio.h>
#include<conio.h>
void main()
{
int n,fact;
clrscr();
printf("enter the number for finding factorial");
scanf("%d",&n);
fact=factorial(n);
printf("factorial=%d",fact);
getch();
}
int factorial(int x)
{
int i, fact=1;
for(i=x;i>0;i--)
{
fact=fact*i;
}
return fact;
}
Output:
enter the number for finding factorial 7
factorial= 5040

More Related Content

What's hot

Conditional statement
Conditional statementConditional statement
Conditional statementMaxie Santos
 
Flow of control by deepak lakhlan
Flow of control by deepak lakhlanFlow of control by deepak lakhlan
Flow of control by deepak lakhlanDeepak Lakhlan
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)Jyoti Bhardwaj
 
itft-Decision making and branching in java
itft-Decision making and branching in javaitft-Decision making and branching in java
itft-Decision making and branching in javaAtul Sehdev
 
C language control statements
C language  control statementsC language  control statements
C language control statementssuman Aggarwal
 
If and select statement
If and select statementIf and select statement
If and select statementRahul Sharma
 
Mesics lecture 6 control statement = if -else if__else
Mesics lecture 6   control statement = if -else if__elseMesics lecture 6   control statement = if -else if__else
Mesics lecture 6 control statement = if -else if__elseeShikshak
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsIt Academy
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statementsjyoti_lakhani
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJTANUJ ⠀
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and VariablesSyed Afaq Shah MACS CP
 
Control statements in java
Control statements in javaControl statements in java
Control statements in javaManojkumar C
 
Conditional statements
Conditional statementsConditional statements
Conditional statementscherrybear2014
 
Presentation on C Switch Case Statements
Presentation on C Switch Case StatementsPresentation on C Switch Case Statements
Presentation on C Switch Case StatementsDipesh Pandey
 
Control statements
Control statementsControl statements
Control statementsCutyChhaya
 

What's hot (20)

C# conditional branching statement
C# conditional branching statementC# conditional branching statement
C# conditional branching statement
 
Conditional statement
Conditional statementConditional statement
Conditional statement
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
 
Flow of control by deepak lakhlan
Flow of control by deepak lakhlanFlow of control by deepak lakhlan
Flow of control by deepak lakhlan
 
Chap 5(decision making-branching)
Chap 5(decision making-branching)Chap 5(decision making-branching)
Chap 5(decision making-branching)
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
 
itft-Decision making and branching in java
itft-Decision making and branching in javaitft-Decision making and branching in java
itft-Decision making and branching in java
 
C language control statements
C language  control statementsC language  control statements
C language control statements
 
If and select statement
If and select statementIf and select statement
If and select statement
 
Mesics lecture 6 control statement = if -else if__else
Mesics lecture 6   control statement = if -else if__elseMesics lecture 6   control statement = if -else if__else
Mesics lecture 6 control statement = if -else if__else
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statements
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Decision making and looping
Decision making and loopingDecision making and looping
Decision making and looping
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Conditional statements
Conditional statementsConditional statements
Conditional statements
 
Presentation on C Switch Case Statements
Presentation on C Switch Case StatementsPresentation on C Switch Case Statements
Presentation on C Switch Case Statements
 
Control statements
Control statementsControl statements
Control statements
 

Similar to Chapter 4(1)

Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in CRAJ KUMAR
 
Decision Making Statement in C ppt
Decision Making Statement in C pptDecision Making Statement in C ppt
Decision Making Statement in C pptMANJUTRIPATHI7
 
Do While Repetition Structure
Do While Repetition StructureDo While Repetition Structure
Do While Repetition StructureShahzu2
 
2. Control structures with for while and do while.ppt
2. Control structures with for while and do while.ppt2. Control structures with for while and do while.ppt
2. Control structures with for while and do while.pptManojKhadilkar1
 
BSc. III Unit iii VB.NET
BSc. III Unit iii VB.NETBSc. III Unit iii VB.NET
BSc. III Unit iii VB.NETUjwala Junghare
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision ControlJayfee Ramos
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsEng Teong Cheah
 
Conditional statement in c
Conditional statement in cConditional statement in c
Conditional statement in cMuthuganesh S
 
C Programming - Decision making, Looping
C  Programming - Decision making, LoopingC  Programming - Decision making, Looping
C Programming - Decision making, LoopingMURALIDHAR R
 
Decision making and looping - c programming by YEASIN NEWAJ
Decision making and looping -  c programming by YEASIN NEWAJDecision making and looping -  c programming by YEASIN NEWAJ
Decision making and looping - c programming by YEASIN NEWAJYeasinNewaj
 
Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 

Similar to Chapter 4(1) (20)

Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
 
Decision Making Statement in C ppt
Decision Making Statement in C pptDecision Making Statement in C ppt
Decision Making Statement in C ppt
 
Do While Repetition Structure
Do While Repetition StructureDo While Repetition Structure
Do While Repetition Structure
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
C language 2
C language 2C language 2
C language 2
 
2. Control structures with for while and do while.ppt
2. Control structures with for while and do while.ppt2. Control structures with for while and do while.ppt
2. Control structures with for while and do while.ppt
 
C++ STATEMENTS
C++ STATEMENTS C++ STATEMENTS
C++ STATEMENTS
 
BSc. III Unit iii VB.NET
BSc. III Unit iii VB.NETBSc. III Unit iii VB.NET
BSc. III Unit iii VB.NET
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
Conditional statement in c
Conditional statement in cConditional statement in c
Conditional statement in c
 
C Programming - Decision making, Looping
C  Programming - Decision making, LoopingC  Programming - Decision making, Looping
C Programming - Decision making, Looping
 
Controls & Loops in C
Controls & Loops in C Controls & Loops in C
Controls & Loops in C
 
CONTROL STMTS.pptx
CONTROL STMTS.pptxCONTROL STMTS.pptx
CONTROL STMTS.pptx
 
Decision making and looping - c programming by YEASIN NEWAJ
Decision making and looping -  c programming by YEASIN NEWAJDecision making and looping -  c programming by YEASIN NEWAJ
Decision making and looping - c programming by YEASIN NEWAJ
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
Control structures in c
Control structures in cControl structures in c
Control structures in c
 
6.pptx
6.pptx6.pptx
6.pptx
 
What is Switch Case?
What is Switch Case?What is Switch Case?
What is Switch Case?
 

More from TejaswiB4

Chapter 3(1)
Chapter 3(1)Chapter 3(1)
Chapter 3(1)TejaswiB4
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)TejaswiB4
 
Chapter 1 1(1)
Chapter 1 1(1)Chapter 1 1(1)
Chapter 1 1(1)TejaswiB4
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programmingTejaswiB4
 
Chapter 1 1(1)
Chapter 1 1(1)Chapter 1 1(1)
Chapter 1 1(1)TejaswiB4
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programmingTejaswiB4
 

More from TejaswiB4 (6)

Chapter 3(1)
Chapter 3(1)Chapter 3(1)
Chapter 3(1)
 
Chapter 2(1)
Chapter 2(1)Chapter 2(1)
Chapter 2(1)
 
Chapter 1 1(1)
Chapter 1 1(1)Chapter 1 1(1)
Chapter 1 1(1)
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 
Chapter 1 1(1)
Chapter 1 1(1)Chapter 1 1(1)
Chapter 1 1(1)
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 

Recently uploaded

Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 

Recently uploaded (20)

Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 

Chapter 4(1)

  • 1. CHAPTER 4 4.1 DECISION MAKING STATEMENTS C program is a set of statements, which are normally executed sequentially in the order in which they appear. This happens when no repetitions of certain calculations are needed. But we have a number of situations where we may have to change the order of execution of statements based on certain conditions. If condition is satisfied some set of statements will be executed. Else, another set of statements will be executed. A simple analogy for decision making We are all familiar with the concept of making a decision. When driving a car, we have to make decisions all the time. When we drive up to a light, we decide if it is red to stop the car. Else we can keep on driving. So here the condition is the color of the traffic light. If red we stop else we drive as usual. Thus in every action of our life we are making decision based on some situations or conditions. C language has such decision making capacities and supports the following statements known as decision-making statements or control statements.  Simple if  if else  Nested if  Nested else-if ladder  switch 3.1.1 SIMPLE IF A simple if statement consists of a boolean expression followed by one or more statements. Syntax: if (condition/boolean expression) { Statement(s) } Flowchart
  • 2. If the condition or Boolean expression results true then the block of code inside the if statement will be executed. If Boolean expression results false then the statement or set of statements after if i.e, after the closing curly brace will be executed. If the result of boolean expression is 1 then it is assumed as true. Otherwise,the result is assumed as false. Example: Output: pass
  • 3. Mark is 60 If the variable mark is assigned a value of 40(int mark =40; in the above example), then the output is Mark is 40 Note:  More than one condition can be written inside the if statement using logical connectives &&(AND) and ||(OR).  If the body of if statement has multiple statements then we can use opening and closing braces to make it as a block. Otherwise they are not needed.  But the better practice is to envelop even a single statement within open and close braces for easing the readability. 4.1.2 IF...ELSE STATEMENT An if condition followed by else statement makes the programmer to check any condition and depending on the result of that condition they can take appropriate path. If the condition is true, then true part can be executed and the false part otherwise. Syntax if(condition/boolean expression) { True statement(s) } else { False statement(s) } Flowchart
  • 4. If the condition or Boolean expression results true then the true statements inside the if statement will be executed. If Boolean expression results false then the false statements inside the else part will be executed. Example The output will be
  • 5. pass Mark is 60 If mark is assigned a value of 40(int mark =40; in the above example), then the output will be fail Mark is 40 4.1.3 NESTED IF STATEMENT A if statement can be used within another if statement and this is called as nesting of if statements. When we want to check more than one condition at a time in a same program, nested if conditional statement can be used. Syntax if(condition) { if(condition) { statements; } else { statements; } } else { statements; } Flowchart
  • 6. The conditions are executed from top to bottom checking each condition whether it meets the conditional criteria or not. If it found the condition is true then it executes the block of associated statements of true part else it goes to next condition to execute. 4.1.4 NESTED ELSE-IF We can nest else if… else in the similar way as we have nested if statements. This is also known as else..if ladder. Syntax if(condition1) { True Statements; } else if(condition2) { Statement 1; }
  • 7. : : else if(condition n) { Statement n; } else { Default statements; } Flowchart
  • 8. Example for nested if and else..if ladder in one program Output pass & grade II 4.1.5 SWITCH STATEMENT One of the common problem that we come across nested if else and else if ladder is that problem of confusion. It occurs when no matching else for if is available. And main reason is that as the number of alternative increases the complexity of program also extremely increases. In order to overcome this, C provides a decision making statement called as switch. It is also called as multi-way decision statement. The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated with that case is executed. Syntax switch(expression){ case constant 1: body 1;
  • 9. break; case constant 2: body 2; break; case constant 3: body 3; break; default: default body; } Flowchart How it works?  Switch case checks the value of expression or a variable against the list of case constants. The expression could be integer expression or character expression.  When a match is found, the body of statements associated with that case is executed.  Each body of case constants is associated with a break statement. The break statement takes control out of the case.
  • 10.  After executing the body of case constant, the control goes to the statement after the switch statement.  When no match is found default body of statement is executed and control goes to the statement after the switch statement. Example Output: In case 4 statement next to switch statement Explanation
  • 11. Note: follow the arrow marks and number.  4 is assigned to integer variable a.  Switch statement is executed.  Case variable a is first checked against case 1, not matched hence case 2 is checked and it goes on until case constant 4 is found.  Block of code specified in 4th case is executed.  After executing it comes out of switch with the help of break statement and executes statement next to the switch statement. Rules of using switch case  Case label must be unique. Example: int a=2; switch(a) { case 1: printf(“case 1”); break; case2: printf(“case 2”); break; case 2: //not allowed printf(“case 2 again”); break; }  Case labels must end with colon. Example: case 1:  Case labels must have constants and constants expression. But it should not include variables as case labels. Allowed not allowed case ‘a’: case var:
  • 12. case 67: case num: case 1+1: case a+b:  Case labels must be integer or character. Example: case ‘a’: case 67:  Case labels should not be floating point number. Example: case 5.6:  Default label is optional and can be placed anywhere inside the switch. int a=2; switch(a) { case 1: printf(“case 1”); break; default: printf(“default block”); break; case2: printf(“case 2”); break; }  Two or more cases can share a single break. char a=’a’; switch(a) { case ‘a’: case ‘A’: printf(“case 1”); break; default: printf(“default block”); break; }  Switch can be nested i.e., switch statement within another switch statement.  Relational operators are not allowed. Example: case >15: Nested Switch Statements It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise. Syntax:
  • 13. switch(expression) { case constant 1: body1 switch(expression) { case constant 1: body 1of inner switch; break case constant 2: /* case code */ } break; case constant 2: /* case code of outer switch */ } Example: #include <stdio.h> int main () { /* local variable definition */ int a = 100; int b = 200; switch(a) { case 100: printf("This is part of outer switchn", a ); switch(b) { case 200: printf("This is part of inner switchn", a ); } } printf("Exact value of a is : %dn", a ); printf("Exact value of b is : %dn", b ); return 0; } When the above code is compiled and executed, it produces following result:
  • 14. This is part of outer switch This is part of inner switch Exact value of a is : 100 Exact value of b is : 200 4.2 BRANCHING AND LOOPING STATEMENTS Sometimes it is necessary to execute some set of statements in a program repeatedly. To handle such situations C provide looping statements. A loop is a part of code or set of statements which is executed repeatedly. A loop is always used along with a condition. The reason is that the repetition is done as long as the condition is true. A loop declaration and execution can be done in the following steps 1. checking a condition to start a loop 2. Initializing loop variable 3. Executing statements inside the loop 4. Increment or decrement of value of a loop variable. C supports the following looping statements namely,  while  do…while  for Types of Looping Statements Loops are classified normally based on the mode of checking the condition. Condition checking can be done in two ways 1) before loop and 2) after loop. Based on this loops are broadly classified into two types Entry-controlled loops Exit controlled loops Entry Controlled Loops In entry controlled loops, condition is checked before executing the loop. Example include while loop and for loop Exit Controlled Loops In exit controlled loops, the loop is executed at least once. After that only condition is checked. Example include do…while loop 4.2.1 WHILE LOOP While loop is entry controlled loop. It checks the conditions first. If the conditions are satisfied the loop is executed. Otherwise it will not execute the loop at all.
  • 16. Output 4.2.2 DO..WHILE LOOP do.. while loop is exit controlled loop. Here the body of the loop is executed at least once and then the condition is checked. If the condition is true, the loop is executed again, otherwise loop terminates (not executed, comes out of the loop) and executes the statement after the while loop. Syntax do { Statements; Increment /decrement; } while(condition); Flowchart
  • 17. Example Output Difference Between While and Do-While Looping Statements While Do…while Entry controlled loop Exit controlled loop If the condition is satisfied only the loop is executed. Otherwise it is not at all executed At least for once the loop is executed regardless of the condition. After execution, the condition is checked and if it is satisfied the loop is executed. Otherwise not. 4.2.3 FOR LOOP
  • 18. For loop is entry controlled loop. The loop is executed until the condition is satisfied. Syntax: for (initialization; condition; increment/decrement) { Body of the loop } Flowchart For loop consists of the following parts inside the brackets which are separated by semicolons: 1. First part is called initialization part to initialize the loop variable. A loop variable is the one that controls and counts the number of times the loop is executed. 2. Second part is the condition that must be satisfied for loop execution. 3. Third part is the loop variable increment or decrement. We can increment the loop variable (adding 1) by step value or we can decrement (subtracting 1) the loop variable by a step value as needed. The advantage of for loop is that all initialization, condition checking and increment or decrement can be done with the help of a single statement. Whereas in while and do..while, all these must be done as a separate statement.
  • 19. Program Output When to use for loop and while loop? If the number of iterations the loop should run is known beforehand, then use for construct. While loops are used when the number of iterations the loop should run will be determined in the future. 4.2.4 BREAK STATEMENT Break statement is used to exit out of a loop at any time. This is useful when we want a loop to stop running because a condition has been met other than the loop end condition. Syntax break;
  • 20. Example Output Explanation: Note: Follow the numbers and arrow mark 1. If the condition in for loop is satisfied, first statement in the body of the loop is executed. 2. If statement in the second line is executed. 3. If condition is true, break statement is executed. 4. Break statement terminates the loop and comes out of the loop. 5. If condition is false the control goes to the increment or decrement part of for loop. 4.2.5 CONTINUE STATEMENT Continue statement is used to skip the rest of the current loop and start from the top again while incrementing the loop variable again. Syntax
  • 21. continue; Example #include<stdio.h> #include<conio.h> void main() { int i,n; clrscr(); printf("Enter the number of elementsn"); scanf("%d",&n); for(i=1;i<=n;i++) { 1 2 printf("ni never gets printedn"); continue; printf("nValue of i:%d n",i); } getch(); } Output Explanation: Note: Follow the numbers and arrow mark 1. If the condition in for loop is satisfied, first statement in the body of the loop is executed. 2. Continue statement takes control to the increment part of for loop again and hence only ‘i never gets printed’ is displayed for 5 times. The control does not go to the statement after continue.
  • 22. 4.4 ARRAYS An array is a collection of variables of similar type of data. Arrays consist of adjacent memory locations. The lowest address refers to the first element and the highest address to the last element. We can access a particular or individual element in an array by using an index. An index is an integer enclosed in a square bracket in the array declaration followed by array name. First element is referred by index 0 and last element is referred by index array size-1. Types of Array Based on the number of subscript used in an array, two types of arrays exist namely,  Single dimensional array  Multi dimensional array
  • 23. 4.4.1 SINGLE DIMENSIONAL ARRAY An array with only one subscript is known as single dimensional array. Subscript is the value enclosed within square brackets [] following the arrayname in the syntax. Syntax datatype arrayname[subscript/size]; Where Parameter Description Datatype Type of each element of the array Arrayname Name of the array using a valid variable name Subscript or size Dimension of the array Example: int a[10]; char text[20]; float b[10]; Initializing arrays Arrays in C can be initialized one by one or using the following syntax. datatype arrayname[size]={value1,value2,……….,value n); Example: int a[5]={1,2,3,4,5};
  • 24. The number of elements in the braces {} cannot exceed the size specified within []. The elements are stored in contiguous memory location as show in the following figure 1 2 3 4 5 a[0] a[1] a[2] a[3] a[4] Accessing Array Elements Array index normally starts with 0 and hence the first element is stored in 0th index and the last element in 4th index. To access array elements use the corresponding array name with index. For example, the statement int x=a[3]; assigns the value at index 3 to variable x. Now x has the value 4. To access entire elements of an array, we can use for loop. Example Program #include<stdio.h> #include<conio.h> void main() { int a[5], i; clrscr(); printf("Enter the elements of the arrayn"); for(i=0;i<5;i++) { scanf("%d",&a[i]); } printf("nthe array elements aren"); for(i=0;i<5;i++) { printf("%dn",a[i]); } getch(); }
  • 25. Output 4.3.2 MULTIDIMENSIONAL ARRAY Arrays with more than one subscript are called as multidimensional arrays. Syntax: datatype arrayname[size1][size2]….[sizeN]; Example: int a[10][10]; and int a[10][10][10]; Two dimensional arrays Most simple form of multidimensional array is the two dimensional array which comes with two subscripts. It stores the value in the form of a matrix. The first subscript indicates “row” of a matrix and the second subscript indicates “column” of a matrix. Here in the above figure
  • 26. [0][0] means 0th row and 0th column [0][1] means 0th row and 1st column and so on Syntax: datatype arrayname[size1][size2]; Example: int a[3][3]; Initializing Two-Dimensional Arrays Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row have 4 columns. int a[3][3] = { {1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6} , /* initializers for row indexed by 1 */ {7, 8, 9} /* initializers for row indexed by 2 */ }; The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example: int a[3][3] = {1,2,3,4,5,6,7,8,9}; Accessing Two-Dimensional Array Elements An element in 2-dimensional array is accessed by using the subscripts ie. row index and column index of the array. For example: int val = a[2][3];
  • 27. The above statement will take 3rd element from the 2nd row of the array. For accessing elements from two dimensional array, we need two for loops (one for accessing row details and the other for accessing column details). Example program #include<stdio.h> #include<conio.h> void main() { int a[3][3]={1,2,3,4,5,6,7,8,9}, i,j; clrscr(); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("the value of a[%d][%d] =%dn",i,j,a[i][j]); } } getch(); } Output Applications of Array Array can be used in the following applications 1. Sorting problems 2. Performing matrix operations 3. CPU scheduling 4. Recursive Function and so on..
  • 28. Limitations of Array 1. Array is a static data type. Memory allocated once at compile time cannot be changed at run time. 2. Inserting in an array is difficult. Because before inserting an element in array, a free space must be created for which other elements are pushed one position ahead. This works faster for array of small size. But for larger size array, this operation will be time consuming and non-efficient. 3. Likewise delete operation is also difficult to be performed. 4. If large array is declared, but have less elements, then there is wastage of memory. 5. If the size of the array is n, then we can access n-1 elements. If we try to access elements after n- 1, then we will get garbage value as result. 3.4 FUNCTIONS Function is a segment that groups a number of program statements to perform specific task. A C program has at least one function main( ). Without main() function, there is technically no C program. Types of C functions Basically, there are two types of functions in C on basis of whether it is defined by user or not.  Library function  User defined function Library function Library functions are the in-built function in C programming system. Following are some of the examples for library functions in C  main() - The execution of every C program starts from this main() function.  printf() - prinf() is used for displaying output in C.  scanf() - scanf() is used for taking input in C. User defined function User defined functions are the own functions written by the programmer/user according to their requirement. Suppose, a programmer wants to find factorial of a number and as well as check whether it is prime or not in same program. Then, he/she can create two separate user-defined functions in that program: one for finding factorial and other for checking whether it is prime or not. Syntax void main() { Body of the main function
  • 29. } return_type function_name(type 1 argument 1,..,type n argument n)function declrator { //body of functionfunction body } The program given below is an example for creating a user defined function add in order to find sum of two integer numbers. Program Output Explanation The function is called and executed in the following order. Step 1: the function add is called from the main function and hence control goes to the function decalrator part of the function definition. Then the first line of the body of the function is executed. Step 2: after execution, the resultant value is returned from the called function(user defined function) to the calling function(main function). Advantages of functions/user-defined functions  User defined functions helps to decompose the large program into small segments which makes programmar easy to understand, maintain and debug.
  • 30.  If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function. Function prototype (declaration): Like variables are declared before they are being used, every function in C programming should be declared before they are used. This type of declaration are also called function prototype. Function prototype gives compiler information about function name, type of arguments to be passed and return type. Syntax return_type function_name(type1 argument1,....,type n argument n); Example In the above example int add (int , int ); is a function prototype which provides following information to the compiler: 1. name of the function is add() 2. return type of the function is int. 3. two arguments of type int are passed to function. There is no need of function prototype whenever user-definition function is written before main() function. Function call To transfer the control of the program to user-defined function, it must be called or invoked. Syntax function_name(argument 1,....argument n); Example In the above example, function call is made using statement add(a,b); from main(). After executing this statement, the control of program jumps from that statement to function definition and executes the codes inside that function. Function definition Function definition contains programming codes to perform specific task. Syntax return_type function_name(type 1 argument 1,..,type n argument n)function declrator { //body of functionfunction body } Function definition has two major components:
  • 31. 1. Function declaratory 2. Function body Function declarator is the first line of function definition. When a function is invoked from calling function, control of the program is transferred to function declarator or called function. Syntax of function declaration and declarator are almost same except, there is no semicolon at the end of declarator and function declarator is followed by function body. Function declarator is followed by body of function which is composed of statements. Passing arguments/paramters to a function Argument/parameter is piece of data(variable or a constant value) passed from the main function to the user defined function. Here the main function is called as calling function and user defined function is called as called function. Two types of variables exist namely  Local variable  Global variable Local Variable Global Variable Variable that is declared inside a function is a local variable Variable that is declared outside of all functions is a local variable Local variable can only be used in the function where it is declared A global variable can be used in all functions Arguments that are passed in calling function and arguments that are accepted in called function should have same data type. For example: in the above example program, If argument a was of integer type and b was of float type then, argument variable x should be of type integer and y should be of type float. A function can be called with or without an argument. Two types of parameters exist namely  Actual parameter-Parameter used in calling function. In the above example parameters a & b are actual parameters  Formal parameter-Parameter used in called function. In the above example parameters x & y are formal parameters.
  • 32. Return Statement Return statement is used to return a value from function definition to calling function. Syntax return (expression); OR return; Example return; return a; return (a+b); in the above example program, we use return x+y; to return the value from function definition to calling function.
  • 33. 4.4.1 TYPES OF USER DEFINED FUNCTION User defined functions in C are classified into four types namely,  Functions with no argument and no return value  Functions with no arguments and with return value  Functions with arguments and no return value  Functions with arguments and return value Functions with no argument and no return value In this type of function, no argument is passed to the user defined function from the main function and no value is also returned from the user defined function to the main function. Hence return statement is not used. Program #include<stdio.h> #include<conio.h> void add(); void main() { clrscr(); add(); getch(); } void add() { int a,b; printf("enter a nd b"); scanf("%d%d",&a,&b); printf("sum=%d",a+b); } Output
  • 34. Functions with no arguments and with return value In this type of user defined function, no argument is passed to the user defined function from the main function, but resultant value is returned to the main function. Hence return statement is needed. Program #include<stdio.h> #include<conio.h> int add(); void main() { int c; clrscr(); c=add(); printf("Sum=%d",c); getch(); } int add() { int a,b; printf("enter a nd b"); scanf("%d%d",&a,&b); return (a+b); } Output Functions with arguments and no return value In this type of user defined function, arguments are passed from main function to user defined function but no resultant value is returned to main function from the user defined function. Program #include<stdio.h> #include<conio.h>
  • 35. void add(int, int); void main() { int a,b; clrscr(); printf("enter a and b"); scanf("%d%d",&a,&b); add(a,b); getch(); } void add(int x, int y) { printf("sum=%d",x+y); } Output Functions with arguments and return value In this type of user defined function, arguments are also passed from the main function to the user defined function and result of the function is returned from the user defined function to the main function. Program #include<stdio.h> #include<conio.h> int add(int, int); void main() { int a,b,c; clrscr(); printf("enter a and b"); scanf("%d%d",&a,&b); c=add(a,b); printf("sum=%d",c); getch(); } int add(int x, int y) { return(x+y); } Output
  • 36. 4.4.2 PARAMETER PASSING While calling a function, C supports two ways of passing parameter or arguments to it namely  Pass/Call by value  Pass/Call by reference Pass/Call by value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C programming language uses call by value method to pass arguments. Program #include<conio.h> #include<stdio.h> void swap(int, int); void main() { int a,b; clrscr(); printf("enter the value of a and b"); scanf("%d%d",&a,&b); printf("noriginal value of a=%d",a); printf("noriginal value of b=%d",b); swap(a,b); printf("nafter swap a=%d",a); printf("nafter swap b=%d",b); getch(); } void swap(int x, int y) { int temp; temp=x; x=y; y=temp; printf("nINSIDE swap a=%d",x); printf("nINSIDE swap b=%d",y); } Output
  • 37. Pass/Call by reference This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument. To pass the value by reference, argument pointers are passed to the functions just like any other value. So accordingly we need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments. Program #include<conio.h> #include<stdio.h> void swap(int *, int *); void main() { int a,b; clrscr(); printf("enter the value of a and b"); scanf("%d%d",&a,&b); printf("noriginal value of a=%d",a); printf("noriginal value of b=%d",b); swap(&a,&b); printf("nafter swap a=%d",a); printf("nafter swap b=%d",b); getch(); } void swap(int * x, int * y) { int temp; temp=*x; *x=*y; *y=temp; printf("nINSIDE swap a=%d",*x); printf("nINSIDE swap b=%d",*y); } Output
  • 38. Difference between call by value and call by reference Call By Value Call By Reference Duplicate copy of original parameter is passed Actual copy of original parameter is passed If any change is done in the user defined function , it will not be reflected in main function If any change is done in the user defined function , it will reflected in main function 4.4.3 RECURSIVE FUNCTION A function that contains a call to itself is called a recursive function. There must be at least one terminating condition for a recursive function. Otherwise the recursive function will call itself infinitely. Recursive functions are very useful to solve many mathematical problems like to calculate factorial of a number, generating Fibonacci series etc. Program #include<stdio.h> #include<conio.h> void main() { int n,fact; clrscr(); printf("enter the number for finding factorial"); scanf("%d",&n); fact=factorial(n); printf("factorial=%d",fact); getch(); } int factorial(int x) { if(x==0) { return 1; } else { return x*factorial(x-1); } }
  • 39. Output Advantages  Problems can be solved in easy way  Size of the code can be reduced Disadvantages  Difficult to debug and understand the logic  Increases space complexity since recursive function consumes more memory if the depth of recursion is too large. Applications  Solving Tower of Hanoi problem  Solving Mathematical problems like finding LCM, GCD and Factorial of a given number, Generation of Fibonacci series and so on  Solving problems that have hierarchical relationship for example trees. 4.4.4 PASSING ARRAYS TO FUNCTIONS In C programming, a single array element or an entire array can be passed to a function. Also, both one- dimensional and multi-dimensional array can be passed to function as argument. Passing single element of an array to a function Single element of an array can be passed in similar manner as passing variable to a function. Program #include<stdio.h> #include<conio.h> void display(int); void main() { int a[]={1,2,3}; clrscr(); display(a[2]); getch(); } void display(int a) { printf("The element to be displayed=%d",a); }
  • 40. Output Passing entire array to the function To pass entire array as an argument to the function, just pass the name of the array as an argument(,i.e, starting address of memory area is passed as argument). Program #include<stdio.h> #include<conio.h> void display(int a[]); void main() { int a[]={1,2,3,4,5}; clrscr(); printf("display the elements of an array"); display(a); getch(); } void display(int a[]) { int i; for(i=0;i<5;i++) { printf("n%dn",a[i]); } } Output Passing Multi-dimensional Arrays to Function For passing two dimensional arrays to a function, the starting address of memory area reserved is passed as argument to function. This is similar to passing one dimensional array. Program #include<stdio.h> #include<conio.h>
  • 41. void display(int a[2][2]); void main() { int a[2][2]={1,2,3,4}; clrscr(); printf("display the elements of an array"); display(a); getch(); } void display(int a[2][2]) { int i,j; for(i=0;i<2;i++) { printf("n"); for(j=0;j<2;j++) printf("%dt",a[i][j]); } } Output 4.5 STORAGE CLASSES A storage class identifies the scope (visibility) and life time of variables, functions declared within a C program. Storage class of a variable determines the following 1. Where the variable is stored 2. Scope (visibility) of a variable 3. Default initial value of a variable (if it is not initialized). 4. Life time of a variable. Where the variable is stored Storage class determines the location of a variable it is being stored. For example, sometimes variables can be stored in memory and at times, they are stored in CPU register. Scope of a variable Scope of a variable is the visibility of the variable in the block. Visibility means accessibility i.e., up to which division or area of a program, we can access a variable. There are four types of scopes in C namely,
  • 42.  Block scope -If a variable or function has scope only within the area where it has declared then scope of variable or function is called as block scope.  Function scope -there is no difference between function block and any other blocks in c. Because, there is no modifier of storage class group existing, that has function block. Label of goto statement has function block scope. Label of particular goto statement is not visible in another function  File scope - If any variable or function has scope only within a file where it has declared then scope of variable or function is known file scope.  Program scope - If any variable or function has scope throughout the whole program, then scope of variable or function is known program scope. Default initial value of a variable Whenever a variable is declared in C, a garbage value is assigned to it automatically. This is considered as initial value of the variable. Different storage classes have different initial values. For example, global variables have initial value as 0 whereas local variables have some garbage value. Life time of a variable Lifetime of a variable is the extent to which it is active in the program and in which area of the program. It is given as Life time of a variable = time of declaration – time of variable destruction. For example, if we have declared variable inside the main function, then the variable is destroyed only when the control comes to the end of the program. 4.5.1 TYPES OF STORAGE CLASSES Four types of storage classes exist in C namely,  Auto  extern  static  register 4.5.1.1 AUTO auto storage class is the default storage class for all local variables. They are usually defined inside the function. Syntax auto datatype variable; Example auto int a;
  • 43. Features of this storage class are listed in the following table. Features Value Storage Memory Scope Local and block scope Life time Exist as long as control remains in that block Default initial value Garbage value Program #include<stdio.h> #include<conio.h> void main() { auto num=20; clrscr(); { auto num=60; printf("number=%dn", num); } printf("nnumber=%d",num); getch(); } Output Note: variable num is declared in two different blocks, hence considered as two different variables. 4.5.1.2 EXTERN extern storage class is the default storage class for all global variables. They are usually defined outside the function and are accessible to all functions in the program. A particular extern variable can be declared many times but we can initialize at only one time. extern variable cannot be initialized locally i.e. within any block either at the time of declaration or separately. If extern keyword is not used with global variables then compiler will automatically initialize with default value to extern variable. Syntax extern datatype variable; Example extern int a;
  • 44. Features of this storage class are listed in the following table. Features Value Storage Memory Scope Global and file scope Life time Exist as long as variable is running Retains value within the function Default initial value 0 Program #include<stdio.h> #include<conio.h> int num=20;/*all global variables are considered as extern and hence no need to specify the keyword extern*/ void main() { extern int num; clrscr(); printf("number=%dn",num); { extern int num; printf("number=%dn", num); } getch(); } Output Note: variable num is treated as local variable and hence considered as to have single value even though, they are declared in two different blocks. 4.5.1.3 STATIC Static variable may be either internal or external depending on where it is declared. If declared outside the function body, then it acts as either static or extern variable. If declared inside the function body, then it acts as auto variable. The contents of static variable will remain the same throughout the program. Thus using this property we can count the number of times a function is being called. Syntax static datatype variable; Example
  • 45. static int a=10; Features of this storage class is listed in the following table Features Value Storage Memory Scope Global and file scope as well as local and block scope Life time Global: Exist as long as variable is running Retains value within the function Local: Exist as long as control remains in that block Default initial value 0 Program #include<stdio.h> #include<conio.h> void main() { void f1(); clrscr(); f1(); printf("tafter first call.n"); f1(); printf("tafter second call.n"); f1(); printf("tafter third call.n"); getch(); } void f1() { static int i=0; int j=10; printf("value of i is %d and j is %d",i,j); i=i+10; getch(); } Output
  • 46. Function f1 is called for the first time and value 0 is initialized to i and 10 to j. After first call the value of k and j is printed as output. Then control transfer to the main program. At the second call value of i is not initialized because of being a static variable. Value of i and j is printed after second call and third call as output. 4.5.1.4 Register The register storage class is used to define local variables that should be stored in a register instead of memory. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions. Syntax register datatype variable; Example register int miles; Features of this storage class are listed in the following table. Features Value Storage CPU register Scope Local to the block Life time Exist as long as control remains in that block Default initial value Garbage Program #include<stdio.h> #include<conio.h> void main() { int a=10,b=20; register int c; clrscr(); c=a+b; printf("the value of %d is stored in register c", c); getch();
  • 47. } Output 4.6 STRINGS The string in C programming language is actually a one-dimensional array of characters terminated by a null character '0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. Actually, it is not compulsory to place the null character at the end of a string constant. The C compiler automatically places the '0' at the end of the string when it initializes the array. Each character occupies one byte of memory and hence the last character is always ‘0’. Thus to hold the null character at the end of the array, the size of the character array containing the string is always one more than the number of characters in the word "Hello." char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'}; Program #include<stdio.h> #include<conio.h> void main() { char greeting[6]={'H','E','L','L','O'}; clrscr(); printf(" Greetings is %s",greeting); getch(); } Output
  • 48. If size of the character array for the above example is given as exactly 5 as shown below, then some garbage value will be printed. Program #include<stdio.h> #include<conio.h> void main() { char greeting[5]={'H','E','L','L','O'}; clrscr(); printf(" Greetings is %s",greeting); getch(); } Output If the rule of array initialization is followed, then the above statement can be written as follows: char greeting[] = "Hello"; Following is the memory presentation of above defined string in C/C++: Reading and writing strings Control string ‘%s’ can be used in scanf() statement to read a string from the terminal (keyboard) as well as in printf() statement to write a string to the terminal(console or monitor). We can also use gets() and puts() as well as getchar() functions. 4.6.1 STRING FUNCTIONS
  • 49. C supports a wide range of functions that manipulate null-terminated strings. These functions are available in the header file <string.h>. If we want to use these functions, this header file can be included in the program. Function Description Syntax Example strlen() Determines the length of the string strlen(char* string) char txt[10]=”hello”; int length=strlen(txt); output is 5 strcpy() Copies one string to the another string strcpy(char *s2, char *s1); s1 source string s2destination String char text[10]=”hai”; char dest[10]; strcpy(dest,text); Output is dest=hai strncpy() Concatenates string s2 onto the end of string s1. strcpy(char *s1, char *s2, int n); s2 source string s1destination String nlength of the string to be copied char text[10]=”hai”; char dest[10]=”hello” n=2 strcpy(dest,text,2); Output is dest=hallo strcmp() Two strings are compared. Differentiate between upper and lower case. strcmp(char *s1,char * s2); char text[10]=”hai”; char dest[10]=”Hai” strcmp(dest,text); Output is strings are different stricmp() Two strings are compared. Does not differentiate between upper and lower case. stricmp(char *s1,char * s2); char text[10]=”hai”; char dest[10]=”Hai” stricmp(dest,text); Output is strings are same. strncmp() Two strings are compared up to the specified length. Differentiate between upper and lower case. strncmp(char *s1, char *s2, int n); s2 string2 s1 String1 nlength of the string to be compared char text[10]=”hai”; char dest[10]=”Hai” n=1 strncmp(dest,text); Output strings up to 1 character are different strnicmp() Two strings are compared up to the specified length. Does not differentiate between upper and lower case. strnicmp(char *s1, char *s2, int n); s2 string2 s1 String1 nlength of the string to be char text[10]=”hai”; char dest[10]=”Hai” n=2 strnicmp(dest,text); Output strings up to 2 character are different
  • 50. compared strlwr() Upper case of the string is converted to lower case strlwr(char * s) char text[10]=”ABC”; strlwr(text); output: abc strupr() Lower case of the string is converted to upper case strupr(char * s) char text[10]=”abc”; strlwr(text); output: ABC strdup() Given string is duplicated char * strdup(char * string) char text[10]=”abc”; char * txt=strdup(text); output: txt=abc strchr() First occurrence of a given character in a string is determined chp=strchr(char * String, char ch) chppointer that collects the address returned by the function char text[10]=”beginner”; char ch=’n’; chp=strchr(text,ch); Output character n is found at address 28270 strrchr() Last occurrence of a given character in a string is determined chp=strrchr(char * String, char ch) chppointer that collects the address returned by the function char text[10]=”beginner”; char ch=’n’; chp=strrchr(text,ch); Output character n is found at address 25966 strstr() Returns a pointer to the first occurrence of string s2 in string s1 chp= strstr(char * s1, char * s2);. char text[10]=”I love India”; char text1[10]=”India”; chp=strstr(text,text1); Output India is present at address 25966 strcat() String s2 is concatenated onto the end of string s1. strcat(char * s1,char *s2); char txt1[10]=”good”; char txt2[10]=”morning”; strcat(txt1,txt2); output is goodmorning strncat() String s2 is concatenated onto the end of string s1upto the specified length strcat(char * s1,char *s2,int n); nno of characters to append txt1[10]=”good”; char txt2[10]=”morning”; n=2 strcat(txt1,txt2,n); output is goodmo strrev() Reverses the given string strrev(char * string) char txt[10]=”xyz”; strrev(txt); Output:zyx strset() All characters of a string are set with strset(char * s1, char text[10]=”xyz”;
  • 51. a given argument or symbol char symbol);. char symbol=’$’; strset(text,symbol); Output $$$ strnset() Specified number of characters of a string are set with a given argument or symbol strnset(char * s1, char symbol,int n);. char text[10]=”xyz”; char symbol=’$’; N=2 strnset(text,symbol,n); Output $$ strspn() Finds up to what length two strings are identical int length=strspn(char * s1,char *s2); char text[10]=”beginner”; char text1[10]=”begin”; length=strspn(text,text1); Output up to 5 characters are same. strpbrk() First occurrence of the character in a given string is searched and then the string is displayed starting from that character chp= strpbrk(char * s1, char ch);. char text[10]=”beginner”; char ch=’n’; chp=strpbrk(text,ch); Output is nner Among these string library functions, the following are the most widely used. They are namely,  strlen()  strcpy()  strcmp()  strcat()  strrev(). The strlen() function This function determines the length of the string i.e., it counts the number of characters in that particular string. Syntax int var=strlen(char* string); where string is the given input string var is a integer variable in which the number of characters in the given input string is stored Program #include<stdio.h> #include<conio.h> #include<string.h>
  • 52. void main() { int length; char text[10]; clrscr(); printf("enter the input string"); gets(text); length=strlen(text); printf("the length of the given string %s is %d",text,length); getch(); } Output The strcpy() function This function copies one string into another string. Syntax strcpy(char *s2, char *s1); where, s1 source string s2destination String string s1 is copied to string s2. Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char src[10],dest[10]; clrscr(); printf("enter the src stringn"); gets(src); strcpy(dest,src); printf("nthe source string %sn",src); printf("nthe destination string %st",dest); getch(); } Output
  • 53. The strmp() function Using this function, two strings are compared to determine whether they are same or different. It compares the strings character by character. It considers the difference between upper and lower case. If two strings are equal, it returns 0, else it returns the numeric difference between the firstnon-matching characters. Syntax strcmp(char *s1,char * s2); where s1 and s2 are the input strings to be compared. Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char text[10],text1[10]; int result; clrscr(); printf("enter the first string"); gets(text); printf("enter the second string"); gets(text1); result=strcmp(text,text1); if(!result) { printf("Two strings are same"); } else { printf("Two strings are different"); } getch(); } Output 1
  • 54. Output 2 The strcat() function This function concatenates one string onto the end of another string. Syntax strcat(char * s1,char *s2); where string s2 is appended to the end of string 1. Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char text[10],text1[10]; clrscr(); printf("enter the first string"); gets(text); printf("enter the second string"); gets(text1); strcat(text,text1); printf("Two strings are CONCATENATED %s",text); getch(); } Output The strrev() function This function reverses the given string. Syntax
  • 55. strrev(char * string) where string is the input string to be reversed Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char src[10]; clrscr(); printf("enter the src stringn"); gets(src); printf("the reversed string=%s", strrev(src)); getch(); } Output Two mark questions 1. define Example Programs C program to find a perfect number. Perfect number is a positive number which sum of all positive divisors excluding that number is equal to that number. For example 6 is perfect number since divisor of 6 are 1, 2 and 3. Sum of its divisor is 1 + 2+ 3 =6. Other perfect numbers are 28, 496, 8128 etc #include<stdio.h> int main(){ int n,i=1,sum=0; printf("Enter a number: "); scanf("%d",&n); while(i<n){ if(n%i==0) sum=sum+i; i++;
  • 56. } if(sum==n) printf("%d is a perfect number",i); else printf("%d is not a perfect number",i); return 0; } Sample output: Enter a number: 6 6 is a perfect number Enter a number: 7 7 is not a perfect number C program to find whether the given number is an amstrong number Those numbers which sum of the cube of its digits is equal to that number are known as Armstrong numbers. For example 153 since 1^3 + 5^3 + 3^3 = 1+ 125 + 9 =153. Other Armstrong numbers: 370,371,407 etc. #include<stdio.h> int main(){ int num,r,sum=0,temp; printf("Enter a number: "); scanf("%d",&num); temp=num; while(num!=0){ r=num%10; num=num/10; sum=sum+(r*r*r); } if(sum==temp) printf("%d is an Armstrong number",temp);
  • 57. else printf("%d is not an Armstrong number",temp); return 0; } Sample output: Enter a number: 153 153 is an Armstrong number C program to check whether a given number is palindrome or not A number is called palindrome number if it is remain same when its digits are reversed. For example 121 is palindrome number. When we will reverse its digit it will remain same number i.e. 121 Palindrome numbers examples: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191 etc. #include<stdio.h> int main(){ int num,r,sum=0,temp; printf("Enter a number: "); scanf("%d",&num); for(temp=num;num!=0;num=num/10){ r=num%10; sum=sum*10+r; } if(temp==sum) printf("%d is a palindrome",temp); else printf("%d is not a palindrome",temp); return 0; } Sample output:
  • 58. Enter a number: 1221 1221 is a palindrome C program to check if a number is palindrome using recursion #include<stdio.h> int checkPalindrome(int); int main(){ int num,sum; printf("Enter a number: "); scanf("%d",&num); sum = checkPalindrome(num); if(num==sum) printf("%d is a palindrome",num); else printf("%d is not a palindrome",num); return 0; } int checkPalindrome(int num){ static int sum=0,r; if(num!=0){ r=num%10; sum=sum*10+r; checkPalindrome(num/10); } return sum;
  • 59. } Sample output: Enter a number: 25 25 is not a palindrome C program to print Floyd’s triangle Floyd's triangle is a right angled-triangle using the natural numbers. Examples of floyd's triangle: Example 1 2 3 4 5 6 7 8 9 10 #include<stdio.h> int main(){ int i,j,r,k=1; printf("Enter the range: "); scanf("%d",&r); printf("FLOYD'S TRIANGLEnn"); for(i=1;i<=r;i++){ for(j=1;j<=i;j++,k++) printf(" %d",k); printf("n"); } return 0; } Sample output: Enter the range: 10 FLOYD'S TRIANGLE 1 2 3 4 5 6 7 8 9 10
  • 60. 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 C program to print Pascal triangle using for loop To build the pascal triangle, start with "1" at the top, then continue placing numbers below it in a triangular pattern. Each number is build just sum of above two number, (except for the edge, which are all ‘1’ and all numbers outside the Triangle are 0's). so #include<stdio.h> long fact(int); int main(){ int line,i,j; printf("Enter the no. of lines: "); scanf("%d",&line); for(i=0;i<line;i++){ for(j=0;j<line-i-1;j++) printf(" "); for(j=0;j<=i;j++) printf("%ld ",fact(i)/(fact(j)*fact(i-j))); printf("n"); } return 0; } long fact(int num){ long f=1; int i=1; while(i<=num){ f=f*i; i++; }
  • 61. return f; } Sample output: Enter the no. of lines: 8 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 A series of numbers in which each sequent number is sum of its two previous numbers is known as Fibonacci series and each numbers are called Fibonacci numbers. So Fibonacci numbers is Algorithm for Fibonacci series Fn = Fn-2 + Fn-1 Example of Fibonacci series: 0 , 1 ,1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 ... Fibonacci series in c using for loop #include<stdio.h> int main(){ int k,r; long int i=0l,j=1,f; //Taking maximum numbers form user printf("Enter the number range:"); scanf("%d",&r);
  • 62. printf("FIBONACCI SERIES: "); printf("%ld %ld",i,j); //printing firts two values. for(k=2;k<r;k++){ f=i+j; i=j; j=f; printf(" %ld",j); } return 0; } Sample output: Enter the number range: 15 FIBONACCI SERIES: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 C code which prints initial of any name #include<stdio.h> int main(){ char str[20]; int i=0; printf("Enter a string: "); gets(str); printf("%c",*str); while(str[i]!='0'){ if(str[i]==' '){ i++; printf("%c",*(str+i)); } i++; } return 0;
  • 63. } Sample output: Enter a string: Robert De Niro RDN C program to find factorial using function #include<stdio.h> #include<conio.h> void main() { int n,fact; clrscr(); printf("enter the number for finding factorial"); scanf("%d",&n); fact=factorial(n); printf("factorial=%d",fact); getch(); } int factorial(int x) { int i, fact=1; for(i=x;i>0;i--) { fact=fact*i; } return fact; } Output: enter the number for finding factorial 7 factorial= 5040