IP _C_ UNIT-2[R-23]

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

UNIT-2

What is Decision Making Statement?


In the C programming language, the program execution flow is line by line from top to bottom.
That means the c program is executed line by line from the main method. But this type of
execution flow may not be suitable for all the program solutions. Sometimes, we make some
decisions or we may skip the execution of one or more lines of code. Consider a situation, where
we write a program to check whether a student has passed or failed in a particular subject. Here,
we need to check whether the marks are greater than the pass marks or not. If marks are greater,
then we decide that the student has passed otherwise failed. To solve such kind of problems in c
we use the statements called decision making statements.

Decision-making statements are the statements that are used to verify a given condition
and decide whether a block of statements gets executed or not based on the condition
result.

In the c programming language, there are two decision-making statements they are as follows.

1. if statement
2. switch statement

if statement in c
In c, if statement is used to make decisions based on a condition. The if statement verifies the
given condition and decides whether a block of statements are executed or not based on the
condition result. In c, if statement is classified into four types as follows...

1. Simple if statement
2. if-else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)

Simple if statement
Simple if statement is used to verify the given condition and executes the block of statements
based on the condition result. The simple if statement evaluates specified condition. If it is
TRUE, it executes the next statement or block of statements. If the condition is FALSE, it skips
the execution of the next statement or block of statements. The general syntax and execution
flow of the simple if statement is as follows.

C - PROGRAMMING UNIT-2[R-23] Page 1


The if statement evaluates the test expression inside the parenthesis ().
 If the test expression is evaluated to true, statements inside the body of if are executed.
 If the test expression is evaluated to false, statements inside the body of if are not executed.
Example:-

Program :-
#include <stdio.h>
int main()
{
int n ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
{
printf("Given number is divisible by 5\n") ;
}
printf("hai hello") ;
}

C - PROGRAMMING UNIT-2[R-23] Page 2


Output 1:-
Enter any integer number: 5
Given number is divisible by 5
hai hello
Output 2:-
Enter any integer number: 6
hai hello

if-else statement
The if-else statement is used to verify the given condition and executes only one out of the two
blocks of statements based on the condition result. The if-else statement evaluates the specified
condition. If it is TRUE, it executes a block of statements (True block). If the condition is
FALSE, it executes another block of statements (False block). The general syntax and execution
flow of the if-else statement is as follows.

Example :-

C - PROGRAMMING UNIT-2[R-23] Page 3


Program :-
#include <stdio.h>
int main()
{
int n ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;
else
printf("Given number is ODD\n") ;
}
Output 1:-
Enter any integer number: 4
Given number is EVEN
Output 2:-
Enter any integer number: 21
Given number is ODD

