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

Programming

Section - 6
Switch

3
Switch

• The switch statement is used to perform different actions


based on different conditions:
➢ The switch expression is evaluated once.
➢ The value of the expression is compared with the values of each
case.
➢ If there is a match, the associated block of code is executed.
➢ If there is no match, the default code block is executed.

4
Switch

• A switch statement allows a variable to be tested for equality against a


list of values.

switch( variable_Name ) {
case value1 :
Statements;
break;
case value2 :
Statements;
break;
default:
statements;

}
5
Switch

6
Switch

int expression = 2;

switch (expression) {
case 1:
printf("Case 1");
case 2:
printf("Case 2");
case 3:
printf("Case 3");
default:
printf("Default case");
}
7
Example 1:

Write a c program to print a day of week name according to


number user enters.

8
Answer:

9
Answer

10
Example 2:

Write a c program to check if character vowel or not.

11
Answer

12
Task:

• Using a C program to design calculator that accept two


numbers from the user & operator (+, -, *, /),
• Then using switch to do operation that the user needs

13
Answer

14
For loop

15
For Loop

• Loops can execute a block of code a number of times.

• Loops are handy, if you want to run the same code over and
over again, each time with a different value.

16
For

• Executes a sequence of statements multiple times.


• Syntax :

for (counter = initial value ; counter < final value ; step)


{
// ‫الجمل المراد تكرارها توضع هنا‬
}
17
Example 4:

Write a c program to print number from 1 to 10

18
Answer

19
Example 5:

Print even numbers from 0 to 10?

20
Example 6:
Write a program to print the sum of even numbers from 0 to 100 ?

21
Another solution

22
Example 7:

Write a c program to to print the factorial of (N!)


where
N! = 1*2*3*….*N

23
Answer

24
Example 8:

Write a c program to to print to calculate 𝑥 𝑦

where x is the base ,


y is the power.

25
Answer

26
THANK YOU

You might also like