0% found this document useful (0 votes)
4 views

C Program-Module 2

Uploaded by

preyasnayak19
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

C Program-Module 2

Uploaded by

preyasnayak19
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

MODULE 2

DECISION CONTROL AND LOOPING STATEMENTS

Introduction
All statements written in a program are executed from top to bottom one by one.
Control statements are used to execute/transfer the control from one part of the program to the another
depending on condition.
These statements are also called conditional statement. There are two types of control statements-

Conditional Branching Statements

Decision-making structures require that the programmer specifies one or more conditions to be evaluated or
tested by the program, along with a statement or statements to be executed if the condition is determined to
be true, and optionally, other statements to be executed if the condition is determined to be false.

C programming language assumes any non-zero and non-null values as true, and if it is either zero or
null, then it is assumed as false value.

There are the following types of conditional statements in C.


1. if the statement
2. if-else statement
3. if-else-if statement
4. switch statement
1. if statement: It is one of the simplest form of decision control statements which is frequently
used indecision making.

if (test expression)
{
statement 1;
…...............
statement n;
}
statement x;

Figure 1: Flow chart of if statement


• The if structure may have one statement or n number of statements which are enclosed within the
curly braces ({ }).
• Initially the test expression is evaluated.
• If this expression is true, the statement of the if block is executed or all the statements will be
skipped and statement x will be executed.

Example:
Write a program to print the higher number than 100.

#include <stdio.h>
void main()
{
int n;
printf("Enter a number:");
scanf("%d", &n);
printf ("The entered number %d", n);
if (n>100)
printf ("You entered a higher number");
}
In the above program, a number is accepted as an input from the user and the output is given. The
expression (n>100) is given. If the user gives a number higher than 100 then only will the message be
printed else the statement will be skipped.

2. if-else statement: There are times where we would like to write that if the expression is true an action
should be taken and if the expression is false there would be no action. We can also include an action for
both the conditions.

In such cases, we use the if-else statement.


if (expression)
{
Statement 1;
}
else
{
Statement 2;
}
statement x;

✔ If the Expression is true (or non-zero) then Statement1 will be executed; otherwise if it is false (or zero),
then Statement2 will be executed

✔ In this case either true block or false block will be executed, but not both.
✔ This is illustrated in Figure 2. In both the cases, the control is transferred subsequently to the Statement x.
Figure 2: Flow chart of if-else statement

Example:
Program to check voting eligibility

#include
<stdio.h>void
main()
{
int yr;
printf("Enter a
year:");scanf("%d",
&yr);

if (yr >=18)
{
printf("Eligible to vote...!!!!");
}
else
{
printf ("Not Eligible to vote !!!");
}
}
Output:
Enter a year: 1997
It's not a leap year...!!!
3. if-else-if statement :
• This statement works in the normal way as the if statement.
• After the first if branch the program can have many other else-if branches depending on
the expressions that need to be tested.
if (test expression 1)
{
statement block 1;
}
else if (test expression 2)
{
statement block 2;
}
....................
else
{
statement block 3;
}
statement y;

✔ If Expression1 is true, Execute statement block 1


✔ If Expression1 is false, check for Expression2, if it is true then Statement2 is executed. ✔
If Expression1 and 2 both are false, then Statement3 is executed.

Figure 3: Flow chart of if-else if statement


