0% found this document useful (0 votes)
13 views30 pages

UNIT-2 Control Structures

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views30 pages

UNIT-2 Control Structures

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Control Structures in C

➢ The statement that is used to control the flow of execution of a program is called control
structure.
➢ Types of Control Structures:
1) Sequence control structure
2) Selection control structure
3) Repetition control structure
Sequence control structure
▪ The most common and basic structure of a program.
▪ A set of instructions in sequence from top to bottom.
▪ Statements executed one after the other in the order in which they are written.
(or)
▪ It executes the statements in the order which we have specified (in sequence order). i.e.,
one by one.
▪ It can’t execute a statement more than once.
Program:
/* program to find area of a rectangle */
#include<stdio.h>
int main()
{
float a, b;
a = 10;
b = 20;
area = a*b;
printf(“area of a rectangle is %d”, area);
return 0;
}
Selection control structure
▪ The selection control structure allows one set of statements to be executed if a condition is
true and another set of actions to be executed if a condition is false.
▪ Whenever a condition is executed based on that next statement will be executed.
Program:
/* program to find given number is even or odd */
#include<stdio.h>
int main()
{
int n;
printf(“\n enter any number”);
scanf(“%d”, &n);
if(n%2==0)
printf(“%d is an even number”, n);
else
printf(“%d is an odd number”, n);
return 0;
}
Repetition control structure
▪ These are used to execute a block of statements more than once based on the condition
specified.
▪ These are also called as iterative or loops.
▪ Eg: for, while, do-while
Program:
/* program to print numbers 1 to 10*/
#include<stdio.h>
int main()
{
int i;
i= 1;
while(i<=10)
{
printf(“\n %d”, i);
i++;
}
return 0;
}
Selection statements in C
▪ These are also called as conditional/ Branching/ Decision making statements.
▪ When a group of statements are specified in a block, based on the given condition they are
going to be executed.
▪ The conditional statements help to jump from one part of the program to another depending
on whether a particular condition is satisfied or not.
▪ The decision control statements include
▪ if statement
▪ switch statement
▪ conditional operator statement
▪ goto statement
if statement
▪ The if statement is powerful decision-making statement and is used to control the flow of
execution of statements.
if(test expression)
▪ It allows the computer to evaluate the expression first and then, depending on whether the
value of the expression is ‘true’ or ‘false’, it transfers the control to a particular statement.
▪ This point of program has two paths to follow, one for the true condition and the other for
the false condition.

▪ Different forms of if statement are


▪ Simple if
▪ If-else
▪ Nested if
▪ Else if ladder
Simple if
▪ First condition will be executed.
▪ If condition is TRUE, then the statements followed by ‘if’ will be executed.
▪ If condition is FALSE, then control goes out of the if statement.
▪ Simple if statement contains only TRUE block statements.
Syntax:
if(condition)
{
statement(s);
}
next statements

Program: Example program on simple if statement


#include<stdio.h>
main()
{
int a, b;
printf(“enter any two numbers: ”);
scanf(“%d%d”, &a, &b);
if(a>b)
{
printf(“\n a is big number”);
}
Printf(“simple if statement prog”);
}
Program: Write a program to check whether the entered number is less than 10? If yes,
display the same.
#include <stdio.h>
#include <conio.h>
int main()
{
int a;
printf(“\n Enter number: ”);
scanf(“%d”,&a);
if(a<10)
printf(“\n the given number is less than 10”);
return 0;
}

If-else
▪ It contains both TRUE block statements and FALSE block statements.
▪ If the test expression is TRUE, then True- block statement(s), are executed; otherwise, the
false-block statement(s) are executed.
▪ In either case, either true-block or false-block will be executed, not both.
▪ It has two blocks. One block is for ‘if’ and it is executed when the condition is true. The
other block is of else and it is executed when the condition is false. The else statement
cannot be used without if.
▪ No multiple else statements are allowed with one if.
Syntax:
if(condition)
{
True block statement(s);
}
else
{
False block statement(s);
}
next statements
Program: Write a program by using if-else statement to check weather the given year is a leap
year or not.
#include<stdio.h>
main()
{
int year;
printf(“\n enter Year: ”);
scanf(“%d”, &year);
if(((year%4==0)&&(year%100)!=0))||(year%400)==0)
{
printf(“\n %d is a leap year”, year);
}
else
{
printf (“\n %d is not a leap year”, year);
}
}