Nested if statement
Writing a if statement inside another if statement is called nested if statement. The general syntax
of the nested if statement is as follows...
Syntax:-
if ( test condition -1)
{
//If the test condition 1 is TRUE , it will check for test condition 2
if ( test condition- 2)
{
//If the test condition 2 is TRUE thenTest condition- 2 True statements executed
}
else
{
//If the test condition- 2 is FALSE, Test condition -2 False statements executed
}
else
{
//If the test condition -1 is FALSE then Test condition -1 False statements will be executed
}

C - PROGRAMMING UNIT-2[R-23] Page 4


Flowchart:-

Program:-
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

if (number1 >= number2) {


if (number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
else
{
printf("Result: %d > %d", number1, number2);
}
}
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}
Output:-
Enter two integers: 46 45
Result: 46 > 45

C - PROGRAMMING UNIT-2[R-23] Page 5


if-else-if statement (if-else ladder)
In if-else-if ladder statement, if a condition is true then the statements defined in the if block will
be executed, otherwise if some other condition is true then the statements defined in the else-if
block will be executed, at the last if none of the condition is true then the statements defined in
the else block will be executed. There are multiple else-if blocks possible.
Syntax:-

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
---
---
else{
//code to be executed if all the conditions are false
}

Flowchat:

C - PROGRAMMING UNIT-2[R-23] Page 6


Program:-
#include <stdio.h>
int main()
{
int a, b, c ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;
if( a>=b && a>=c)
printf("%d is the largest number", a) ;
else if (b>=a && b>=c)
printf("%d is the largest number", b) ;
else
printf("%d is the largest number", c) ;
return 0;
}
Output:-

Enter any three integer numbers: 4 5 2


5 is the largest number
Switch Statement

Switch statement is a control statement that allows us to choose only one choice among the
many given choices. The expression in switch evaluates to return an integral value, which is
then compared to the values present in different cases. It executes that block of code which
matches the case value. If there is no match, then default block is executed (if present). The
switch statement is a multi-way branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
The general form of switch statement is
switch(expression)
{
case constant-expression :
statement(s);
break;
case constant-expression :
statement(s);
break;
…..
…..
default : statement(s);
}

C - PROGRAMMING UNIT-2[R-23] Page 7


Important Points about Switch Case Statements:

1. The expression provided in the switch should result in a constant value otherwise it
would not be valid.
2. Duplicate case values are not allowed.
3. The default statement is optional. Even if the switch case statement does not have a default
statement, it would run without any problem.
4. The break statement is used inside the switch to terminate a statement sequence. When a
break statement is reached, the switch terminates, and the flow of control jumps to the next
line following the switch statement.
5. The break statement is optional. If omitted, execution will continue on into the next case.
The flow of control will fall through to subsequent cases until a break is reached.
6. Nesting of switch statements are allowed, which means you can have switch statements
inside another switch. However nested switch statements should be avoided as it makes
program more complex and less readable.
Flowchart

C - PROGRAMMING UNIT-2[R-23] Page 8


Following is a simple C program to demonstrate syntax of switch.
#include <stdio.h>
int main() {
char op;
double first, second;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
printf("Enter two operands: ");
scanf("%lf %lf", &first, &second);
switch (op) {
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
// operator doesn't match any case constant
default:
printf("Error! operator is not correct");
}
return 0;
}
Output :-
Enter an operator (+, -, *, /): +
Enter two operands: 45
34
45.0 + 34.0 = 79.0

C - PROGRAMMING UNIT-2[R-23] Page 9


LOOPS IN C

Concept of Loop

You may encounter situations, when a block of code needs to be executed several number of
times. In general, statements are executed sequentially. The first statement in a function is
executed first, followed by the second, and so on. A loop statement allows us to execute a
statement or group of statements multiple times. Given below is the general form of a loop
statement in most of the programming languages –

In computer programming, a loop is a sequence of instructions that is repeated until a certain


condition is reached.
 An operation is done, such as getting an item of data and changing it, and then some
condition is checked such as whether a counter has reached a prescribed number.
 Counter not Reached: If the counter has not reached the desired number, the next
instruction in the sequence returns to the first instruction in the sequence and repeat it.
 Counter reached: If the condition has been reached, the next instruction “falls through”
to the next sequential instruction or branches outside the loop

The Infinite Loop


A loop becomes an infinite loop if a condition never becomes false. When the
conditional expression is absent, it is assumed to be true. You may have an initialization
and increment expression.

C - PROGRAMMING UNIT-2[R-23] Page 10


There are mainly two types of loops:
1. Entry Controlled loops: In this type of loops the test condition is tested before entering
the loop body. For Loop and While Loop are entry controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at
the end of loop body. Therefore, the loop body will execute at least once, irrespective of
whether the test condition is true or false. do – while loop is exit controlled loop.

WHILE LOOP
It is an entry-controlled loop. The most basic loop in C is the while loop and it is used is to
repeat a block of code. A while loop has one control expression (a specific condition) and
executes as long as the given expression is true. Here is the syntax :

while(condition)
{
Statement(s);
}
In while loop first the condition is tested; if it is false the loop is finished without executing
the statement(s). If the condition is true, then the statements are executed and the loop
executes again and again until the condition is false. Here, statement(s) may be a single
statement or a block of statements. If there is only one statement, the braces may be
omitted; however, it is good practice to always include the braces.
Flowchart:

C - PROGRAMMING UNIT-2[R-23] Page 11


Properties of while loop
 A conditional expression is used to check the condition. The statements defined inside the
while loop will repeatedly execute until the given condition fails.
 The condition will be true if it returns 0. The condition will be false if it returns any non-
zero number.
 In while loop, the condition expression is compulsory.
 Running a while loop without a body is possible.
 We can have more than one conditional expression in while loop.
 If the loop body contains only one statement, then the braces are optional.

Program :-

#include<stdio.h>
int main()
{
int num, count = 1;
printf("Enter a number :");
scanf("%d", &num);
printf("\nMultiplication table for %d is:\n\n", num);
while(count <= 10)
{
printf("%d x %d = %d\n", num, count, (num*count));
count++;
}
Output:-
Enter a number :4
Multiplication table for 4 is:
4x1=4
4x2=8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28

C - PROGRAMMING UNIT-2[R-23] Page 12


4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

Do-While loop

A do-while loop is similar to the while loop except that the condition is always executed after the
body of a loop. It is also called an exit-controlled loop.
Syntax:

do {
statements
} while (expression);

Flowchart :-

In some cases, we have to execute a body of the loop at least once even if the condition is false.
This type of operation can be achieved by using a do-while loop.

In the do-while loop, the body of a loop is always executed at least once. After the body is
executed, then it checks the condition. If the condition is true, then it will again execute the body
of a loop otherwise control is transferred out of the loop.

Similar to the while loop, once the control goes out of the loop the statements which are
immediately after the loop is executed. The critical difference between the while and do-while
loop is that in while loop the while is written at the beginning. In do-while loop, the while
condition is written at the end and terminates with a semi-colon (;)

C - PROGRAMMING UNIT-2[R-23] Page 13


Program:-

#include <stdio.h>
int main() {
double number, sum = 0;
// the body of the loop is executed at least once
do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}

Output:-
Enter a number: 25
Enter a number: 50
Enter a number: 15
Enter a number: 0
Sum = 90.00

For Loop
A for loop is a repetition control structure which allows us to write a loop that is executed a
specific number of times. The loop enables us to perform n number of steps together in one line.
The syntax of the for loop is:

for (initializationStatement; testExpression; updateStatement)


{
// statements inside the body of loop
}
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some
value, then check whether this variable is less than or greater than counter value. If statement is
true, then loop body is executed and loop variable gets updated . Steps are repeated till exit
condition comes.

C - PROGRAMMING UNIT-2[R-23] Page 14


 Initialization Expression: In this expression we have to initialize the loop counter to some
value. for example: int i=1;
 Test Expression: In this expression we have to test the condition. If the condition evaluates
to true then we will execute the body of loop and go to update expression otherwise we will exit
from the for loop. For example: i <= 10;
 Update Expression: After executing loop body this expression increments/decrements the
loop variable by some value. for example: i++;

Flowchart :-

Program:-
#include <stdio.h>
int main() {
int n, i, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i) {
sum += i;
}
printf("Sum = %d", sum);
return 0;
}

C - PROGRAMMING UNIT-2[R-23] Page 15


Output:-
Enter a positive integer: 20
Sum = 210

Nested For Loop in C

Using a for loop within another for loop is said to be nested for loop. In nested for loop one or
more statements can be included in the body of the loop. In nested for loop, the number of
iterations will be equal to the number of iterations in the outer loop multiplies by the number of
iterations in the inner loop.

Syntax
The syntax for a nested for loop statement in C is as follows −
for ( init; condition; increment ) {

for ( init; condition; increment ) {


statement(s);
}
statement(s);
}

Program :-
#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
scanf("%d",&n);
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}

