0% found this document useful (0 votes)
6 views31 pages

C Chapter 03

The document provides an overview of C programming concepts focusing on control structures such as if-else statements, switch statements, and while loops. It includes examples of how to implement these structures in C programs for various tasks, such as checking odd/even numbers, finding the largest of three numbers, and performing arithmetic operations based on user input. Additionally, it discusses the syntax and usage of these control structures, along with practical coding examples.

Uploaded by

basarenkov
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)
6 views31 pages

C Chapter 03

The document provides an overview of C programming concepts focusing on control structures such as if-else statements, switch statements, and while loops. It includes examples of how to implement these structures in C programs for various tasks, such as checking odd/even numbers, finding the largest of three numbers, and performing arithmetic operations based on user input. Additionally, it discusses the syntax and usage of these control structures, along with practical coding examples.

Uploaded by

basarenkov
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/ 31

C Programming

• IF-ELSE
• SWITCH
• LOOPS— ONLY while
• Other Loops-NEXT WEEK
If-else Statements

if (expr)
statement1 /*do this if expr is non-zero*/
else
statement2 /*do this if expr is zero*/

• The else clause is optional!

2
If-else Examples

if (j > limit)
return j; /* note semicolon*/

else
j += stepValue; /* note semicolon*/

...

if (++k >= 4)
k = 0; /* increment k mod 4*/

3
Selection: the if statement

if ( condition )
{
statement(s) /* body of the if statement */
}

The braces are not required if the body contains only a


single statement. However, they are a good idea and
are required by the 104 C Coding Standards.
If-else Examples (continued)

5
Concatenated If-else Statements

if (expr1)
statement1 /*do this if expr1 is non-zero*/

else if (expr2)
statement2 /*i.e., expr1 == 0, expr2 != 0*/

else if (expr3)
statement3 /expr1 and expr2 are zero, expr3 != 0*/
else if (expr4)
statement4 /expr1, expr2 , expr3 all zero, expr4 != 0*/
else
statement5 /*i.e., all expr are zero*/
6
Concatenated If-else Statements

• Last else is always attached to last if

• If it should be attached to any other if, use


{} to control the flow of execution.

7
More Practice-What is the output?
int main(int argc, char *argv[]) {
int a = 3, b = 2, c = 11 ;
if(c / b == 5){printf("True");}else{printf("False");}printf("\n");

if(c % b <= a % b){printf("True");}else{printf("False");}printf("\n");

if(b + c / a != c - a){printf("True");}else{printf("False");}printf("\n");

if(b < c && c == 7){printf("True");}else{printf("False");}printf("\n");

if((c + 1 - b == 0) || (b = 3)){printf("True");}else{printf("False");}
return 0;
}
Example -1 for IF Statement
• Write a C program for asking the user to enter a number and to
check and display whether the entered number is odd or even.
• Note That:
– Use the modulus operator.
– The number must be entered from the user like “Enter a Number=“
– Display the result like “5 is an Odd Number” or “6 is an Even Number”

