LESSON2 C Programming

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 75

LESSON 2

C Flow Control
OBJECTIVES:
• Familiarize yourself with control
structures;
• Know how to use logical expressions in C
programming;
• Learn how to use if ... else statements;
• and appreciate the importance of C flow
controllers.
TRULALA (TRUE)
WIZ (FALSE)
TRULALA (TRUE) or WIZ (FALSE)

1. Control statements help users


specify the order of execution of
the instructions present in a
program.
TRULALA (TRUE) or WIZ (FALSE)

2. In the if statement…
If test expression is evaluated to
FALSE, statements inside the body
of if are executed.
TRULALA (TRUE) or WIZ (FALSE)

3. In the if statement…
If the test expression is
evaluated to TRUE, statements
inside the body of if are not
executed.
TRULALA (TRUE) or WIZ (FALSE)

4. Uppercase letters (If or IF) will


generate an error.
TRULALA (TRUE) or WIZ (FALSE)

5. It is possible to include an if...else


statement inside the body of
another if...else statement.
Overview
Decisions are always taken based on different
conditions, whether it is real life or programming, it applies
to both.
In C programming language, if-else statement is
used to perform the operations based on some specific
condition. If the given condition is true, then the code
inside the if block is executed, otherwise else block code is
executed. It specifies an order in which the statements are
to be executed. If-else statement controls the flow of a
program and hence also termed as control statements.
LO.1. if...else Statement
1. if Statement
The syntax of the if statement in C
programming is:

if (condition)
{
// code
}
Flowchart of
if statement in C
How if statement works?
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.
if Statement
Let's see a simple example of
C language if statement.
Example 1: if statement

// Program to display a number if it is negative

#include <stdio.h>
int main()
{
int number;
printf("Enter a number: ");
scanf("%d", &number); // true if number is less than 0
if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
OUTPUT 1:
Enter a number: -2
You entered -2.
The if statement is easy.
When the user enters -2, the test expression number<0 is
evaluated to true. Hence, You entered -2 is displayed on the
screen.

OUTPUT 2:
Enter a number: 5
The if statement is easy.

When the user enters 5, the test expression number<0 is evaluated


to false and the statement inside the body of if is not executed
2. if...else Statement
The if statement may have an optional else
block.

The syntax of the if..else statement is:


if (condition) {
// run code if condition is TRUE
}
else {
// run code if condition is FALSE
}
Flowchart of the
if-else statement in C
How if...else statement works?

If the condition is evaluated to TRUE,


• statements inside the body of if are executed.
• statements inside the body of else from execution
are skipped
If the condition is evaluated to FALSE,
• statements inside the body of else are executed
• statements inside the body of if are skipped from
execution.
if...else Statement
Let's see a simple example of
C language if-else statement.
Example 2: if...else statement
// Check whether a number is odd or even
#include <stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);

// True if the remainder is 0


if (number%2 == 0) {
printf("%d is an even number.",num);
}
else {
printf("%d is an odd number.",num);
}
return 0;
}
Output
Enter a number: 7
7 is an odd number

When the user enters 7, the test


expression number%2==0 is evaluated to false.
Hence, the statement inside the body
of else is executed.
3. if...else Ladder

The if-else-if ladder statement is an extension to the


if-else statement. It is used in the scenario where there are
multiple cases to be performed for different conditions.
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.
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
Flowchart of
else-if ladder statement in C
Let's see a simple example of
C language if-else ladder
statement.
Example 3: C if...else Ladder
// Program to relate two integers using =, > or < symbol

#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
//checks if the two integers are equal.
if(number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
//checks if number1 is greater than number2.
else if (number1 > number2) {
printf("Result: %d > %d", number1, number2);
}
//checks if both test expressions are false
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}
Output

Enter two integers:


12
23
Result: 12 < 23
4. Nested if...else
It is possible to include an if...else statement
inside the body of another if...else statement.

In this case, the condition available in the


next if statement (the second statement) will only get
evaluated if the evaluation of the condition available in
the first statement turns out to be true. This occurs
throughout the program that has a nested statement.
#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;
}
Possible Outputs

Enter two integers:


22 Enter two integers:
22 80
Result: 22 = 22 56
Result: 80 > 56
Enter two integers:
10
45
Result: 10 < 45
• if-else statement is used for decision making in
programming.
• If the given condition is true, then the code inside if
block is executed, otherwise else block code is
executed.
• Since the if-else statement controls the flow of the
program, it is also called as Control Flow
statement.
Performance Task. Using your android phone
and C-programming apps do the following:
1. Write a program that will check whether a
person is eligible to vote or not.

Enter your age: 18 Enter your age: 12

You are eligible to vote! You are NOT eligible to vote!