/* Finding the given alphabet is lower case or upper case using if-else construct */
#include<stdio.h>
int main()
{
char ch;
printf(“Enter the alphabet: ”);
scanf(“%c”, &ch);
if(ch>=65 && ch<=90)
printf(“%c is upper case”,ch);
else
printf(“%c is lower case”,ch);
return 0;
}
Nested if
▪ When a series of decisions are involved, we may have to use more than one if-else statement
in nested form.
Syntax:
if(condition1)
{
if(condition2)
{
statement1;
}
else
{
statement2;
}
}
else
{
if(condition3)
{
statement3;
}
else
{
statement4;
}
}
next statements
Program: Write a program by using nested if statement to find biggest of three numbers.
#include<stdio.h>
main()
{
int a, b, c;
printf(“\n enter any three numbers: ”);
scanf(“%d%d%d”, &a, &b, &c);
if(a>b)
{
if(a>c)
{
printf(“\n a is big number);
}
else
{
printf(“\n c is big number);
}
}
else
{
if(b>c)
{
printf(“\n b is big number);
}
else
{
printf(“\n c is big number);
}
}
}

else if ladder
▪ It is used to check multiple conditions.
▪ In this kind of statement, a number of logical conditions are checked for executing various
statements.
▪ Here, if the first logical condition is true the compiler executes the block followed by first
if condition, otherwise it skips that block and checks for next logical condition followed by
else-if, if the condition is true the block of statements followed by that if condition is
executed. The process is continued until a true condition is occurred or an else block is
occurred. If all if conditions become false it executes the else block (default statement).
▪ The conditions are evaluated from top to bottom. As soon as a true condition is found, the
statement associated with it is executed and the control is transferred to the statement-x.
When all the n conditions become false, then final else containing default statement will be
executed.

Program: Write a program by using else if ladder print Distinction if marks is greater than 75,
First class if marks is greater than 60, second class if marks is greater than 50. Pass if marks is
greater than 40, and Fail if marks is less than 40.

#include<stdio.h>
main()
{
int marks;
printf(“\n enter marks: ”);
scanf(“%d”, &marks);
if(marks>=75)
printf(“\n Distinction”);
else if (marks>=60)
printf(“\n First class”);
else if (marks>=50)
printf(“\n Second class”);
else if (marks>=40)
printf(“\n Pass”);
else
printf(“\n Fail”);
}
Conditional Statement/ Expression in C
▪ It is an alternative for if-else construct.
▪ It uses the operator? and:
Syntax:
condition? expression1: expression 2;

Program: Write a program by using conditional statement to find big value among two
values.
#include<stdio.h>
main()
{
int a, b, big;
printf(“\n enter a,b values: ”);
scanf(“%d %d”, &a, &b);
big = (a>b)? a: b;
printf(“\n biggest value = %d”, big);
}

Program: Write a program by using conditional statement to find biggest of three numbers.
#include<stdio.h>
main()
{
int a, b, c, big;
printf(“\n enter a, b, c values: ”);
scanf(“%d %d %d”, &a, &b, &c);
big = ((a>b)&&(a>c))? a: ((b>c)? b: c);
printf(“\n biggest value = %d”, big);
}
(or)
#include<stdio.h>
main()
{
int a, b, c, big;
printf(“\n enter a, b, c values: ”);
scanf(“%d %d %d”, &a, &b, &c);
big = (a>b)? ((a>c): a: c): ((b>c)? b: c);
printf(“\n biggest value = %d”, big);
}

Switch statement in C

➢ It is an alternative form of else-if ladder.

➢ Switch statement in C tests the value of a variable and compares it with multiple cases.
Once the case match is found, a block of statements associated with that particular case is
executed.

➢ Each case in a block of a switch has a different name/number which is referred to as an


identifier. The value provided by the user is compared with all the cases inside the switch
block until the match is found.

Syntax:

