0% found this document useful (0 votes)
23 views39 pages

Lecture 3

Uploaded by

techifiafrica
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)
23 views39 pages

Lecture 3

Uploaded by

techifiafrica
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/ 39

CPE/EET 224 : GENERAL COMPUTER PROGRAMMING

CONTROL STRUCTURES IN C

Department of Computer Engineering


School of Engineering and Engineering Technology (SEET)
Federal University of Technology Minna, Nigeria.
Assignment operators
=, +=, -=, *=, /=, %=.
a=10, b=15, c=25;
c+=a……c=c+a;
c-=a…….c=c-a;
c*=a…….c=c*a;
c%=a……c=c%a;
Using the scanf() function
int num;
printf(“Enter the number:\t”); // Ask user to enter 1 number
scanf(“%d”,&num); // Recv number in num
printf(“User entered: %d\n”);

Note:
We can see that instead of num, &num is passed as 2nd
argument to scanf() function.The unary & here passes
the address of num to the scanf() function. This is called
pass by reference
 Exercise 1.
Take 2 numbers as input from user, add
them and print the result back to user.
What to cover Today
 Review control structures
 Sequence
 Selection
 Repetition
Learning Objectives
 Explain the three basic types of control
structures
 Explain the selection structure and it types
 Explain how the three kinds of repetition
structures work
 Apply the concept of repetition control
structures to practical problems
CONTROL STATEMENTS
In the program codes we have studied so far, you would
observe most of the instructions are executed once in the order
in which they appear in the program.

But in reality most program operations require you to have


some selection process, repetitive loop, inclusion of some logical
structure and so on within it in order for you to achieve your
desired operation or task.

 In C, to be able to write programs to perform this operations


and lots more we need to study the control structure or
statements.
CONTROL STATEMENTS
Basically in C , we have Three Control Structure and Seven
Control Statements namely

SEQUENCE STRUCTURE
SELECTION STRUCTURE (3 TYPES: if, if-else, switch)
REPTITION STRUCTURE (3 TYPES: while, do-while, for)

SEQUENCE: These structures are built in the C-program or


compiler. The execution of programs one after the other in the
order in which they were written is the called the sequential
execution.
CONTROL STATEMENTS: SELECTION STRUCTURE

SELECTION STRUCTURE: This structure may also be called a


branching control structure. It helps to decide on the possible
direction upon the completion of a logical test or group of
statements.
There basically three types namely ; the IF structure, the IF-
ELSE structure and the SWITCH structure.

IF: it is a single selection statement which carries out a logical


test and then takes the one of the two possible action depending
on the outcome of the test (whether TRUE or FALSE).
CONTROL STATEMENTS: SELECTION STRUCTURE (IF :Contd)
IF syntax : if (expression) statement

The expression must be in parentheses and statement will be


executed iff the expression is TRUE (Non-zero value)

However if the expression is FALSE (Zero value) the expression


will be ignored.

Note : the statement can be of any form, simple, compound or


even complex.
CONTROL STATEMENTS: SELECTION STRUCTURE (IF :Contd)

Lets take some examples:


Question: Write a C program code using the if statement to
determine if a mark is a pass mark.

First thing to do by standard practice is to develop or write a


pseudo code for the given task.

/*see definition of pseudo code on note extra */


Pseudo-code:
If student’s score is greater than or equal to 40
Print ‘’pass mark’’
IF statement (single-selection)
 Syntax
if(expression) /* if expression is TRUE (not equal to zero) */
statement1; /* then execute this statement */
statement2;
 Notes
 Indent statements
 Can have multiple statements
 Enclose a ‘block’ of statements using { } (curly braces)
if( x <= 2 )
{
statement1;
statement2;
}
statement3;
CONTROL STATEMENTS: SELECTION STRUCTURE (IF :Contd)

1. #include <stdio.h>
2. int main (void){
3. int score;
4. printf("Enter students score\n");
5. scanf("%d", &score);
6. if(score>=41) {
7. printf("pass score: congrats\n");
8. }
9. return 0;
10. }
CONTROL STATEMENTS: SELECTION STRUCTURE (IF :Contd)

Lets take some examples:


Question: Write a C program code using the if statement to
determine the greatest of three numbers.

First thing to do by standard practice is to develop or write a