Performance Task. Using your android phone
and C-programming apps do the following:
2. Write a program that will display if a number
entered by the user is positive, negative or
equal to zero.
Enter any number: -10 Enter any number : 8 Enter any number : 0

Number is NEGATIVE Number is POSITIVE Number is ZERO


#include <stdio.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) {
printf("You are eligible to vote");
}
else {
printf("You are not eligible to vote");
}
return 0;
}
#include <stdio.h>
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
if (num > 0)
{
printf("Number is POSITIVE");
}
if (num < 0)
{
printf("Number is NEGATIVE");
}
if (num == 0)
{
printf("Number is ZERO");
}
return 0;
}
Performance Task. Using your android phone
and C-programming apps do the following:
1. Write a program that will check if the alphabet
entered by the user is vowel or consonant.

a b

vowel consonant
#include<stdio.h>
int main()
{
char ch;
printf(“enter an alphabet: \n”);
scanf(“%c”, &ch);

if(ch==‘a’ || ch==‘e’ || ch==‘i’ || ch==‘o’ || ch==‘u’)


{
printf(“VOWEL”);
}
else
{
printf(“CONSONANT”);
}
return 0;
}
Performance Task. Using your android phone
and C-programming apps do the following:
1. GREATER VALUE in 2 numbers
Enter first number: Enter first number:
2 1000
Enter second number: Enter second number:
4 10
Second Number is greater First Number is greater
Write a C program to find the largest of three
numbers.
Expected Output :
if ((num1 > num2) && (num1 > num3))
printf("The 1st Number is the greatest among three. \n");

1st Number = 12
2nd Number = 25
3rd Number = 52

The 3rd Number is the greatest among three


LO.2. LOOP
1. for Loop
In programming, a loop is used to repeat a block of code until the
specified condition is met.
C programming has three types of loops:
• for loop
• while loop
• do...while loop
The syntax of the for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
How for loop works?
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test
expression is evaluated to false, the for loop is terminated.
• However, if the test expression is evaluated to true,
statements inside the body of the for loop are executed,
and the update expression is updated.
• Again the test expression is evaluated.
This process goes on until the test expression is false. When
the test expression is false, the loop terminates.
Flowchart of for loop
Example 1: for loop Output
// Print numbers from 1 to 10
#include <stdio.h> 1 2 3 4 5 6 7 8 9 10

int main() {
int i;

for (i = 1; i < 11; ++i)


{
printf("%d ", i);
}
return 0;
}
1. iis initialized to 1.
2. The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body of for loop is executed.
This will print the 1 (value of i) on the screen.
3. The update statement ++i is executed. Now, the value of i will be 2. Again, the test expression is
evaluated to true, and the body of for loop is executed. This will print 2 (value of i) on the screen.
4. Again, the update statement ++i is executed and the test expression i < 11 is evaluated. This process
goes on until i becomes 11.
5. When i becomes 11, i < 11 will be false, and the for loop terminates
Example 2: for loop Output

// Program to calculate the sum of first n natural numbers


// Positive integers 1,2,3...n are known as natural numbers
Enter a positive integer: 10
#include <stdio.h> Sum = 55
int main()
{
int num, count, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &num);

// for loop terminates when num is less than count


for(count = 1; count <= num; ++count)
{
sum += count;
}

printf("Sum = %d", sum);

return 0;
}
2. while loop
The syntax of the while loop is:
while (testExpression) {
// the body of the loop
}

How while loop works?


• The while loop evaluates the testExpression inside the parentheses ().
• If testExpression is true, statements inside the body of while loop are
executed. Then, testExpression is evaluated again.
• The process goes on until testExpression is evaluated to false.
• If testExpression is false, the loop terminates (ends).
Flowchart of while loop
Example 1: while loop
Output
/ Print numbers from 1 to 5

#include <stdio.h>
1
int main() {
int i = 1; 2
while (i <= 5) { 3
printf("%d\n", i);
++i;
4
}

return 0;
5
}
Here, we have initialized i to 1.
When i = 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed. This
prints 1 on the screen and the value of i is increased to 2.
Now, i = 2, the test expression i <= 5 is again true. The body of the while loop is executed again. This
prints 2 on the screen and the value of i is increased to 3.
This process goes on until i becomes 6. Then, the test expression i <= 5 will be false and the loop
terminates.
3. 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.
• The syntax of the do...while loop is:
do {
// the body of the loop
}
while (testExpression);

How do...while loop works?


