Unit - Ii Decision Making, Branching, Looping Arrays & Strings
Unit - Ii Decision Making, Branching, Looping Arrays & Strings
Control statements are the statements which Alter the flow of execution and provide better
control to the programmer. They are useful to write better and complex programs.
Control structures are classified into three types.
1. Conditional statements or decision making statements or selection statements
2. Looping statements or Iterative statements
3. Un conditional statements or jump statements
a. The if Statement
It is used to execute an instruction or sequence/block of instruction only if a condition is true.
Difference forms of implements if-statement are:
Simple if statement
if-else statement
else if statement
i. Simple if statement
Example2
#include <stdio.h>
int main()
{
int x, y;
2
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");
scanf("%d", &y);
if (x>y)
{
printf("x is greater than y\n");
}
if (x<y)
{
printf("x is less than y\n");
}
if (x==y)
{
printf("x is equal to y\n");
}
printf("End of Program");
return 0;
}
In the above example the output depends on the user input.
Output:
ii. If-else statement: This statement is used to execute one or more statements based
on conditions. If-else statement mainly used to select one option among two options.
Operation: whenever condition is true if block statements will be executed by neglecting
else block statements and execute all the statements after the else block statements.
Syntax and flowchart
3
Example : /*Demonstration of if-else statement */
#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the
* above condition (age>=18) returns true
*/
printf("You are eligible for voting");
}
else
{
/* This statement will only execute if the
* condition specified in the "if" returns false.
*/
printf("You are not eligible for voting");
}
return 0;
}
Output:
#include <stdio.h>
int main()
4
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
printf("You are eligible for voting");
else
printf("You are not eligible for voting");
return 0;
}
5
Example program:
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 != var2)
{
printf("var1 is not equal to var2\n");
//Nested if else
if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:
iv.Else if statement
It is used in multi-way decision on several conditions.
Operation: if first condition is true, if block statements will be executed by
neglecting remaining conditions. if first condition is false it will check
second condition if it is true corresponding if block statements will be
executed, otherwise check it will check another condition.
The else...if syntax is as follows:
if(condition_1) block statement_1;
6
else if(condition_2)
block statement_2;
else if(condition_n)
block statement_n;
else
default statement;
7
Example2:
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2\n");
}
else if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else if (var2 > var1)
{
printf("var2 is greater than var1\n");
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:
main()
{ switch(ch)
char ch; {
scanf("%d%d",&a,&b); break;
scanf("%c",&ch); break;
9
case '*': c=a*b; break;
printf("%d",c); }
break; getch();
printf("%d",c);
2. LOOPING STATEMENTS:
Sometimes we require a set of statements to be executed repeatedly until a
condition is met. C supports three looping statements. They are while, do-
while and for.
Both while and for statements are called as entry-controlled loops because
they evaluate the expression and based on the value of the expression they
transfer the control of the program to a particular set of statements.
Do-while is an example of exit-controlled loop as the body of the loop will
be executed once and then the expression is evaluated. If it is non-zero value
then the body of the loop will be executed once again until the expression's
value becomes zero.
WHILE LOOP: This is an entry controlled looping statement. It is used to
repeat a block of statements until the expression evaluates to nonzero value.
Syntax:
while(test condition)
{
body of the loop
}
Flowchart:
10
It is an entry controlled loop. The condition is evaluated and if it is true then
body of loop is executed. After execution of body the condition is once again
evaluated and if it is true body is executed once again. This goes on until test
condition becomes false.
Example: /* sum of 1 to 10 numbers */
#include<stdio.h>
main()
{
inti=1, sum=0;
while(i<=10)
{
sum=sum+i;
i=i+1;
}
printf(“Total : %d”,sum);
11
In above syntax, first the block of statements is executed. At the end of loop,
while statement is executed. If the expression is evaluated to nonzero value
then program control goes to evaluate the body of a loop once again. This
process continues till expression evaluates to a zero. When it evaluates to
zero, then the loop terminates.
Example: /* display the numbers from 1 to 100*/
#include<stdio.h>
main()
{
Int i=1, sum=0;
do
{
sum=sum+i;
i=i+1;
} while(i<=10);
printf(“Total : %d”,sum);
}
FOR LOOP: This is an entry controlled looping statement. In this loop
structure, more than one variable can be initialized. One of the most
important features of this loop is that the three actions can be taken at a time
like variable initialization, condition checking and increment/decrement. The
for loop can be more concise and flexible than that of while and do-while
loops.
Syntax:
for(initialization; test-condition; increment/decrement)
{
statements;
}
Flow Chart:
12
In above syntax, the condition is checked first. If it is true, then the program
control flow goes inside the loop and executes the block of statements
associated with it. At the end of loop increment or decrement is done to
change in variable value. This process continues until test condition satisfies.
EX:
#include<stdio.h>
main()
{
Int i, sum=0;
For(i=1;i<+10;i++)
{
sum=sum+i;
}
printf(“Total : %d”,sum);
BREAK STATEMENT:
OUTPUT:1 2 3 4 5 6
CONTINUE STATEMENT:
This statement has only a limited number of uses. The rules for its use are the
same as for break, with the exception that it doesn't apply to switch
statements.C continue statement is used to skip over the rest of the current
iteration. After continue statement, the control returns to the top of the loop.
The use of continue is largely restricted to the top of loops, where a decision
has to be made whether or not to execute the rest of the body of the loop.
Exit():
The function exit() will terminate the program that calls the exit.
Ex:
#include <stdio.h>
#include <stdlib.h>
main ()
{
printf("Start of the program....\n");
ARRAYS
An array is a group of related data items that share a common name and
stored in contiguous memory locations. Ordinary variables are capable of
16
holding only one value at a time. However, there are situations in which we
would want to store more than one value at a time in a single variable.
3. Multi-dimensional arrays
17
The values to the array elements can be assigned as follows.
num[0]=35;
num[1]=40;
num[2]=20;
num[3]=57;
num[4]=19;
This would cause the array number to store the values as shown below.
18
int temp [5] = {75, 79, 82, 70, 68};
Option 4 If you do not know any data ahead of time, but you want to
initialize
19
everything to 0, just use 0 within { }.
For example:
for(i=0;i<=n;i++)
scanf(“%d”,&num[i]);
20
1./*program to create a single dimensional array & find sum of the
elements*/
#include<stdio.h>
#include <conio.h>
void main()
{
int a[10],i,n,sum;
clrscr();
printf("enter size" );
scanf("%d",&n);
sum=0;
for (i=0;i<n;i++)
{
printf("enter array element ");
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("the array elements are\n");
for (i=0;i<n;i++)
printf("%d\n",a[i]);
printf("the sum = %d\n",sum);
getch();
}
2./*program to create a single dimensional array and to find large and
small of the array elements */
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],i,n,large,small;
clrscr();
21
printf("enter size" );
scanf("%d",&n);
for (i=0;i<n;i++)
{
printf("enter array element ");
scanf("%d",&a[i]);
}
large=a[0];
small=a[0];
for (i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("array elements are\n");
for (i=0;i<n;i++)
printf("%d\n",a[i]);
printf("largest = %d\n",large);
printf("smallest = %d\n",small);
getch();
}
MULTI-DIMENSIONAL ARRAYS
23
DECLARATION OF TWO DIMENSIONAL ARRAYS
The ‘row size’ indicates maximum number of rows and ‘column size’
indicates number of columns in a row.
Example:
int a[4][3];
24
This declaration initiates the elements of first row to zero and second row to
1. The Initialization is done row by row. The above statement is equivalently
written as
int num [2][3] = {{0,0,0}, {1,1,1}};
By surrounding the elements of each row by braces we can also initialize a
two-dimensional array in the form of a matrix.
int num [2][3] = {
{0,0,0},
{1,1,1}
};
If the values are missing in an initializer, they are automatically set to zero.
For instance the statement
int num[2][3] = {
{1,1},
{2}
};
will initialize the first two elements of the first row to one, the first element
of the second row to two. And all other elements to zero. Memory map of a
two dimensional array:
int num[2][3] = {1,2,3,4,5,6};
28
STRINGS
C Strings are nothing but array of characters ended with null
character (‘\0’).
This null character indicates the end of the string.
Strings are always enclosed by double quotes. Whereas, character is
enclosed by single quotes in C.
Declaration of strings
char s[5];
29
Initialization of strings
char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};
30
Example program for displaying string:
#include <stdio.h>
main ()
{
char string[20] = "dbsGroups";
printf("The string is : %s \n", string );
getch();
}
1. Strcpy()
2. Strcmp()
3. Strcat()
4. Strlen()
5. Strlwr()
6. Strupr()
7. Strchr()
8. Strstr()
9. Strrev()
1. Strcpy()
This library function is used to copy from one string to another string.
31
Example:
main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
strcpy ( target, source ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
}
2. Strcmp()
Ex :
main()
{
char str1[20] = “cse”;
char str2[20] = “eee”
int ch;
clrscr();
ch=strcmp(str1,str2);
if(ch==0)
printf("\n the strings are equal:");
else
printf("\n the strings are not equal:");
getch();
}
3. Strcat()
This library function concatenates a string onto the end of the other string.
32
Syntax: strcat(string1,string2)
Ex :
main()
{
char str1[30]="www.cprogramming";
char str2[15]="expert.com";
clrscr();
strcat(str1,str2) :
printf(" %s ”, str1);
getch();
4. Strlen()
Syntax: strlen(string);
Ex:
#include <stdio.h>
#include <string.h>
main()
{
char name[80] = “ programming” ;
int l;
l= strlen( name );
printf("The lenght is %d", l );
}
5. Strlwr():
33
It converts string to lowercase.
Syntax: strlwr(string)
Ex:
#include <stdio.h>
#include <string.h>
main()
{
char name[80] = “ PROGRAMMING ”
strlwr( name );
printf("The name is lower case is %s", name );
}
6. Strupr()
Syntax: strupr(string)
Ex:
#include <stdio.h>
#include <string.h>
main()
{
char name[80] = “ programming”
strupr( name );
printf("The name is uppercase is %s", name );
}
7. Strchr()
34
Syntax: strchr(char string[], int c);
str -- This is the C string to be scanned.
Ex:
main()
{
char s[];
char buf [] = "This is a test";
if (s != NULL)
printf ("found a 't' at %s\n", s);
}
8. Strstr()
The strstr function returns a pointer within string2 that points to a string
identical to string1. If no such sub string exists in source a null pointer is
returned.
main()
{
char s1 [] = "My House is small";
char s2 [] = "My Car is green";
printf ("Returned String 1: %s\n", strstr (s1, "House"));
printf ("Returned String 2: %s\n", strstr (s2, "Car"));
}
9. strrev() function
35
strrev( ) function reverses a given string in C language. Syntax for
strrev( ) function is given below.
Syntax: strrev(string);
Ex:
main()
{
char name[30] = "Hello";
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
getch();
}
36