C - PROGRAMMING UNIT-2[R-23] Page 16


Output :-

Enter the value of n : 4


1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40

Multiple initialization inside for Loop in C


We can have multiple initialization in the for loop
1. Initializing two variables in single for loop is possible. Note: both are separated by
comma (,).
2. It has two test conditions joined together using AND (&&) logical operator. Note: You
cannot use multiple test conditions separated by comma, you must use logical operator
such as && or || to join conditions.
3. It has two variables in increment part. Note: Should be separated by comma.

Example:-

for (i=1,j=1;i<10 && j<10; i++, j++)

Break Statement

The break is a keyword in C which is used to bring the program control out of the loop. The
break statement is used inside loops or switch statement. The break statement breaks the loop
one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. The break statement in C can be used in the following two scenarios:

 With switch case


 With loop

Program:-

#include <stdio.h>
int main()
{
int num = 5;
while (num > 0)
{
if (num == 3)

C - PROGRAMMING UNIT-2[R-23] Page 17


break;
printf("%d\n", num);
num--;
}
}

Output:-
5
4

Continue Statement
The continue statement in C programming works somewhat like the break statement. Instead of
forcing termination, it forces the next iteration of the loop to take place, skipping any code in
between.
For the for loop, continue statement causes the conditional test and increment portions of the
loop to execute. For the while and do...while loops, continue statement causes the program
control to pass to the conditional tests.
Syntax
The syntax for a continue statement in C is as follows –
continue;

Flow Diagram

C - PROGRAMMING UNIT-2[R-23] Page 18


Program:-