Switch(expression)
{
case value1:
Block1 statements;
break;
case value2:
Block2 statements;
break;
:
:
:
case value-n:
Block-n statements;
break;
default:
default statements;
}
Next statements;
RULES
▪ Switch expression should be always an integer/char.
▪ Should be a gap between case & case value.
▪ Char constants should be specified with in ‘ ‘ .
▪ Case value must terminate with :
▪ Should use break at each block.
▪ Each switch contains only one default block.
Write a C program to determine whether an entered character is a vowel or not using
switch statement.
#include<stdio.h>
int main()
{
char ch;
printf(“Enter any alphabet: ”);
scanf(“%c”, &ch); // ch = getchar();
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 vowel”, ch);
break;
default:
printf(“%c is consonant”, ch);
}
return 0;
}
Program: Arithmetic operations using switch
#include<stdio.h>
int main()
{
int a, b, ch;
printf(“\n enter a, b values: ”);
printf(“\n 1. Addition \n 2. Subtraction);
printf(“\n 3. Multiplication \n 4. Division);
printf(“5. Modular Division”);
printf(“\n Emter your choice”);
scanf(“%c”, &ch);
switch(ch)
{
case 1:
printf(“The addition of %d and %d is: %d”, a, b, a+b);
break;
case 2:
printf(“The subtraction of %d and %d is: %d”, a, b, a-b);
break;
case 3:
printf(“The multiplication of %d and %d is: %d”, a, b, a*b);
break;
case 4:
printf(“The division of %d and %d is: %d”, a, b, a/b);
break;
case 5:
printf(“The modular division of %d and %d is: %d”, a, b, a%b);
break;
default:
printf(“Invalid choice, plz enter choice in between 1 to 5”);
break;
}
return 0;
}
Loop control in C
Loops:
➢ A loop is defined as a block of statements which are repeatedly executed for certain
number of times.
➢ There are mainly four parts in any loop. They are Initialization expression, Test
Expression, Body of the loop, Update expression
Initialization expression: It sets initial value for the loop counter before the statements within
the loop body start to execute.
Test Expression: It tests the condition to determine whether to execute the loop or not.
Body of loop: A set of statements which can be executed when the test condition is true.
Update expression: It increments or decrements the loop counter values such that after
appropriate iterations, test condition will result false and loop will be terminated.
There are two types of loop statements available.
1. Entry controlled loop
2. Exit controlled loop

1. Entry controlled loop:-


These loops which check the test condition at the entry level itself, if the test conditions are
not satisfied, then the body of the loop will not be executed. The entry-controlled loops are
also known as pretest loops.
The example of entry-controlled loop are while, for.
2. Exit controlled loop:-
In the exit-controlled loop, the test is performed at the end of the body of the loop and
therefore the body is executed unconditionally for the first time. The exit-controlled loops are
also known as post test loops.
The example of exit-controlled loop is do-while.
While Loop
➢ It is an entry-controlled loop.
➢ Most generally used loop.
➢ This loop can be used to iterate a part of code while the given condition remains true.

Syntax:

initialization of counter;

while(Test condition)

Body of while loop;

update counter;

Next statements;

Steps:

➢ First initialization will be executed.


➢ Test condition is evaluated.
➢ When condition is TRUE, then body of the loop is executed.
➢ Update the counter. (Increment/Decrement)
➢ Repeats steps 2 to 4 until the condition is TRUE.
➢ When test condition is FALSE, the control is transferred to next statements after the
while loop.

How while loop works?

➢ The while loop evaluates the test Expression inside the parentheses ().
➢ If test Expression is true, statements inside the body of while loop are executed. Then,
test Expression is evaluated again.
➢ The process goes on until test Expression is evaluated to false.
➢ If test Expression is false, the loop terminates (ends).
Program:
Write a program to print 1 to 10 numbers using while loop
#include<stdio.h>
int main()
{
int i;
i = 10;
while(i<=10)
{
printf(“\n %d”, i);
i++;
}
return 0;
}

do-while Loop
➢ The structure of do-while loop is similar to the while loop. The difference is that in case of
do-while loop, the expression is evaluated after the body of loop is executed. In case of
while loop, the expression is evaluated before executing body of loop.

Syntax:

initialization of counter;
do
{
Body of do-while loop;
update counter;
}
while(Test condition);
Next statements;
The working of the do-while loop is:
• When the program control first comes to the do…while loop, the body of the loop is
executed first and then the test condition/expression is checked, unlike other loops
where the test condition is checked first. Due to this property, the do…while loop is
also called exit controlled or post-tested loop.
• When the test condition is evaluated as true, the program control goes to the start of the
loop and the body is executed once more.
• The above process repeats till the test condition is true.
• When the test condition is evaluated as false, the program controls move on to the next
statements after the do…while loop.