pseudo code for the given task.
CONTROL STATEMENTS: SELECTION STRUCTURE (IF :Contd)
1. #include <stdio.h>
2. int main (void){
3. int first,second,3rd; /*observe 3rd is an incorrect identifier */
4. printf("Enter number now\n");
5. scanf("%d %d%f", &first,&second,&third);
6. if(first>second) {
7. printf(“first is greater than second\n");
8. }
9. if(second>third) {
10. printf(“second is greater than third\n");
11. }
12. if(third>first) {
13. printf(“third is greater than first\n");
14. }
15. return 0;
16. }
CONTROL STATEMENTS: SELECTION STRUCTURE (IF :Contd)

1. #include <stdio.h>
2. int main (void){
3. int first,second;
4. printf("Enter number now\n");
5. scanf("%d %d", &first, &second);
6. if((first>second)||(second>third)){
7. printf(“first is smallest of all\n");
8. }
9. return 0;
10. }
CONTROL STATEMENTS: SELECTION STRUCTURE (IF :Contd)

1. #include <stdio.h>
2. int main (void){
3. int first,second;
4. printf("Enter number now\n");
5. scanf("%d %d", &first, &second);
6. if((first<second)&&(second<third)){
7. printf(“third is greatest of all\n");
8. }
9. return 0;
10. }
Flowchart for IF Statement
connector
flow line
decision symbol action symbol

TRUE
Speed > 65 Print “You’re
speeding!”

FALSE
CONTROL STATEMENTS: SELECTION STRUCTURE
(IF –ELSE)

Observe that with the IF –statement whenever the expression is


false nothing happens. However this may be very undesirable in
some situations.
The if selection statement performs an indicated action only when
the condition is true, otherwise the action is skipped.
With the IF-ELSE selection statement one can specify actions to be
performed in true and false conditions.
It is also known as the double selection statement
Syntax : if (expression) statement 1
else statement 2
CONTROL STATEMENTS: SELECTION STRUCTURE
(IF –ELSE)

Syntax : if (expression) statement 1


else statement 2
 Let see some examples now; recall our score code.
CONTROL STATEMENTS: SELECTION STRUCTURE
(IF –ELSE)

1. #include <stdio.h>
2. int main (void){
3. int score;
4. printf("Enter students score\n");
5. scanf("%d", &score);
6. if(score>=41) {
7. printf("pass score: congrats\n");
8. }
9. else{
10. printf(“fail score: see you next year\n");
11. }
12. return 0;
13. }
CONTROL STATEMENTS: SELECTION STRUCTURE
(IF –ELSE)

1. #include <stdio.h>
2. int main (void){
3. int num1,num2;
4. scanf("%d%d", &num1,&num2);
5. if(num1<num2) {
6. printf(“num1 is smaller\n");
7. }
8. else {
9. printf(“num1 is bigger\n");
10. }
11. return 0;
12. }
IF-ELSE FLOWCHART (Double-Selection)

FALSE TRUE
Print “Within Speed > 65 Print “Over speed
limit” limit!”
CONTROL STATEMENTS: SELECTION STRUCTURE
(IF –ELSE)
1. //sum of two numbers using if else
2. #include <stdio.h>
3. int main (void){
4. int num1,num2,total;
5. scanf("%d%d", &num1,&num2);
6. if(num1==num2) {
7. total=num1*2;
8. printf(“total is equal to\n”,total);
9. }
10. else {
11. total=num1+num2;
12. printf(“total is equal to\n“,total);
13. }
14. return 0;
15. }
/* Compute Area and Perimeter of a circle */
#include <stdio.h>
float pi = 3.14159; /* Global */

main() {
float rad; /* Local */

printf( “Enter the radius “ );


scanf(“%f” , &rad);

if ( rad > 0.0 ) {


float area = pi * rad * rad;
float peri = 2 * pi * rad;

printf( “Area = %f\n” , area );


printf( “Peri = %f\n” , peri );
}
else
printf( “Negative radius\n”);

printf( “Area = %f\n” , area );


}
Compound Condition - &&
 Logical operators for more complex decisions
 Logical AND operator && (double ampersand)
 if(switch1 = = 0 && switch2 = = 1)
turn on the motor
 The condition evaluates to TRUE if and only if BOTH
expressions on either side of && evaluate to TRUE
 Note operator precedence
 Otherwise condition evaluates to FALSE
 Beware of ‘short circuit evaluation’
o Make the condition most likely to be FALSE the left-
most condition
Compound Condition - | |
 Logical operators for more complex decisions, cont.
 Logical OR operator | | (double vertical bar)
 if(switch1 = = 0 || switch2 = = 1)
turn on the motor
 The condition evaluates to TRUE if one or the other
or both expressions on either side of && evaluate to
TRUE
 Note operator precedence
 Otherwise condition evaluates to FALSE
 Beware of ‘short circuit evaluation’
o Make the condition most likely to be TRUE the
left-most condition
Example
#include<stdio.h>
int main() {
int num;
printf(“Enter a number:\t”);
scanf(“%d”,&num);
if ( (num % 2 == 0) && (num % 3 == 0) ) {
printf(“%d is divisible by 2 and 3…\n”,num);
}
else {
printf(“%d is divisible by 2 and 3…\n”,num);
}
return 0;
}
CONTROL STATEMENTS: SELECTION STRUCTURE
(NESTING )

•Nesting the if-else statement simple refers to the embedding the


if-else into a more complex one for multiple case by placing the if-
else statement inside an if-else statement.
•Syntax : case 1
•If (expression1) if (expression2) statement1
else statement2
else if (expression 3) statement3
else statement4

So lets see how this works


CONTROL STATEMENTS: SELECTION STRUCTURE
(NESTING )

•case 1
•If (expression1) if (expression2) statement1
else statement2
else if (expression 3) statement3
else statement4

•One If-else will be executed if e1 =True and if e1=False


•If e1 is True = e2 ,s1,s2 will be executed.
•If e11 is False =e3,s3,s4
CONTROL STATEMENTS: SELECTION STRUCTURE
(NESTING )

• case 2
• if (expression2) statement1
else if (expression2) statement2
•Case 3
if (expression 1) statement1
else if (expression2) statement4
else statement5

•You can have lot more cases depending on you choice


CONTROL STATEMENTS: SELECTION STRUCTURE: (NESTING )

• So lets write another code using Nested approach


1. #include <stdio.h>
2. int main (void){
3. Float time;
4. scanf("%f", &time);
5. if((time>=0)&&(time<12)) {
6. printf(“Good morning the time is\n”,time);
7. else if((time>=12)&&(time<18))
8. printf(“Good afternoon the time is\n”,time);
9. else if((time>=18)&&(time<24))
10. printf(“Good evening the time is\n”,time);
11. else
12. printf(“you are a liar in correct time\n”)
13. }
14. return 0;
15. }
//simple calculator
#include<stdio.h>
int main() {
int num1, num2, result;
char operation;
printf("enter two number\t");
scanf("%d%d", &num1, &num2);
printf("which operation?\t");
scanf(" %c", &operation);
if(operation=='+'){
result=num1+num2;
printf("num1%cnum2=%d\n", operation,result); }
else if(operation=='-'){
result=num1-num2;
printf("num1%cnum2=%d\n", operation,result); }
else if(operation=='%'){
result=num1%num2;
printf("num1%cnum2=%d\n", operation,result); }
else{
printf("invalid operator");

}
}
CONTROL STATEMENTS: SELECTION STRUCTURE

 SWITCH : Multiple –selection Statement


 The switch statement consist of a series of case labels, an
optional default case and statements to execute for each case.
 Syntax: switch (expression) statement
 The first statement within the group must be preceded by one
or more case labels (prefix).
 The case labels identify the different groups of statements
(alternatives) and distinguishes them from another.
 The case label must therefore be unique within a given switch
statement
CONTROL STATEMENTS: SELECTION STRUCTURE
switch (expression) {
case constant1 : // Execute this case…
Statement1
break;
case constant2 : // Execute this case…
Statement2
break;
case constant3 : // Execute this case…
Statement3
break;
.
.
default : // Execute this case if no case matched …
Statement
break;
}
CONTROL STATEMENTS: SELECTION STRUCTURE
#include<stdio.h>
int main() {
int day;
printf("enter number\t");
scanf("%d", &day);
switch (day) {
case 1: printf("it is monday\n");
break;
case 2: printf("it is tuesday\n");
break;
case 3: printf("it is wednesday\n");
break;
case 4: printf("its Thursday\n");
break;
case 5: printf("it is Friday\n");
break;
case 6: printf("it is saturday\n");
break;
case 7: printf("it is sunday\n");
break;
default: printf("invalid....try again pls!\n");
break;
} }
CONTROL STATEMENTS: SELECTION STRUCTURE
1. #include<stdio.h>
2. void main(){
3. char colour;
4. printf("Enter the first letter of the color\t");
5. scanf("%c", &colour);
6. switch(colour) {
7. case 'r':
8. case 'R':
9. printf("RED\n");
10. break;
11. case 'w':
12. case 'W':
13. printf ("WHITE\n");
14. break;
15. case 'b':
16. case 'B':
17. printf ("BLUE\n");
18. break;
19. default: printf("wrong letter!");
20. break;
21. }
22. }
LECTURE 4: Control Structures
- Repetition

You might also like