Unit III_PART_I (1)
Unit III_PART_I (1)
Conditional statements
The conditional statements help to jump from one part of a program to another depending if a
particular condition is satisfied or not.
1. if statement
It is one of the most simple form of decision control statements which is frequently used in
decision making.
Syntax:
if (test expression)
{
statement 1;
…...............
statement n;
}
statement x;
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: Demonstrating an if statement
#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.
Syntax:
if (expression)
Statement 1;
else
Statement 2;
If the expression is true statement 1 will be executed and if the expression is false statement 2
will be executed.
Example: Program for leap year
#include <stdio.h>
void main()
{
int yr;
clrscr();
printf("Enter a year:");
scanf("%d", &yr);
if ((yr%4 == 0) && ((yr%100 !=0) || (yr%400==0)))
printf("It's a leap year...!!!!");
else
printf ("It's not a leap year....!!!");
}
Output:
Enter a year: 1997
It's not a leap year...!!!
3. if-else-if statement
if (test expression 1)
{
statement block 1;
}
else if (test expression 2)
{
statement block 2;
}
....................
else
{
statement block x;
}
statement y;
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 case
This case statement is a multi-way decision statement which is a simpler version of the if-else
block which evaluates only one variable.
Syntax:
switch (expression)
{
case expression 1: statement 1;
statement 2;
............
statement n;
break;
default: statement 1;
statement 2;
...........
statement n;
}
All the expressions should have a result of an integer value or the character value.
#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);
}
}
Output:
Enter any character: c
c is not a vowel.
Iterative algorithm constructs: Construction of loops, Establishing initial condition, ‘for’,
‘while’, ‘do-while’ statements, nested loops, Continue, break statements
In programming, loops are used to repeat a block of code until a specified condition is
met. C programming has three types of loops:
1. while loop
2. for loop
3. do...while loop
while loop –
The while loop enables us to execute a group of statements many times. This enables us to
express lengthy computations without writing lots of code
While loops check for the stopping condition first, and may not execute the body of the loop at
all if the condition is initially false.
In while loop, a condition is evaluated before processing a body of the loop. If a condition is
true then and only then the body of a loop is executed.
Syntax:
Loop initialization
while(loop condition or test expression )
{
Loop
body
Loop
update
}
Where the body can be either a single statement or a block of statements within
{Curly braces}.
The following code fragment computes the largest power of 2 that is less than or equal to a given
positive integer n
How while loop works?
• The while loop evaluates thecondition/ testExpression inside the parentheses ().
• Ifcondition/testExpression is true, statements inside the body of while loop are executed.
Then,condition/ testExpression is evaluated again.
• The process goes on until condition/testExpression is evaluated to false.
• If condition/testExpression is false, the loop terminates (ends).
Flowchart :
Example 1:
// Print numbers from 1 to 5
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
Here, we have initialized i to 1.
1. When i = 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed. This
prints 1 on the screen and the value of i is increased to 2.
2. Now, i = 2, the test expression i <= 5 is again true. The body of the while loop is executed again. This
prints 2 on the screen and the value of i is increased to 3.
3. This process goes on until i become 6. Then, the test expression i <= 5 will be false and the loop
terminates.
for loop :
for-loops are counter-controlled, meaning that they are normally used whenever the number of
iterations is known in advance.
It allows us even more flexibility when writing loops.
Syntax:
for (initialization expression; loop repetition condition; update expression)
{
Statements;
}
• Then, loop repetition condition is evaluated. If the condition is evaluated to false, the for loop is
terminated.
• However, if the condition is evaluated to true, statements inside the body of the for loop are
executed, and the update expression is updated.
This process goes on until the test expression is false. When the test expression is false, the loop
terminates.
Flowchart :
Example:
1. i is initialized to 1.
2. The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body of for loop is
executed. This will print the 1 (value of i) on the screen.
3. The update statement ++i is executed. Now, the value of i will be 2. Again, the test expression is
evaluated to true, and the body of for loop is executed. This will print 2 (value of i) on the
screen.
4. Again, the update statement ++i is executed and the test expression i < 11 is evaluated. This
process goes on until i becomes 11.
5. When i becomes 11, i < 11 will be false, and the for loop terminates.
do..while
The do..while loop is similar to the while loop with one important difference.
The body of do...while loop is executed at least once. Only then, the test expression is evaluated.
Syntax:
do{
body;
}while ( condition );
• The body of do...while loop is executed once. Only then, the condition is evaluated.
• If the condition is true, the body of the loop is executed again and condition is evaluated once
more.
• This process goes on until condition becomes false.
• If condition is false, the loop ends.
Flowchart:
Example:
Here, we have used a do...while loop to prompt the user to enter a number. The loop works
as long as the input number is not 0.
The do...while loop executes at least once i.e. the first iteration runs without checking the
condition. The condition is checked only after the first iteration has been executed.
So, if the first input is a non-zero number, that number is added to the sum variable and the loop
continues to the next iteration. This process is repeated until the user enters 0.
But if the first input is 0, there will be no second iteration of the loop and sum becomes 0.0.
Outside the loop, we print the value of sum.
Nested Loops
• The code inside a loop can be any valid C code, including other loops.
• Any kind of loop can be nested inside of any other kind of loop.
• for loops are frequently nested inside of other for loops, for example to produce a simple
multiplication table:
printf( "%5d", r * c );
// No newline in the middle of a row
• The limits as to how deeply loops may be nested are implementation dependent, but are usually
too high to be of any concern, except in cases of extremely complex or extremely poorly written
programs.
• break and continue are two C statements that allow us to further control flow within and out
of loops.
• break causes execution to immediately jump out of the current loop, and proceed with the
code following the loop.
• continue causes the remainder of the current iteration of the loop to be skipped, and
for execution to recommence with the next iteration.
o In the case of for loops, the incrementation step will be executed next, followed by the
condition test to start the next loop iteration.
o In the case of while and do-while loops, execution jumps to the next loop condition test.
( We have also seen break used to jump out of switch statements. Continue has no meaning
in switch statements. )
C break statement
The break statement is almost always used with if...else statement inside the loop. Syntax:
break;
How break statement works:
Example:
This program calculates the sum of a maximum of 10 numbers. Why a maximum of 10 numbers? It's
because if the user enters a negative number, the break statement is executed. This will end the for loop,
and the sum is displayed.
C continue statement
The continue statement skips the current iteration of the loop and continues with the next
iteration.
The continue statement is almost always used with the if...else statement.
Syntax:
Continue;
How continue statement works:
Example:
// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, it's not added to the result
#include <stdio.h>
int main()
{ int i;
double number, sum = 0.0;
for (i = 1; i <= 10; ++i) {
printf("Enter a n%d: ", i);
scanf("%lf", &number);
if (number < 0.0) {
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf", sum);
return 0;
}
In this program, when the user enters a positive number, the sum is calculated using sum +=
number; statement.
When the user enters a negative number, the continue statement is executed and it skips the negative
number from the calculation.
Question Bank
1. How switch case works without break statement.
2. Write and explain syntax of for loop.
3. Distinguish between while and do-while statements.
4. Write a program to print the multiplication table from 1 to n?
5. Differentiate between break and continue
6. Write a program to generate prime numbers between 1 and ‘n‘
7. Write a C program to check whether the given number is prime or not
8. Write a program to find the factorial of a given number
9. Write a program to generate ‘n‘ Fibonacci numbers
10. What is a nested loop? Write a program to display multiplications tables from 1 to n.
11. Write a program to display the following pattern(Try many other patterns like this)
*****
****
***
**
*
12. Explain nested for loop with example. Explain nested for loop with general syntax and example.
13. What do you mean by looping? Describe any two looping statements in ‘C’ programming
with examples.
14. Write short notes on: 1)Break Vs. Continue
15. Distinguish between While-Do and Do-While looping structures. Write a program in C to
calculate first 50 Fibonacci numbers using while-loop.
16. What are the different decision control and branching statements available in C? Explain about
each of them with suitable examples
17. Define Looping in C
18. List out the types of looping statements available in C ?
19. Write a C Program to print even numbers from 1 to n using while loop(try with other loop
structures also) ?
20. Write a C Program to print numbers from 1 to n using do while loop(try with other loop
structures also) ?
21. Write a C program to plot a Pascal's triangle
22. What is the output of the following program? (Try many other patterns like this)
main()
{
int i =-3, j=2, k=0, m;
m= ++i && ++j || ++k;
printf(“\n %d %d %d %d”, i , j, k, m);
}
23. Write a program using while loop to reverse the digits of the number.
24. Write a program to read age of 10 persons and count the number of persons in the age group of
60 to 70
*************Best Luck**************