Steps:
➢ First initialization will be executed.
➢ body of the loop is executed.
➢ Update the counter. (Increment/Decrement)
➢ Test condition is evaluated.
➢ When condition is TRUE, then Repeats steps 2 to 4 until the condition is TRUE.
➢ When test condition is FALSE, the control goes out of the loop &executes next
statements after the do-while loop.

What is d0-while Loop in C?

• The do-while in C is a loop statement used to repeat some part of the code till the
given condition is fulfilled.
• It is a form of an exit-controlled or post-tested loop where the test condition is
checked after executing the body of the loop.
• Due to this, the statements in the do-while loop will always be executed at least once
no matter what the condition is.
Program:
Write a program to print 1 to 10 numbers using do-while loop
#include<stdio.h>
int main()
{
int i;
i = 1;
do
{
printf(“\n %d”, i);
i++;
}
while(i<=10);
return 0;
}

// C Program to print multiplication table using do...while loop


#include <stdio.h>
int main()
{
int N = 5, i = 1;

do {
printf("%d\tx\t%d\t=\t%d\n", N, i, N * i);
} while (i++ < 10);

return 0;
}
for Loop
➢ It is an Entry controlled loop or pre-tested loop.
➢ It is also called as king of all loops

Syntax

for (initializationStatement; testExpression; updateStatement)

// statements inside the body of loop

}
How for loop works?
➢ The initialization statement is executed only once.
➢ Then, the test expression is evaluated. If the test expression is evaluated to false, the for
loop is terminated.
➢ However, if the test expression is evaluated to true, statements inside the body of the
for loop are executed, and the update expression is updated.
➢ Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false, the
loop terminates.
Program:

Write a program to print 1 to 10 numbers using for loop

#include <stdio.h>
int main()
{
int i;
for (i = 1; i < =10; i++)
{
printf("%d ", i);
}
return 0;
}

Nested for Loop


➢ Nested loop is nothing but the looping of statements
inside another loop
➢ Nested for loop refers to a for loop that is defined inside a
‘for’ loop
Syntax
for (initialization; condition; updation)
{
// statements inside outer loop body
for (initialization; condition; updation)
{
// statements inside inner loop body
}
// statements inside outer loop body
}
Nested While Loop

Nested while loop refers to a while loop that is defined inside a ‘while’ loop.

Syntax

while(condition)
{
while(condition)
{
// inner loop statements.
}
// outer loop statements.
}

Nested do-While Loop

Nested do-while loop refers to a do-while loop that is defined inside a ‘do-while’ loop.

Syntax

do
{
do
{
// inner loop statements.
} while(condition);
// outer loop statements.
} while(condition);
Unconditional statements in C
➢ They don’t need any condition to execute.
➢ They can transfer the control from one part of the program to another.
• goto
• break
• continue
➢ This statement does not require any condition.
➢ This is an unconditional control jump.
➢ This statement passes control anywhere in the program i.e., control is transferred to
another part of the program without testing any condition.
➢ where, label name must start with any character. Here, the label is the position where the
control is to be transferred.

Syntax:

Forward Jump Backward Jump


goto label; label:
………….… statements;
……………. …………
…………
label: goto label;
statements;

Program:-
Write a program by using goto statement.
Source Code:-
#include <stdio.h>
int main()
{
printf(“Hello my dear friend”);
goto sai;
printf(“\n How are you?”);
sai:
printf(“\nLunch Over?”);
}
Program:-
Write a program to find whether the given number is even or odd. Use goto statement.
Source Code:-
#include <stdio.h>
int main()
{
int n;
printf(“\n Enter n value”);
scanf(“%d”,&n);
if(n%2==0)
{
goto even;
}
else
{
goto odd;
}
even:
printf(“\n %d is even number”,n);
exit(0);
odd:
printf(“\n %d is odd number”,n);
return 0;
}

break statement in C
➢ break is a keyword.
➢ In C, the break statement is used to terminate the execution of the nearest enclosing
loop in which it appears.
➢ If we use break statement in any loop, when that is encountered, then it stops the loop
execution process and transfers the control to the outside of the loop.
➢ We have to use the break in any loop along with ‘if’ construct.
Syntax:
break;
while(condition 1) do for(intilialization;condition1;update)
{ { {
statements; statements; statements;
if(condition2) if(condition2) if(condition2)
{ { {
break; break; break;
} } }
statements; statements; statements;
} } while(condition 1); }
next statements; next statements; next statements;

