C Programming 2
C Programming 2
&
LOOP CONTROL
&
PROGRAMS
default:
code to be executed if all cases are not matched;
}
SWITCH CASE STATEMENT
• Rules for switch statement in C language • Functioning of switch case statement
• The switch expression must be of an integer or character type. • First, the integer expression specified in the switch statement is evaluated.
• The case value must be an integer or character constant. • Secondly this value is then matched one by one with the constant values given in the
different cases.
• The case value can be used only inside the switch statement. • If a match is found, then all the statements specified in that case are executed along
• The expression (after switch keyword) must yield an integer value i.e with the all the cases present after that case including the default statement.
the expression should be an integer or a variable or an expression that • If the matched case contains a break statement, then all the cases present after that
evaluates to an integer. will be skipped, and the control comes out of the switch.
• Otherwise, all the cases following the matched case will be executed.
• The case label values must be unique. • default case is executed when none of the mentioned case matches
• The case label must end with a colon(:) the switch expression. The default case can be placed anywhere in the switch case.
Even if we don't include the default case, switch statement works.
• The next line, after the case statement, can be any valid C statement. • No two cases can have similar values
• The break statement in switch case is not must. It is optional. • Let's see a simple example of c language switch statement.
• If there is no break statement found in the case, all the cases will be
executed present after the matched case. It is known as fall #include<stdio.h>
through the state of C switch statement. int main(){
int number=0;
• Let's try to understand it by the examples. We are assuming that there printf("enter a number:");
are following variables. scanf("%d",&number);
int x,y,z; switch(number){
char a,b; case 10:
float f; printf("number is equals to 10");
break;
Valid Switch Invalid Switch Valid Case Invalid Case case 50:
printf("number is equal to 50");
break; Output
case 100: enter a number:4
switch(x) switch(f) case 3; case 2.5; printf("number is equal to 100"); number is not equal to 10, 50 or 100
break; enter a number:50
switch(x>y) switch(x+2.5) case 'a'; case x; default: number is equal to 50
printf("number is not equal to 10, 50 or 100");
switch(a+b-2) case 1+2; case x+2; }
return 0;
switch(func(x,y)) case 'x'>'y'; case 1,2,3; }
SWITCH CASE STATEMENT
• C Switch statement is fall-through • Nested switch case statement
• We can use as many switch statement as we want inside a switch statement. Such type of
• In C language, the switch statement is fall through; it means if we don't use a statements is called nested switch case statements.
break statement in the switch case, all the cases after the matching case will be
• Nesting of switch statements are allowed, which means you can have switch statements inside
executed.
another switch block.
• Let's try to understand the fall through state of switch statement by the example • However, nested switch statements should be avoided as it makes the program more complex
given below. and less readable.
#include<stdio.h> • Consider the following example.
• .
int main(){
int number=0; #include <stdio.h>
printf("enter a number:"); int main () {
scanf("%d",&number); int i = 10;
switch(number){ int j = 20;
case 10: switch(i) {
printf("number is equal to 10\n"); case 10:
case 50: printf("the value of i evaluated in outer switch: %d\n",i);
printf("number is equal to 50\n"); case 20:
case 100: switch(j) {
printf("number is equal to 100\n"); case 20:
default: printf("The value of j evaluated in nested switch: %d\n",j);
printf("number is not equal to 10, 50 or 100"); }
} }
Output
return 0; printf("Exact value of i is : %d\n", i );
} enter a number:10
printf("Exact value of j is : %d\n", j );
number is equal to10
number is equal to 50 return 0;
number is equal to 100 }
number is not equal to 10, 50 or 100
Output
the value of i evaluated in outer switch: 10
The value of j evaluated in nested switch: 2
0
Exact value of i is : 10
Exact value of j is : 20
if-else vs switch
• Let's summarize the differences between if – else and switch in a tabular form.
If-else switch
Definition Depending on the condition in the 'if' statement, The user will decide which statement is to be executed.
'if' and 'else' blocks are executed.
Expression It contains either logical or equality expression. It contains a single expression which can be either a character or integer
variable.
Evaluation It evaluates all types of data, such as integer, It evaluates either an integer, or character.
floating-point, character or Boolean.
Sequence of First, the condition is checked. If the condition is It executes one case after another till the break keyword is not found, or
execution true then 'if' block is executed otherwise 'else' the default statement is executed.
block
Default If the condition is not true, then by default, else If the value does not match with any case, then by default, default
execution block will be executed. statement is executed.
Editing Editing is not easy in the 'if-else' statement. Cases in a switch statement are easy to maintain and modify. Therefore,
we can say that the removal or editing of any case will not interrupt the
execution of other cases.
Speed If there are multiple choices implemented If we have multiple choices then the switch statement is the best option as
through 'if-else', then the speed of the execution the speed of the execution will be much higher than 'if-else'.
will be slow.
LOOP CONTROL STATEMENTS
• The looping can be defined as repeating the same process multiple times until a specific condition satisfies.
• The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of
writing the same code again and again, we can repeat the same code for a finite number of times.
• Statements with which when a block of code needs to be executed several number of times.
• Advantage with looping statement
• Reduce length of Code
• Take less memory space.
• Burden on the developer is reducing.
• Time consuming process to execute the program is reduced.
• Types of C Loops
• There are three types of loops in C language that is given below:
• do while
• while
• for
C do...while Loop
• 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.
• A do while loop is a control flow statement that executes a
block of code at least once, and then repeatedly executes
the block, or not, depending on a given condition at the
end of the block (in while).
• When use do..while Loop
• When we need to repeat the statement block at least 1
time then we use do-while loop.
• The syntax of the do...while loop is:
do
{ // statements inside the body of the loop
}
while (testExpression);
• How do...while loop works? Flow Chart of
• The body of do...while loop is executed once. Only then, the do….while Loop
test expression is evaluated.
• If the test expression is true, the body of the loop is executed
again and the test expression is evaluated.
• This process goes on until the test expression becomes false.
• If the test expression is false, the loop ends.
C do...while Loop
• Example : do...while loop • While vs do..while loop in C
• Using while loop:
#include <stdio.h>
int main()
// Program to add numbers until the user enters zero {
int i=0;
while(i==1)
#include <stdio.h> { printf("while vs do-while"); }
int main() printf("Out of loop");
}
{
double number, sum = 0;
Output:
// the body of the loop is executed at least once Out of loop
do
{
printf("Enter a number: "); • Same example using do-while loop
scanf("%lf", &number); #include <stdio.h>
sum += number; int main()
} { int i=0;
while(number != 0.0); OUTPUT
Enter a number: 1.5 do { printf("while vs do-while\n");
Enter a number: 2.4 }
printf("Sum = %.2lf",sum); while(i==1);
Enter a number: -3.4
Enter a number: 4.2 printf("Out of loop");
return 0; Enter a number: 0 }
} Sum = 4.70
Output:
while vs do-while
Out of loop
Working:
Here, Expression1 is the condition to be evaluated. If the
condition (Expression1) is True then Expression2 will be
executed and the result will be returned.
Otherwise, if the condition (Expression1) is false
then Expression3 will be executed and the result will be
returned.
Conditional OperatorVS if then…else
Conditional Operator if then…else
• Programmers use the ternary operator for decision making in • if-else statement’s short hand way is ternary operator.
place of longer if and else conditional statements. • Here’s a simple decision-making example using if and else:
Syntax
condition ? value_if_true : value_if_false int a = 10, b = 20, c;
if (a < b) { c = a; }
• The ternary operator take three arguments: else { c = b; } printf("%d", c);
• The first is a comparison argument • This example takes more than 10 lines, but that isn’t necessary. We
• The second is the result upon a true comparison
• The third is the result upon a false comparison.
can write the above program in just 3 lines of code using a ternary
operator.
int a = 10, b = 20, c; • Nested if-else statements just like the following code:
c = (a < b) ? a : b; printf("%d", c);
int a = 1, b = 2, ans;
• c is set equal to a, because the condition a < b was true. if (a == 1)
• Remember that the arguments value_if_true and value_if_false must be { if (b == 2)
of the same type, and they must be simple expressions rather than full { ans = 3; }
statements. else { ans = 5; }
} else { ans = 0; } printf ("%d\n", ans);
• Here's the nested if- else code can be rewritten using a nested
ternary operator:
Here output will be 3
int a = 1, b = 2, ans;
ans = (a == 1 ? (b == 2 ? 3 : 5) : 0);
printf ("%d\n", ans);
#include <stdio.h>
int main ()
{
int i, j;
for(i = 2; i<100; i++)
{
for(j = 2; j <= (i/j); j++)
{
if(!(i%j))
break;
// if factor found, not prime
if(j > (i/j))
printf("%d is prime\n", i);
}
}
return 0;
}
INFINITE LOOP
• The Infinite Loop
• A loop becomes an infinite loop if a condition never becomes false.
• The for loop is traditionally used for this purpose.
• Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the
conditional expression empty.
#include <stdio.h>
int main ()
{
for( ; ; )
{ printf("This loop will run forever.\n");
}
return 0;
}
• When the conditional expression is absent, it is assumed to be true. We may have an initialization and increment expression, but
C programmers more commonly use the for(;;) construct to signify an infinite loop.
• We can terminate an infinite loop by pressing Ctrl + C keys.
C Program to Reverse a Number (for loop)
Reverse an Integer
C program to reverse a number using for loop
#include <stdio.h>
int main()
{
int n, reverse_Number = 0,
int rem,Original_number=0;
printf("Enter a number to get reverse number ");
scanf("%d", &n);
Original_number=n;
for(;n != 0;)
{
rem = n%10;
reverse_Number = reverse_Number*10 + rem;
n /= 10;
}
printf("Reversed Number of %d is = %d",Original_number,reverse_Number);
getch();
}
Input: num
(1) Initialize rev_num = 0
(2) Loop while num > 0
(a) Multiply rev_num by 10 and add remainder
of num
divide by 10 to rev_num
rev_num = rev_num*10 + num%10;
(b) Divide num by 10
(3) Return rev_num
C Program to Reverse a Number
• Example:
num = 4562
rev_num = 0
• rev_num = rev_num *10 + num%10 = 2
num = num/10 = 456
• rev_num = rev_num *10 + num%10 = 20 + 6 = 26
num = num/10 = 45
• rev_num = rev_num *10 + num%10 = 260 + 5 = 265
num = num/10 = 4
• rev_num = rev_num *10 + num%10 = 265 + 4 = 2654
num = num/10 = 0
C Program to Reverse a Number (while loop)
• Reverse an Integer #include <stdio.h>
• This program takes an integer input from the int main() {
int n, rev = 0, remainder;
user. Then the while loop is used until n !=
printf("Enter an integer: ");
0 is false (0). scanf("%d", &n);
• In each iteration of the loop, the remainder while (n != 0) {
when n is divided by 10 is calculated and the remainder = n % 10;
rev = rev * 10 + remainder;
value of n is reduced by 10 times. n /= 10;
• Inside the loop, the reversed number is }
printf("Reversed number = %d", rev);
computed using:
return 0;
• rev = rev*10 + remainder; }
Output
Enter an integer: 2345
Reversed number = 5432
Program code for Factorial of a Number in C
#include<stdio.h> • Working:
#include<conio.h> • First the computer reads the number to find the factorial of
void main() the number from the user.
{ • Then using while loop the value of ‘i’ is multiplied with the value of
int n,i=1,f=1; ‘f’.
clrscr(); • The loop continues till the value of ‘i’ is less than or equal to ‘n’.
printf("\n Enter The Number:"); • Finally the factorial value of the given number is printed.
scanf("%d",&n);
• Step by Step working of the above Program Code:
• Let us assume that the number entered by the user is 6.
//LOOP TO CALCULATE FACTORIAL OF A NUMBER • It assigns the value of n=6 , i=1 , f=1
while(i<=n) • Then the loop continues till the condition of the while loop is true.
{ • 2.1. i<=n (1<=6) , while loop condition is true.
f=f*i; • f=f*i (f=1*1) So f=1
• i++ (i=i+1) So i=2
i++; • 2.2. i<=n (2<=6) , while loop condition is true.
} • f=f*i (f=1*2) So f=2
printf("\n The Factorial of %d is %d",n,f); • i++ (i=i+1) So i=3
• 2.3. i<=n (3<=6) , while loop condition is true.
getch(); • f=f*i (f=2*3) So f=6
} • i++ (i=i+1) So i=4
• 2.4. i<=n (4<=6) , while loop condition is true.
• f=f*i (f=6*4) So f=24
• i++ (i=i+1) So i=5
• 2.5. i<=n (5<=6) , while loop condition is true.
• f=f*i (f=24*5) So f=120
• i++ (i=i+1) So i=6
• 2.6. i<=n (6<=6) , while loop condition is true.
• f=f*i (f=120*6) So f=720
• i++ (i=i+1) So i=7
• 2.7. i<=n (7<=6) , while loop condition is false.
• It comes out of the while loop.
• Finally it prints as given below
• The Factorial of 6 is 720
• Thus the program execution is completed.
C program to check Least Significant Bit (LSB) of a
number is set or not
Logic to check Least Significant Bit (LSB) of a number
• To check the status of Least Significant Bit (LSB) of any /** * C program to check Least Significant Bit
number we will use bitwise AND & operator. (LSB) of a number using bitwise operator
• Even for checking the current status of any bit we use bitwise */ #include <stdio.h>
AND operator. int main()
• We know that bitwise AND operator evaluates each bit of the {
result to 1 if the corresponding bits of both operands are 1. int num;
• Now to check the LSB of any number we are going to perform // Input a number from user
bitwise AND operation with the number and 1. printf("Enter any number: ");
• The bitwise AND operation number & 1 will evaluate to 1 if and scanf("%d", &num);
only if the LSB of number is 1 otherwise will evaluate to 0. //If (num & 1) evaluates to 1
if(num & 1)
printf("LSB of %d is set (1).", num);
else
printf("LSB of %d is unset (0).", num);
return 0;}
C program to swap two numbers using bitwise operator
• Logic to swap two numbers using bitwise • Program to swap two numbers
operator #include <stdio.h>
• We can perform swapping of two numbers using int main()
bitwise XOR ^operator. { int num1, num2;
• Bitwise XOR operator evaluates each bit of the result printf("Enter any two numbers: ");
to 1 if each corresponding bits of the two operands scanf("%d%d",&num1,&num2);
differ else evaluates to 0. printf("Original value of num1 = %d\n", num1);
• Suppose two integer values a and b printf("Original value of num2 = %d\n", num2);
num1 ^= num2;
Let's suppose x = a ^ b
num2 ^= num1;
Then again x ^ b will evaluate to a and x ^ a will num1 ^= num2;
evaluate to b. printf("Num1 after swapping = %d\n", num1);
printf("Num2 after swapping = %d\n", num2);
return 0;}
C program to check even or odd using bitwise operator
• Logic to check even or odd numbers using bitwise • Program to check even or odd using bitwise operator
#include <stdio.h>
• In the above image we can see that if the number is even int main()
then its LSB is 0 otherwise LSB is 1. {
• To check the status of any bit we can use bitwise AND int num;
operator. If num & 1 evaluates to 1 then the number is // Input a number from user
odd otherwise even. printf("Enter any number: ");
scanf("%d", &num); (num & 1) ?
printf("%d is odd.", num) : printf("%d is even.", num);
return 0;
}
THANK YOU!!