Example:
Program to find largest of the three numbers by using && operator.
#include
<stdio.h>void
main()
{
int n1=10, n2=30, n3=75;
if (n1>n2 && n1>n3)
printf("%d is the largest
number",n1);if(n2>n1 && n2>n3)
printf("%d is the largest number",
n2);else
printf("%d is the largest number", n3);
}

Output:
75 is the largest number.

4. Switch Statement

✔ C language provides a multi-way decision statement so that complex else-if statements can be easily
replaced by it. C language’s multi-way decision statement is called switch.
General syntax of switch statement is as follows:

switch(choice)
{
case label1: block1;
break;
case label2: block2;
break;
case label3: block-3;
break;
default: default-block;
break;
}

✔ Here switch, case, break and default are built-in C language words.
✔ If the choice matches to label1 then block1 will be executed else if it evaluates to label2 then block2 will
be executed and so on.
✔ If choice does not matches with any case labels, then default block will be executed.
✔ The choice is an integer expression or characters.
✔ The label1, label2, label3,…. are constants or constant expression evaluate to integer constants.
✔ Each of these case labels should be unique within the switch statement. block1, block2, block3, … are
statement lists and may contain zero or more statements.
✔ There is no need to put braces around these blocks. Note that case labels end with colon(:).
✔ Break statement at the end of each block signals end of a particular case and causes an exit from switch
statement.
✔ The default is an optional case when present, it will execute if the value of the choice does not match
with any of the case labels.

Figure 4: Flow chart of switch statement

Example:
Label Number Label Character

#include<stdio.h> #include<stdio.h>
#include<stdlib.h> #include<stdlib.h>
void main( ) void main( )
{ {
int ch,a,b,res; int a,b,res;
float div; char ch;
printf(“Enter two numbers:\n”); float div;
scanf(“%d%d”,&a,&b); printf(“Enter two numbers:\n”);
printf(“1.Addition\n 2.Subtraction\n scanf(“%d%d”,&a,&b);
3.Multiplication\n 4.Division\n printf(“a.Addition\n b.Subtraction\n
5.Remainder\n”); printf(“Enter your c.Multiplication\n d.Division\n
choice:\n”); e.Remainder\n”); printf(“Enter your
scanf(“%d”,&ch); choice:\n”);
switch(ch) scanf(“%c”,&ch);
{ switch(ch)
case 1: res=a+b; {
break; case ‘a’: res=a+b;
case 2: res=a-b; break;
break; case ‘b’: res=a-b;
case 3: res=a*b; break;
break; case ‘c’: res=a*b;
case 4: div=(float)a/b; break;
break; case ‘d’: div=(float)a/b;
case 5: res=a%b; break;
break; case ‘e’ : res=a%b;
default: printf(“Wrong choice!!\n”); break;
} default: printf(“Wrong choice!!\n”);
printf(“Result=%d\n”,res); }
} printf(“Result=%d\n”,res);
In this program if ch=1 case ‘1’ gets executed and if ch=2, case ‘2’ gets executed and so on.
Iterative Statements

Definition of Loop: It is a programming structure used to repeatedly carry out a particular


instruction/statement until a condition is true. Each single repetition of the loop is known as an iteration of
the loop.

Looping Statements in C execute the sequence of statements many times until the stated condition
becomes false. A loop in C consists of two parts, a body of a loop and a control statement. The control
statement is a combination of some conditions that direct the body of the loop to execute until the specified
condition becomes false. The purpose of the C loop is to repeatthe same code a number of times.
Three important components of any loop are:
1. Initialization (example: ctr=1, i=0 etc)
2. Test Condition (example: ctr<=500, i != 0 etc)
3. Updating loop control values (example: ctr=ctr+1, i =i-1)

LOOPS IN C
C language provides 3 looping structures namely:
1. while loop
2. do….while loop
3. for loop

Sr. Loop
Description
No. Type
While In while loop, a condition is evaluated before processing a body of the loop. If a condition is
1.
Loop true then and only then the body of a loop is executed.
Do-While In a do…while loop, the condition is always executed after the body of a loop. It is also called
2.
Loop an exit-controlled loop.

3. For Loop In a for loop, the initial value is performed only once, then the condition tests and compares the
counter to a fixed value after each iteration, stopping the for loop when false is returned.
i. while loop:
✔ It is a pre-test loop (also known as entry controlled loop).
✔ In the syntax given above ‘while’ is a key word and condition is at beginning of the loop.
✔ If the test condition is true the body of while loop will be executed.
✔ After execution of the body, the test condition is once again evaluated and if it is true, the body is
executed once again.
✔ This process is repeated until condition finally becomes false and control comes out of the body of the
loop.

Example: WAP to find sum of 1 to 5 using while.


#include<stdio.h>
void main()
{
int i=1, sum=0;
while (i<=5)
{
sum=sum+i;
i=i++;
}
printf(“%d”, sum);
}
ii. do…. while loop: It is a post-test loop (also called exit controlled loop) it has two keywords do and
while. The General syntax and flow chart

✔ In this loop the body of the loop is executed first and then test condition is evaluated. ✔ If the
condition is true, then the body of loop will be executed once again. This process continues as
long ascondition is true.
✔ When condition becomes false, the loop will be terminated and control comes out of the loop

Example: WAP to find sum of 1 to 5 using do… while


#include<stdio.h>
void main()
{
int i=1, sum=0;
do
{
sum=sum+i;
i=i++;
} while (i<=5)
printf(“%d”, sum);
}
iii. for loop:

✔ It is a pre test loop and also known as entry controlled loop.


✔ “for” keyword is used here.
✔ Here, the head of the for loop contains all the three components that is initialization, condition and
Updation.
General syntax:
for( initialization; test-condition; updation)
{
Statements;
}

The execution of for statement is as follows.


1. First the control variable will be initialized. (Example i=1)
2. Next the value of control variable is tested using test condition. (i<=n)
3. If the condition is true the body of the loop is executed else terminated.
4. If loop is executed then control variable will be updated (i++) then, the condition is checked again.

Flowchart:

Example: WAP to find the sum of 10 numbers using for loop.


#include<stdio.h>
void main( )
{
int i, sum=0;
for (i=1; i<=10; i++)
{
sum=sum+i;
}
printf(“%d”, sum);
}
Note: In for loops whether both i++ or ++i operations will be treated as pre-increment only.

while do… while

It is a pre test loop. It is a post test loop.

It is an entry controlled loop. It is an exit controlled loop.

The condition is at top. The condition is at bottom.

There is no semi colon at the end of while. The semi colon is compulsory at the end of while.

It is used when condition is important. It is used when process is important.

Here, the body of loop gets executed if and only if Here, the body of loop gets executed at least once
condition is true. even if condition is false.
Nested for loops

✔ A for loop inside a for loop is called Nested for loop.

#include<stdio.h>
int main()
{
int i, j;
for(i=1; i<=5; i++)
{
for(j=1; j<=3; j++)
printf("*");

printf("\n");
}

return 0;

output

***
***
***
***
***

Example 2

#include<stdio.h>
int main()
{
int i, j;
for(i=1; i<=5; i++)
{
for(j=1; j<=3; j++)
printf("%d", j);

printf("\n");
}

return 0;

output

123
123
123
123
123
Example 3

Example 2

#include<stdio.h>
int main()
{
int i, j;
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
printf("%d", j);

printf("\n");
}

return 0;

output

1
12
123
1234
12345

Note: If updation is not present in loops then, it will execute infinite times.
If initialization is not given then, program prints nothing.
Break and continue
• break and continue are unconditional control construct.

4. Break

✔ It terminates the execution of remaining iteration of loop.


✔ A break can appear in both switch and looping statements.

Syntax Example

while(condition) #include<stdio.h>
{ void main( )
Statements; {
if(condition) int i;
break; for(i=1; i<=5; i++)
Statements; {
} if(i==3)
break;
printf(“%d”, i)
}
}

OUTPUT 1 2
5. Continue

✔ It terminates only the current iteration of the loop.

✔ Continue can appear in looping statements.


Syntax Example

hile(condition) #include<stdio.h>
void main( )
{
{
Statements;
if(condition) int i;
continue; for(i=1; i<=5; i++)
Statements;
{
}
if(i==3)
continue;
printf(“%d”, i)
}
}

OUTPUT 1 2 4 5

2.4 Example Programs


1. Write a program to check whether the given number is even or odd.

#include<stdio.h>void
main()
{
int num,flag;
printf("Enter the Number");
scanf("%d",&num);
flag = (num%2)?1:0;
if(flag==0)
printf("\nEven");else
printf("\nOdd");
}
2. Write a program to determine the character entered by the user.

Function Test
isalnum(c) Is c alphanumeric character?
isalpha(c) Is c alphabetic character?
isdigit(c) Is c a digit?
islower(c) Is c a lower case letter?
isupper(c) Is c a upper case letter?
isspace(c) Is c a white case character?
ispunct(c) Is c a punctuation mark?
isprint(c) Is c a printable character?

#include<stdio.h>
#include<ctype.h> void
main( )
{
char key;
printf(“Enter any key\n”);
scanf("%c",&key);
if(isalpha(key))
printf("The entered key is a letter\n");else
if(isdigit(key))
printf("The entered key is a digit\n");else
printf("The entered key is not alphanumeric\n");
}

OUTPUT:

Enter any key Enter any key Enter any key


A 7 $
The entered key is a letter The entered key is a digit The entered key is not alphanumeric
3. Write a program to find the roots of quadratic equation.

The Quadratic Formula uses the "a", "b", and "c" from "ax2 + bx + c", where "a", "b", and "c" are just
numbers; they are the "numerical coefficients" of the quadratic equation they've given you to solve.

#include<stdio.h>
#include<math.h> void
main()
{
float a, b, c, root1, root2, rpart, ipart, disc;printf("Enter
the 3 coefficients:\n"); scanf("%f%f%f", &a,&b,&c);
if((a*b*c)==0)
{
printf("Roots cannot be Determined:\n");exit(0);
}
disc=(b*b) - (4*a*c);if(disc
== 0)
{
printf("Roots are equal\n");root1= -
b / (2*a); root2=root1;
printf ("root1 = %f \n", root1);printf
("root2 = %f \n", root2);
}
else if(disc>0)
{

printf("Roots are real and distinct\n");


root1= (-b + sqrt(disc)) / (2*a);root2= (-b
- sqrt(disc)) / (2*a); printf ("root1 = %f
\n", root1); printf ("root2 = %f \n",
root2);
}
else
{
printf("Roots are complex\n");rpart = -b
/ (2*a);
ipart = (sqrt (-disc)) / (2*a);
printf("root1 = %f + i %f \n", rpart, ipart);printf("root2
= %f - i %f \n", rpart, ipart);
}
}

Output Output Output


1 2 3
Enter the 3 coefficients: Enter the 3 coefficients: Enter the 3 coefficients:
1 2 2
2 3 2
1 2 2
Roots are equal Roots are real and equal Roots are complex
Root1= -1.000000 Root1=-0.500000 Root1=-0.500000+i
Root2= -1.000000 Root2=-2.000000 0.866025
Root2=-0.500000- i
0.866025
4. Write a program to get the triangle of numbers as a result

1
12
123
1234

#include<stdio.h>void
main( )
{
int n, i, j;
printf("Enter the number of rows\n");
scanf("%d",&n);
for(i=1 ;i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf("%d\t", j);
}
printf("\n");
}
}

5. Write a program in C to display the grade based on the marks as follows:


Marks Grades
0 to 39 F
40 to 49 E
50 to 59 D
60 to 69 C
70 to 79 B
80 to 89 A
90 to 100 O

#include<stdio.h>void
main( )
{
int marks;
printf(“Enter the marks\n”);
scanf("%d", &marks);
if(marks >= 0 && marks <= 39)
printf("F");
else if(marks >= 40 && marks <= 49)printf("E");
else if(marks >= 50 && marks <= 59)
printf("D");
else if(marks >= 60 && marks <= 69)printf("C");
else if(marks >= 70 && marks <= 79)printf("B");
else if(marks >= 80 && marks <= 89)printf("A");
else
printf("O");

6. Write a program to find the sum of natural numbers from 1 to N using awhile loop.
#include<stdio.h>void
main()
{
int n, i=1, sum=0; printf("Enter the
value of n");scanf("%d",&n);
while (i<=n)
{
sum=sum+i;i++;
}
printf("%d",sum);
}

7. WAP to find sum of odd numbers from 1 to N using do-while loop.


#include<stdio.h>void
main()
{
int n, i=1, sum=0; printf("Enter the
value of n");scanf("%d", &n);
do
{
sum=sum+i;i = i
+ 2;
} while (i<=n);
printf("Sum of odd numbers is %d", sum);
}
8. WACP to check whether a given number is even or odd using if-elsestatement.
#include<stdio.h>void
main()
{
int n;
printf("Enter a number");
scanf("%d", &n); if(n%2==0)
printf("The given number is Even\n");else
printf("The given number is Odd\n");
}

9. Write a program to check if the character entered is a vowel or not.


#include <stdio.h>void
main( )
{
char ch;
printf("Enter any character:");
scanf("%c", &ch);
switch(ch)
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
printf("%c is a vowel",ch);break;
default:
printf("%c is not a vowel", ch);
}
}
Evaluate:
1.
i=1
l : if(i >2)

printf(“saturday”);i
= i-1;
goto l;

printf(“sunday”);
Explain your result briefly.

Output Sunday
The i is initialized to 1 and in if condition when checked 1 > 2 returns false. Hence, it
doesn’t enter inside loop and just prints the Sunday.
2. Write a C program that prints the following output:

#include<stdio.h>
void main( )
{
printf(“\”I am\n”);
printf(“an\” \t
‘Engineering\n”);
printf(“student’\n”);
}
3 State the drawback of ladder if-else. Explain how do you resolve with suitable with
suitable example.

✔ If there are more than one if statement and only one else occurs, this situation is called as
dangling else problem.
✔ This problem is created when no matching else exists for every if.

Ex: if(condition1)
{
}
if(condition2)
{
}
if(condition3)
{
}
else
printf(“Dangling Problem\n”);

Solutions:

1. The first approach is to follow simple rule i.e., “Always pair on else to most recent unpaired
if the current block.”

if (condition1)
if (condition2)
if(condition3)
else
printf(“Dangling Problem\n”);

2. The second approach is a compound statement. Here, we make else to belong for the desired
if statement using brackets. (In the below example else belongs to first if statement) if
(condition1)
{
if (condition2)
if (condition3)
}
else
printf(“Dangling Problem\n”);

You might also like