continue statement in C

➢ continue is a keyword.
➢ Like the break statement, the continue statement can only appear in the body of the
loop.
➢ When the compiler encounters the continue statement
the rest of the statements in the loop are skipped, and
the control is unconditionally transferred to next
iteration of the loop.

while(condition 1) do for(intilialization;condition1;update)
{ { {
statements; statements; statements;
if(condition2) if(condition2) if(condition2)
{ { {
continue; continue; continue;
} } }
statements; statements; statements;
} } while(condition 1); }
next statements; next statements; next statements;
Break Continue
Keyword ‘break’ is used Keyword ‘continue’ is used
It is used to continue the next iteration in the
It is used to terminate the loop
loop
It breaks the iteration It skips the iteration
It is used in switch case and looping
It is used in looping statements only
statements
In break statement, control transfers outside It continue the statement, control remains in
the loop the same loop
5 marks
1. Develop a C program to find the largest of three integers using the ternary operator.
2. Write a C program to determine whether an entered character is a vowel or not using
switch statement.
3. Build a C program to check whether a given number is a perfect number or not.
4. Develop a C program to reverse the digits of a given positive integer using while loop.
Example: Input: 123 Output: 321
5. a) Develop a program to find the average of six subjects and display the results as
follows: Average Result
>34 & <50 Third Division
> 49 & <60 Second Division
>=60 & <75 First Division
>=75 & <=100 Distinction
If marks in any subject less than 35 Fail.
6. Build a calculator program in C language to do simple operations like addition,
subtraction, multiplication and division. Use switch statement in your program.
7. Write about dangling Else problem with an example?
8. Develop a C program to find GCD of given two numbers.
9. Develop a program to print the following sequence of numbers 1, 8, 27, 64……..
10. Develop a program to print multiplication tables from 1 to 10 except 3 and 5.
11. Develop a program to convert binary number to decimal.
12. Develop a program to check whether the given number is Armstrong or not.
13. Develop a C program to find whether the given number is a palindrome number or not.
Note: A palindrome number is a number that remains the same when digits are reversed.
For example, the number 12321 is a palindrome number, but 1451 is not a palindrome
number.
14. Develop a program to check whether the given number is prime or not .
15. Construct a program to check whether the given number is strong number or not.
Note: A number can be said as a strong number when the sum of the factorial of the
individual digits is equal to the number. For example, 145 is a strong number.
16. Develop a C program to check whether number is Perfect Square or not .
Note: A perfect square is a number that can be expressed as the product of an integer
by itself or as the second exponent of an integer. For example, 25 is a perfect square
because it is the product of integer 5 by itself, 5 × 5 = 25.
17. Construct a C Program to determine whether a given year is a Leap year or not.
Example : Test Case 1: Enter a year: 1900, 1900 is not a leap year. Test Case 2: Enter
a year: 2012, 2012 is a leap year
18. You and your three friends have decided to go for a trip by sharing the expenses of the
fuel equally. Write a C program to calculate the amount (in Rs) each of them need to
put in for the complete (both to and from) journey when mileage, amount per litre of
fuel and distance for one way is given. Sample input: Mileage of the vehicle (Km/litre):
12 Amount per litre: 65 Distance travelled one way: 96 Expected output: amount (in
Rs) each of them need to put: 260
19. Develop a program to print the following pattern:

1 2 1

1 2 3 2 1

1 2 3 4 3 2 1

20. Develop a program to print the following pattern:


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

2 marks
1. Explain significance of if statement in c
2. Explain working of continue statement.
3. Describe switch case statement with syntax
4. Describe two-way selection with an example.
5. Describe break syntax and example.
6. Explain about while loop with an exampe.
7. Describe for loop with an example.
8. Describe do-while with suitable example.
9. Compare while and do-while.
10. Compare if-else-if with switch.
11. Compare break and continue statements.
12. Explain sequence control structure.
13. Explain selection control structure.
14. Explain repetitive control structure.
15. What are different types of decision control statements.
16. What are different types of if statements.
17. Explain simple if statement.
18. Explain else if ladder.
19. Explain if-else statement.
20. Explain nested if statement.
21. Explain conditional statement in C.
22. What is a loop. And what are the main parts in loop.
23. What are the different types of unconditional statements.
24. Explain goto statement.
25. Write a program to find the given number is even or odd.

You might also like