•The body of do...while loop is executed once. Only then, the testExpression is evaluated.
•If testExpression is true, the body of the loop is executed again and testExpression is evaluated once
more.
•This process goes on until testExpression becomes false.
•If testExpression is false, the loop ends.
Flowchart of do...while Loop
Example 2: do...while loop Output
/ Program to add numbers until the user enters zero
Enter a number: 1.5
#include <stdio.h>
int main() {
Enter a number: 2.4
double number, sum = 0; Enter a number: -3.4
Enter a number: 4.2
// the body of the loop is executed at least once
Enter a number: 0
do {
printf("Enter a number: "); Sum = 4.70
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}
LO.3.

C BREAK AND CONTINUE


C break
• The break statement ends the loop immediately when it is encountered. Its
syntax is:

break;

The break statement is almost always used with if...else


statement inside the loop.
How break statement works?
Example 1: break statement Output
// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, the loop terminates
Enter n1: 2.4
#include <stdio.h>
Enter n2: 4.5
int main() {
int i; Enter n3: 3.4
double number, sum = 0.0;
Enter n4: -3
for (i = 1; i <= 10; ++i) {
printf("Enter n%d: ", i); Sum = 10.30
scanf("%lf", &number);

• Output
// if the user enters a negative number, break the loop
if (number < 0.0) {
This program calculates the
break; sum of a maximum of 10
}
numbers. Why a maximum of
sum += number; // sum = sum + number; 10 numbers? It's because if the
}
user enters a negative number,
printf("Sum = %.2lf", sum); the break statement is
return 0;
executed. This will end the for
} loop, and the sum is displayed.
C switch Statement
The switch statement allows us to execute one code block
among many alternatives.
You can do the same thing with the if...else..if ladder. However,
the syntax of the switch statement is much easier to read and
write.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;

case constant2:
// statements
break;
.
.
.
default:
// default statements
}
How does the switch statement work?
• The expression is evaluated once and compared with the values of
each case label.
• Ifthere is a match, the corresponding statements after the
matching label are executed. For example, if the value of the
expression is equal to constant2, statements after case
constant2: are executed until break is encountered.
• If there is no match, the default statements are executed.

Notes:
• If
we do not use the break statement, all statements after the
matching label are also executed.
• The default clause inside the switch statement is optional.
switch Statement Flowchart
Example: Simple Calculator Output
// Program to create a simple calculator
#include <stdio.h>

int main() { Enter an operator (+, -, *, /): -


char operation;
double n1, n2;
Enter two operands: 32.5
printf("Enter an operator (+, -, *, /): ");
12.4
scanf("%c", &operation);
printf("Enter two operands: ");
32.5 - 12.4 = 20.1
scanf("%lf %lf",&n1, &n2);

switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break; The - operator entered by the user is
case '-':
stored in the operation variable. And,
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
two operands 32.5 and 12.4 are stored
in variables n1 and n2 respectively.
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2); Since the operation is -, the control of
break;
the program jumps to
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

// operator doesn't match any case constant +, -, *, /


default:
printf("Error! operator is not correct");
Finally, the break statement terminates
} the switch statement.
return 0;
}
C goto Statement
The goto statement allows us to transfer control of the program to the
specified label.
Syntax of goto Statement:

goto label;
... .. ...
... .. ...
label:
statement;
The label is an identifier. When the goto statement is
encountered, the control of the program jumps to label: and starts
executing the code
Example: goto Statement Ou
// Program to calculate the sum and average of positive numbers tput
// If the user enters a negative number, the sum and average are displayed.
1. Enter a number: 3
#include <stdio.h> 2. Enter a number: 4.3
int main() { 3. Enter a number: 9.3
4. Enter a number: -2.9
const int maxInput = 100;
int i; Sum = 16.60
double number, average, sum = 0.0; Average = 5.53
for (i = 1; i <= maxInput; ++i) {
printf("%d. Enter a number: ", i);
scanf("%lf", &number);

// go to jump if the user enters a negative number


if (number < 0.0) {
goto jump;
}
sum += number;
}

jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);

return 0;
}
• The first 10 natural number is:
• 1 2 3 4 5 6 7 8 9 10
• The sum is:
• 55
Input the age of candidate: 10
Not eligible to vote!

Input the age of candidate: 18


Congratulation! You are eligible to vote!
character = k

1
3
5
7
9
#include <stdio.h>
int main() {
int i;
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
return 0;
}
#include <stdio.h> #include
#include <stdio.h>
int main() {
<stdio.h>
int main() { int i, j, rows;
printf("Enter the number of rows: "); int main()
int i; scanf("%d", &rows); {
for (i = 0; i <= 10; i = i for (i = rows; i >= 1; --i) { int x = 10;
+ 2) { for (j = 1; j <= i; ++j) { x += 10;
printf("%d ", j); printf("%d", x);
printf("%d \n", i); }
return 0;
printf("\n");
} }
}
return 0; return 0;
}
}
#3
#2
#1

You might also like