int main(int argc, char *argv[]) {


int num;
printf("Enter a number :");
scanf("%d",&num);
if(num%2==0)
{
printf("This is an even number");
}
else
{
printf("This is an odd number");
}
return 0;
}
9
Example -2 for IF Statement
• Write a C program for asking the user to enter the three number to
check which one is the largest or biggest of the three number, then
display the result on the screen.
• Note That:
– The numbers must be entered from the user like “Enter three Numbers=“
– Display the result like “Biggest number is 5”
int main(int argc, char *argv[]) {
int a, b, c, big;
printf("Enter three numbers : "); scanf("%d%d%d",&a,&b,&c);
big=a;
if(big<b)
{
if(b>c) { big=b;} else { big=c; }
}
else if(big<c)
{
if(c>b) { big=c; } else { big=b; }
}
else
{
big=a;
}
10
printf("Biggest number is %d",big);
return 0;
Example -3 for IF Statement
• Write a C program to relate two integers using =, > or <
• Note That:
– The numbers must be entered from the user like “Enter Two Integers=“
– Display the result like “Result 5 < 6” or “Result 5 = 5” or “Result 6>5”

int main(int argc, char *argv[]) {

int number1, number2;


printf("Enter two integers: "); scanf("%d %d", &number1, &number2);

if(number1 == number2) { printf("Result: %d = %d",number1,number2); }

else if (number1 > number2) { printf("Result: %d > %d", number1, number2); }

else { printf("Result: %d < %d",number1, number2); }

return 0;
}

11
Example -4 for IF Statement
• Write a C program to convert Fahrenheit to Celsius and Celsius to
Fahrenheit.
• Note That:
– You must ask the choice for conversion from the user.
– Find the converted temperature based on given input
– You must use only two variables for the selection and the temperature.
– The variables “temp” and “sel” must be used for the temperature and the
choice, respectively.
– For from Fahrenheit to Celsius: (temp - 32) / 1.8
– For from Celsius to Fahrenheit: (temp*1.8)+32;
– Display the result like:

12
float temp;
int sel;
printf("Enter a temperature=");scanf("%f",&temp);
printf("For From Fahrenheit to Celsius [1]\n");
printf("For From Celsius to Fahrenheit [2]\n");
printf("Enter Your Choice (1 or 2)=");scanf("%d",&sel);
if(sel==1)
{
printf("The Temperature in Celsius is %0.3f",(temp-32)/1.8);
}
else
{
printf("The Temperature in Fahrenheit is %0.3f",(temp*1.8)+32);
}

13
Switch
– The syntax of switch statement is
switch (expression) {
case const-expression1 : statement1
case const-expression2 : statement2
:
default : statementn
}
– All case expressions must be different.
– Expression must evaluate to an integer.
– First the expression is evaluated. Then the value of expression is compared with
the case expressions. The execution begins at the case statement, whose case
expression matches.
– All the statements below are executed.
– If default is present and if no other case matches then default statement is
executed.
The Switch Statement
• The break statement can
switch ( expression ){
be used as the last
case value1 :
statement in each case's statement-list1
statement list break;
case value2 :
• A break statement statement-list2
causes control to transfer break;
to the end of the switch case value3 :
statement statement-list3
break;
• If a break statement is case ...
not used, the flow of
control will continue into }
the next case
Fixed Program using Switch-Case Structures
Switch Example
• What is the output of program below:
int main(int argc, char *argv[]) {

int num;
num=1;
switch(num)
{
case 1:printf("A");
case 2:printf("B");
case 3:printf("C");
default:printf("D");
}

return 0;
}
Switch Statement Example
int month, daysInMonth, leapYear;

switch (month) {
case 0: printf("January\n");
daysInMonth = 31;
break;
case 1: printf("February\n");
daysInMonth = leapYear ? 29 : 28;
break;
case 2: printf("March\n");
daysInMonth = 31;
break;
case 3: printf("April\n");
daysInMonth = 30;
break;

} // switch expression 1 ? expression 2 : expression 3
where
•expression1 is Condition
18
•expression2 is Statement Followed if Condition is True
•expression3 is Statement Followed if Condition is False
Example -1 for SWITCH Statement
• Write a C program which is a menu-driven program based on simple
calculation like addition, subtraction, multiplication and division
according to user's choice
• Note That:
– You must use switch statement.
– The numbers must be entered from the user like “Enter Two Numbers:“
– The four basic operation of arithmetic is selected by the user.
– The output of the program must be displayed like the below

19
ANSWER for Example 1
int main(int argc, char *argv[]) {
float n1, n2, res; char choice, ch;
printf("1.Addition\n");
printf("2.Subtraction\n");
printf("3.Multiplication\n");
printf("4.Division\n");
printf("5.Exit\n\n");
printf("Enter Your Choice : "); scanf("%c",&choice);
switch(choice)
{
case '1' : printf("Enter two number : ");scanf("%f%f",&n1,&n2); res=n1+n2; printf("Result = %f",res); break;
case '2' : printf("Enter two number : "); scanf("%f%f",&n1,&n2); res=n1-n2; printf("Result = %f",res); break;
case '3' : printf("Enter two number : "); scanf("%f%f",&n1,&n2); res=n1*n2; printf("Result = %f",res); break;
case '4' : printf("Enter two number : "); scanf("%f%f",&n1,&n2); res=n1/n2; printf("Result = %f",res); break;
case '5' : exit(0);break;
default : printf("Wrong Choice..!!"); break;
}
printf("\n------------------------------------\n");
return 0;
}

20
Repetition Structure

• A repetition structure allows the programmer to


specify that an action is to be repeated while some
condition remains true.
• There are three repetition structures in C, the
while loop, the for loop, and the do-while loop.
The while Repetition Structure
while ( condition )
{
statement(s)
}

The braces are not required if the loop body contains


only a single statement. However, they are a good
idea and are required by the 104 C Coding
Standards.
while Loop Example
• Problem: Write a program that calculates the average exam grade
for a class of 5 students.
• What are the program inputs?
– the exam grades
• What are the program outputs?
– the average exam grade
• The Output must be like:
Answer
int main(int argc, char *argv[]) {
int counter=1, total=0, grade;
float average; // average=(float)total/5;
while(counter<=5)
{
printf("Enter The grade for %d.student=",counter);
scanf("%d",&grade);
total+=grade;
counter+=1;
}
average=total/5.0;
printf("The Class Average For Ten Grades is %.2f",average);

return 0; 24

}
while Loop Example
• The Same Problem:
Write a program that calculates the average exam grade for a class.
Note That:
– You must use a sentinel value to control your while loop
– The sentinel value is tested and then the loop is executed with regard to “true”
or “false”.
– The sentinel value you will use is “-1” that is referred to as priming read.
– You must use four variables at most.
– The output must be like:
Answer
int main(int argc, char *argv[]) {
int counter=0,total=0,grade;
float average;
printf("Enter a grade=");scanf("%d",&grade);
while(grade!=-1)
{
total+=grade;
printf("Enter a grade=");scanf("%d",&grade);
counter+=1;
}
average=(float)total/counter;
printf("The Class Average For %d Grades is %.2f",counter,average);

return 0;
}
while Loop Example
Write a program that prints star patterns on the screen up to a certain row.
Note That:
– You must use while statement for the loop.
– The total number of stars must be entered from the user.
– A number of certain row must be entered from the user.
– All rows contain the same number of stars’.
– You consider that the row number is important for this problem
– The output must be like:
Answer
int main(int argc, char *argv[]) {
int totalstar, totalrow, i=1, j=1;
printf("How many stars you want to print ? ");
scanf("%d", &totalstar);
printf("Upto how many rows ? ");
scanf("%d", &totalrow);

int number_star_a_row=totalstar/totalrow;
while(i<=totalrow)
{
while(j<=number_star_a_row)
{
printf("* ");
j++;
}
printf("\n");
j=1;i++;
}
return 0;
}
The Problem but;
Write a program that prints star patterns on the screen up to a row.
Note That:
– You must use while statement for the loop.
– The total number of stars must be entered from the user.
– A number of row must be entered from the user.
– You can consider that the row number is NOT important for this problem
– The output must be like:
Answer
int main(int argc, char *argv[]) {
int totalstar, totalrow, i=1, j=1;

while(i<=totalrow)
{
while(j<=number_star_a_row)
{
printf("* ");
j++;
}
printf("\n");
j=1;i++;
}
int lacknum=totalstar-number_star_a_row*totalrow;
i=1;while(i<=lacknum){printf("* ");i++; }
return 0;
}
Questions?

31

You might also like