#include<stdio.h>
int main(){
int i=1;//initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++){
if(i==5){//if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}//end of for loop
return 0;
}
Output:-
1
2
3
4
6
7
8
9
10

Goto statement
Goto statement in C is a jump statement that is used to jump from one part of the code to any
other part of the code in C. Goto statement helps in altering the normal flow of the program
according to our needs. This is achieved by using labels.

Syntax of goto Statement

goto label;
... .. ...
... .. ...
label:
statement;

 The above statement jumps the execution control of the program to the line
where label_name is used.
 We need to always use : (colon) after the label_name

C - PROGRAMMING UNIT-2[R-23] Page 19


 Each label_name has to be unique in the scope where it has been defined and cannot be a
reserved word, just like in variables.

Two Styles of goto Statement


There are two different styles of implementing goto statements

Style 1: Transferring the Control from Down to the Top


In this style, the control is transferred to a part of the program which is above the goto statement.
This results in a kind of loop in the program.

Style 2: Transferring the control from top to down

In this case, the label has been defined below the goto statement. Hence, the statements between
the goto statement and the label declaration are skipped.

C - PROGRAMMING UNIT-2[R-23] Page 20


Example:-

#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}

Output:
Enter the number whose table you want to print?10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

While loop examples:-

1. Program to Enter a number and print the Fibonacci series up to that number using
a while loop

#include <stdio.h>
int main ()
{
int i, n, j, k;
printf ("Enter a Number : ");
scanf ("%d", &n);
i = 0;
j = 1;
printf ("%d %d ", i, j);
k = i + j;

C - PROGRAMMING UNIT-2[R-23] Page 21


while (k <= n)
{
printf (" %d", k);
i = j;
j = k;
k = i + j;
}
return 0;
}

Output:-
Enter a Number : 10
01 12358

2. Given number is palingrom or not


#include <stdio.h>
int main() {
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;

// reversed integer is stored in reversed variable


while (n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
// palindrome if orignal and reversed are equal
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);

return 0;
}
Output:-
Enter an integer: 153
153 is not a palindrome.

C - PROGRAMMING UNIT-2[R-23] Page 22


3. GCD of two numbers
#include <stdio.h>
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);

while(n1!=n2)
{
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
printf("GCD = %d",n1);

return 0;
}

Output:-
Enter two positive integers: 81
153
GCD = 9

For loop examples:-

1. Program on perfect no
If the sum of all factors is equal to that number then it is called a perfect number.
#include <stdio.h>
int main()
{
int n, i, sum = 0;
printf("\nenter a number ");
scanf("%d", &n);
for(i = 1; i<= n/2; i++)
{
if(n % i == 0)
sum = sum + i;
}

C - PROGRAMMING UNIT-2[R-23] Page 23


if (sum == n && n != 0)
printf("it is a perfect number");
else
printf("it is not a perfect number");
return 0;
}

Output:-
enter a number 28
it is a perfect number

2. Program to check whether a number is Armstrong no or not

If the sum of all individual cube values is equal to that number then it is called the Armstrong
number.

#include <stdio.h>
int main()
{
int n, rem, temp, sum = 0;
printf("\nEnter a number : ");
scanf("%d", &n);
for(temp = n; temp != 0;)
{
rem = temp % 10;
sum = sum + (rem* rem* rem);
temp = temp /10;
}
if (sum == n && n != 0)
printf("It is an Armstrong number");
else
printf("It is not an Armstrong number");
return 0;
}

Output:
Enter a number : 153
It is an Armstrong number

C - PROGRAMMING UNIT-2[R-23] Page 24


3. Program to enter a number and check whether it is a prime number or not

The number which is divisible by 1 and itself is called a prime number.

#include <stdio.h>
int main()
{
int n, i;
printf("\nEnter a number : ");
scanf("%d", &n);
for(i = 2; i < n; i++)
{
if(n % i == 0)
break;
}
if (i == n && n >= 2)
printf("It is a prime number");
else
printf("It is not a prime number");
return 0;
}

Output:-
Enter a number : 7
It is a prime number

Nested for Example:-

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

C - PROGRAMMING UNIT-2[R-23] Page 25


}
printf("\n");
}
}
Output:-
Enter the no of rows:5

1
22
333
444
55555

2.
#include<stdio.h>
main()
{
int i,j,n;
printf("Enter the no of rows:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);

}
printf("\n");
}
}
Output:-
Enter the no of rows:5
1
12
123
1234
12345

C - PROGRAMMING UNIT-2[R-23] Page 26

You might also like