[go: up one dir, main page]

0% found this document useful (0 votes)
10 views18 pages

Lecture Five

Uploaded by

alvinmwangisir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views18 pages

Lecture Five

Uploaded by

alvinmwangisir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIVERSITY OF EMBU

SCHOOL OF PURE AND APPLIED SCIENCES


DEPARTMENT OF MATHEMATICS, COMPUTING & IT

STA 121: PROGRAMMING METHODOLOGY

WRITTEN BY: EDITED BY:


MR JOHN KIRWA

Copyright © UNIVERSITY OF EMBU, AUGUST 2020


All Rights Reserved
LESSON 5: CONTROL OF FLOW

Sometimes the program needs to be executed depending upon a particular condition. C provides
the following statements for implementing the selection control structure.

 if statement
 if else statement
 nested if statement
 switch statement

if statement
syntax of the if statement
if (condition)
{
statement(s);
}
If the condition is true, the statement is executed; otherwise, it is skipped. The statement may
either be single or compound.

/* This program illustrates if statement. */

#include <stdio.h>

int main()
{
int number;

printf("Enter a number: ");


scanf("%d", &number);

if (number < 0)
{
number = - number;
}

printf("The absolute value of number is %d", number);

return 0;
}
Output:
Enter a number: -15
The absolute value of number is 15
if else statement

syntax of the if - else statement

if (condition)
statement1;
else
statement2;

The given condition is evaluated first. If the condition is true, statement1 is executed. If the
condition is false, statement2 is executed. It should be kept in mind that statement and
statement2 can be single or compound.

/* This program illustrates if..else statements */

#include <stdio.h>

int main()
{
int num1, num2;

printf("Enter two integers :");


scanf("%d%d", &num1, &num2);

if (num1 > num2)


{
printf("Largest number is %d.", num1);
}
else
{
printf("Largest number is %d.", num2);
}

return 0;
}
Output:
Enter two integers:25 19
The largest number is 25.
Nested if statement
The if block may be nested in another if or else block. This is called nesting of if or else block.
syntax of the nested if statement
if(condition 1)
{
if(condition 2)
{
statement(s);
}
}
Sometimes you want to check for a number of related conditions and choose one of several
actions. One way to do this is by chaining a series of ifs and elses. Look at the following code
segment :
if(condition 1)
statement 1;
else if (condition 2)
statement2;
else
statement3;

/* This program illustrates if elseif statement */

#include <stdio.h>

int main()
{
int num1, num2, num3;

printf("Enter three integers :");


scanf("%d%d%d", &num1, &num2, &num3);

if (num1 > num2 && num1 > num3)


{
printf("Largest number is %d.", num1);
}
else if (num2 > num3)
{
printf("Largest number is %d.", num2);
}
else
{
printf("Largest number is %d.", num3);
}
return 0;
}
Output
Enter three integers :8 18 11
Largest number is 18.

switch statement
The syntax of the switch statement is:
switch (var / expression)
{
case constant1: statement 1;
break;
case constant2: statement2;
break;
.
.
default: statement3;
break;
}
The execution of the switch statement begins with the evaluation of the expression. If the value
of expression matches with the constant then the statements following this statement execute
sequentially till it executes break. The break statement transfers control to the end of the switch
statement. If the value of expression does not match with any constant, the statement with default
is executed.
Some important points about the switch statement

 The expression of a switch statement must be of type integer or character type.


 The default case needs not to be used in the last case. It can be placed at any place.
 The case values need not be in a specific order.

Below is an example of a switch case statement:

/* This program illustrates switch.. case statement */

#include <stdio.h>

int main()
{
int day;
printf("Enter number 1-7 :");
scanf("%d", &day);

/* Determine the corresponding week's day */


switch (day)
{
case 1:
printf("Sunday");
break;

case 2:
printf("Monday");
break;

case 3:
printf("Tuesday");
break;

case 4:
printf("Wednesday");
break;

case 5:
printf("Thursday");
break;

case 6:
printf("Friday");
break;

case 7:
printf("Saturday");
break;

default:
printf("Invalid input");
}

return 0;
}

Output:
Enter number 1-7 :5
Thursday
Looping statement

It is also called a repetitive control structure. Sometimes we require a set of statements to be


executed several times by changing the value of one or more variables each time to obtain a
different result. This type of program execution is called looping. C provides the following
construct

 while loop
 do-while loop
 for loop

while loop
Syntax of while loop
while(condition)
{
statement(s);
}

The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop
body is executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly
as long as the condition remains true. As soon as the condition becomes false, it comes out of the
loop and goes to the statement next to the ‘while’ loop.

/* This program illustrates while loop. */

#include <stdio.h>

int main()
{
int i = 1;

while (i <= 10)


{
printf("%d ", i);
i++;
}

return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
do-while loop
Syntax of a do-while loop
do
{
statements;
} while (condition);

Note: That the loop body is always executed at least once. One important difference between the
while loop and the do-while loop the relative ordering of the conditional test and loop body
execution. In the while loop, the loop repetition test is performed before each execution of the
loop body; the loop body is not executed at all if the initial test fails. In the do-while loop, the
loop termination test is performed after each execution of the loop body. Hence, the loop body is
always executed at least once.

/* This program illustrates do..while loop. */

#include <stdio.h>

int main()
{
int number, sum = 0;
char choice;

do
{
printf("Enter a number :");
scanf("%d", &number);

sum += number;

printf("Do you want to continue(y/n)? ");


scanf("%c", &choice);

}while (choice == 'y' || choice == 'Y');

printf("\nSum of numbers :%d", sum);

return 0;
}
Output:
Enter a number:12
Do you want to continue(y/n)? y
Enter a number:6
Do you want to continue(y/n)? y
Enter a number:19
Do you want to continue(y/n)? n

Sum of numbers:37

for loop
It is a count controlled loop in the sense that the program knows in advance how many times the
loop is to be executed.
syntax of for loop
for (initialization; decision; increment/decrement)
{
statement(s);
}

The flow diagram indicates that in for loop three operations take place:

 Initialization of loop control variable


 Testing of the loop control variable
 Update the loop control variable either by incrementing or decrementing.

Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test
whether the condition is true or false. If the condition is true, the program executes the body of
the loop and then the value of the loop control variable is updated. Again it checks the condition
and so on. If the condition is false, it gets out of the loop.

/* This program illustrates the working of for loop */

#include <stdio.h>

int main()
{
int i;

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


{
printf("%d ", i);
}

return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
Jump Statements
The jump statements unconditionally transfer program control within a function.

 goto statement
 break statement
 continue statement

The goto statement


goto allows us to make the jump to another point in the program.
goto pqr;
pqr: pqr is known as a label. It is a user-defined identifier. After the execution of the goto
statement, the control transfers to the line after label pqr.
The break statement
The break statement, when executed in a switch structure, provides an immediate exit from the
switch structure. Similarly, you can use the break statement in any of the loops. When the break
statement executes in a loop, it immediately exits from the loop.

/* This program illustrates break to exit a loop. */

#include >stdio.h>

int main()
{
int i;
for (i = 1; i >= 10; i++)
{
if (i == 5)
{
break; /* terminate loop if i is 5 */
}

printf("%d ", i);


}

printf("Loop is over.");

return 0;
}
Output:
1 2 3 4 Loop is over.
The continue statement
The continue statement is used in loops and causes a program to skip the rest of the body of the
loop.
while (condition)
{
Statement 1;
If (condition)
continue;
statement;
}
The continue statement skips the rest of the loop body and starts a new iteration.

/* This program illustrates continue to skip remaining statements of iteration. */

#include <stdio.h>

int main()
{
int i;
for (i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue; /* skip next statement if i is even */
}

printf("%d ",i);
}
printf("Loop is over.");
return 0;
}
Output:
1 3 5 7 9 Loop is over.
The exit ( ) function

The execution of a program can be stopped at any point with exit ( ) and a status code can be
informed to the calling program. The general format is
exit (code) ;
where code is an integer value. The code has a value 0 for correct execution. The value of the
code varies depending upon the operating system.

Function

A function in C is a block of statements that has a name and can be executed by calling it from
some other place in your program. functions are used to divide complicated programs into
manageable pieces. Using functions has several advantages:

 Different people can work on different functions simultaneously.


 If a function is needed more than once, you can write it once and use it many times.
 Using functions greatly enhances the program’s readability because it reduces the
complexity of the function main.

There are both library functions, functions that are already written and provided by C, and user-
defined functions, functions that you create. Because C does not provide every function that you
will ever need, you must learn to write your functions. User-defined functions in C are classified
into two categories:

 void functions - functions that do not have a return data type. These functions do not use
a return statement to return a value.
 Value-returning functions - functions that have a return data type. These functions return
the value of a specific data type using the return statement.

Creating User-Defined Functions


Declare the function.

The declaration, called the function prototype, informs the compiler about the functions to be
used in a program, the argument they take, and the type of value they return.

Define the function.

The function definition tells the compiler what task the function will be performing. The function
prototype and the function definition must be the same on the return type, the name, and the
parameters. The only difference between the function prototype and the function header is a
semicolon. The function definition consists of the function header and its body. The header is
EXACTLY like the function prototype, EXCEPT that it contains NO terminating semicolon.

/* This program illustrates how to define


and call a function */

#include <stdio.h>

void printline(); /* prototype */

int main()
{
printf("Statement 1\n");
printline();
printf("Statement 2\n");
printline();

return 0;
}

/* function definition */
void printline()
{
int i;
for (i = 0; i < 30; i++)
{
printf("_");
}
printf("\n");
}
Output:
Statement 1
______________________________
Statement 2
______________________________

Argument To A Function
Sometimes the calling function supplies some values to the called function. These are known as
parameters. The variables which supply the values to a calling function called actual parameters.
The variable which receives the value from the called statement is termed formal parameters.
Consider the following example that evaluates the area of a circle.
Here radius is called the actual parameter and r is called a formal parameter.

/* This program illustrates actual and


formal parameter of function */

#include <stdio.h>

void print_area(float); /* prototype */

int main()
{
float radius;
printf("Enter radius of circle: ");
scanf("%f", &radius);
print_area(radius);

return 0;
}

/* function definition */
void print_area(float r)
{
float area;
area = 3.14 * r * r;
printf("The area of circle is %f\n", area);
}
Output:
Enter radius of circle: 3.5
The area of circle is 38.465000

Return Type Of A Function


To let a function return a value, use the return statement. Here is an example of a value retuning
function that takes two parameters length and width and returns the area of the rectangle.

/* This programs demonstratres value returning function */

#include <stdio.h>

int area_rectangle(int, int);

int main()
{
int l, b, area;
printf("Enter the length : ");
scanf("%d", &l);

printf("Enter the width : ");


scanf("%d", &b);

area = area_rectangle(l, b);

printf("The area of the rectangle : %d", area);

return 0;
}

int area_rectangle(int length, int width)


{
return length * width;
}
Output:
Enter the length: 15
Enter the width: 9
The area of the rectangle: 135

Global Variable And Local Variable


Local Variable: Variables declared within a function, become local to the function. Local
variables have local scope: They can only be accessed within the function. Local variables are
created when a method starts and is deleted when the method is completed.

Global Variable: a variable that is declared outside any function is known as a global variable.
The scope of such a variable extends until the end of the program. these variables are available to
all functions which follow their declaration. So it should be defined at the beginning before any
function is defined.

Unary Scope Resolution Operator (::)

It is possible to declare local and global variables of the same name. C++ provides the unary
scope resolution operator (::) to access a global variable when a local variable of the same name
is in scope. A global variable can be accessed directly without the unary scope resolution
operator if the name of the global variable is not the same as that of a local variable in scope.

Static Variables

Static variables are declared by writing the keyword static in front of the declaration. If a static
variable is not initialized then it is automatically initialized to 0. A static variable is initialized
only once and its value is retained between function calls.

/* This program illustrates working of static variable */

#include <stdio.h>

void fun();

int main()
{
fun();
fun();
fun();

return 0;
}

void fun()
{
static int a = 10;
printf("a = %d\n", a);
a++;
}
Output:
a = 10
a = 11
a = 12

Variables and Storage Class

The storage class of a variable determines which parts of a program can access it and how long it
stays in existence. The storage class can be classified as automatic register static external.

Automatic variable
All variables by default are auto i.e. the declarations int a and auto int a are equivalent. Auto
variables retain their scope until the end of the function in which they are defined. An automatic
variable is not created until the function in which it is defined is called. When the function exits
and control is returned to the calling program, the variables are destroyed and their values are
lost. The name automatic is used because the variables are automatically created when a function
is called and automatically destroyed when it returns.

Register variable
A register declaration is an auto declaration. A register variable has all the characteristics of an
auto variable. The difference is that the register variable provides fast access as they are stored
inside CPU registers rather than in memory.

Static variable
A static variable has the visibility of a local variable but the lifetime of an external variable. Thus
it is visible only inside the function in which it is defined, but it remains in existence for the life
of the program.
External variable
A large program may be written by several persons in different files. A variable declared global
in one file will not be available to a function in another file. Such a variable, if required by
functions in both the files, should be declared global in one file and at the same time declared
external in the second file.

Related links

The development of C language by Dennis M. Ritchie

DJGPP a complete 32-bit C/C++ development system for Intel 80386 and higher PCs.

List of Free C Compilers and interpreters available on the internet.

https://www.sanfoundry.com/c-programming-examples/

You might also like