Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Computer Programming 05

This document discusses loops in computer programming. It covers the for loop syntax and flowchart, as well as examples. It also discusses the do-while loop syntax, flowchart and examples. It explains break and continue statements and nested loops. Functions are also briefly mentioned. The agenda outlines these topics to be covered in the lecture.

Uploaded by

Salman shakeel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Computer Programming 05

This document discusses loops in computer programming. It covers the for loop syntax and flowchart, as well as examples. It also discusses the do-while loop syntax, flowchart and examples. It explains break and continue statements and nested loops. Functions are also briefly mentioned. The agenda outlines these topics to be covered in the lecture.

Uploaded by

Salman shakeel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

COMPUTER

PROGRAMMING

Lecture 05
do while, for, and nested loops
functions

Dr. Muniba Ashfaq


TODAY’S AGENDA
 For loop
 Syntax
 Flowchart
 Examples
 Do while
 Syntax
 Flowchart
 Examples
 Break and Continue Statements
 Nested Loops
 Functions

Dr. Muniba Ashfaq


FOR REPETITION
STRUCTURE
 for loop is used when the number of times to be repeated is fixed/known
 It handles all the details of the counter controlled repetition
 Execution continues as long as the boolean expression is true

 General format of the for loops


for (initialization; Loop Continuation Test; update)
{
statement block;
}

 Initialization action
 Done only once at the start
 Initialization expression initialize and declare the loop’s control
variable e.g. int counter = 1;
 Notice that there is a semi colon after initialization statement

Dr. Muniba Ashfaq


FOR REPETITION
STRUCTURE
 Loop continuation test
 Is a boolean expression
 Expreassion contains the final value of the control variable for which the
condition is true e.g. counter <= 10;
 Loop continuation test evaluates to true or false
 If true body of for is executed, else exit for loop
 Notice that there is also a semi colon after loop condition test
 Update
 Specifies how to update condition
 After the execution of the body of the loop, the condition of the loop is

updated e.g. counter ++


 Notice that there is no semi colon after update action

 Example
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
 Prints integers from one to ten

Dr. Muniba Ashfaq


COMPONENTS OF TYPICAL FOR
HEADER

for keyword
Control variable name Final value of control variable for which the
condition is true

for ( var counter = 1; counter <= 7; ++counter )

Initial value of control variable Increment of control variable

Loop-continuation condition

Dr. Muniba Ashfaq


EXAMPLES USING THE FOR
STRUCTURE
 Vary control variable from 1 to 100 in increments of 1
 for (int i = 1; i <= 100; i++)

 Vary control variable from 100 to 1 in decrements of -1


 for (int i = 100; i >= 1; i--)

 Vary control variable from 7 to 77 in steps of 7


 for (int i = 7; i <= 77; i += 7)

 Vary control variable from 20 to 2 in steps of -2


 for (int i = 20; i >= 2; i -= 2)

Dr. Muniba Ashfaq


FOR EQUIVALENT WHILE
STRUCTURE
 In most cases, the for structure can be represented by an equivalent
while structure as follow

initialization;
while ( loop Continuation Test)
{ statement
increment;}

for loop in previous example can be rewritten as while loop


as following

int counter = 1; //initialization


While(counter<=10) //boolean expression to test the loop
condition
{
cout<<“counter”<<endl; // print the value of counter
counter++; //incriment counter
}

Dr. Muniba Ashfaq


C++ CODE
1 // example to print numbers 1 to 10
2 // Counter-controlled repetition with the for structure.
3 #include <iostream>
4 using namespace std;
5
8 // function main begins program execution
9 int main()
10 {
11 // Initialization, repetition condition and incrementing
12 // are all included in the for structure header.
13
14 for ( int counter = 1; counter <= 10; counter++ )
15 cout << counter << endl;
16
17 return 0; // indicate successful termination
18
19 } // end function main

Dr. Muniba Ashfaq


OUTPUT

Dr. Muniba Ashfaq


EXAMPLE
 Problem statement

 Write a For statement that computes the sum


of all even integers up 100.

Dr. Muniba Ashfaq


EXAMPLE
1 // program to sum all even integers from 2 to 100
2 // Summation with for.e
3 #include <iostream> output
4 using namespace std;
5
8 // function main begins program execution
9 int main()
10 {
11 int sum = 0; // initialize sum
12
13 // sum even integers from 2 through 100
14 for ( int number = 2; number <= 100; number += 2 )
15 sum += number; // add number to sum
16
17 cout << "Sum is " << sum << endl; // output sum
18 return 0; // successful termination
19
20 } // end function main

Dr. Muniba Ashfaq


<math.h> header needed for
the pow function (program will
C++ CODE not compile without it).

1 // example program using for loop <math.h> file tells the compiler
to convert the value of year to a
2 // Calculating compound interest.
temporary double
3 #include <iostream> representation before calling
4 the function pow (functions
10 #include <iomanip> will be discussed latter)
11
15 #include <math.h> // enables program to use function pow
16 using namespace std;
17 // function main begins program execution
18 int main()
19 {
20 double amount; // amount on deposit
21 double principal = 1000.0; // starting principal
22 double rate = .05; // interest rate

Dr. Muniba Ashfaq


C++ CODE
24 // output table column heads
25 cout << "Year" << setw( 21 ) << "Amount on deposit" << endl;
26
•Manipulator setw is defined
27 // set floating-point number format
28 cout << fixed << setprecision( 2 ); in <iomanip> library
29 •Sets the field width to at least
30 // calculate amount on deposit for each of ten years 21 characters position.
31 for ( int year = 1; year <= 10; year++ ) { •If output less than 21, it is
32 right-justified.
33 // calculate new amount for specified year •If the output is more than 21
34 amount = principal * pow( 1.0 + rate, year );
35
the field width is extended to
36 // output one table row accommodated entire value
37 cout << setw( 4 ) << year
38 << setw( 21 ) << amount << endl;
39
pow(x,y) = x raised to the
40 } // end for yth power.
41 Principal*(1.0 + rate)year
42 return 0; // indicate successful termination
43
44 } // end function main

Dr. Muniba Ashfaq


OUTPUT

Numbers are right-justified


due to setw statements (at
positions 4 and 21).

Dr. Muniba Ashfaq


DO-WHILE REPETITION
STRUCTURE
 A variation of the while loop.
 A do-while loop is always executed at least once
 Makes loop continuation test at the end not the beginning
 The body of the loop is first executed
 The condition (boolean expression) is checked after the body
has been executed
 Syntax / Format
do {
statement block
} while ( condition );
 semantics
1. Execute the statement.
2. Evaluate the expression.
3. If it is TRUE then proceed to step (1) else exit the loop

Dr. Muniba Ashfaq


DO-WHILE FLOW CHART
do
statement;
while (condition);
action(s)

Or

true do
condition
{
false statement block
} while (condition);

Dr. Muniba Ashfaq


A SIMPLE EXAMPLE TO PRINT NUMBERS
1 TO 10
1. // simple program to print the numbers 1 to 10
2. // Using the do/while repetition structure

3. #include <iostream> //preprocessor directive


4. using namespace std;
5. int main()
6. {
7. int counter = 1; //initializing counter to 1 that control variable
Notice
8. do counter is pre-incremented in
9. { //do while loop begins loop continuation test
10. cout << counter << " "; //display counter
11. } while ( ++counter <= 10 );//loop continuation test // do while loop ends
12.
13. cout << endl; output
14. return 0;
15. }

Dr. Muniba Ashfaq


BREAK AND CONTINUE
STATEMENTS
 The break and continue statements alter the flow of control

 break statement
 Causes immediate exit from while, for, do/while or
switch structure
 Program execution continues with first statement after
structure
 Common uses
 Escape early from a loop
 Skip the remainder of switch structure

Dr. Muniba Ashfaq


EXAMPLE PROGRAM TO DEMONSTRATE THE
BREAK STATEMENT IN FOR REPETITION
STRUCTURE
1 // Using the break statement in a for structure.
2 // the for loop will terminate as soon as x becomes 5
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11
12 int x; // x declared here so it can be used both in and after the loop
13 Exits for structure when
14 // loop 10 times
15 for ( x = 1; x <= 10; x++ ) break is executed.
16 {
17 // if x is 5, terminate loop
18 if ( x == 5 )
19 break; // break loop only if x is 5
20
21 cout << x << " "; // display value of x
22
23 } // end for
24 Output
25 cout << "\nBroke out of loop when x became " << x << endl;
26
27 return 0; // indicate successful termination
28
29 } // end function main

Dr. Muniba Ashfaq


BREAK AND CONTINUE
STATEMENTS
 continue statement
 Used in while, for, do/while
 Skips remainder of loop body
 Proceeds with next iteration of loop

 while and do/while structure


 Loop-continuation test evaluated immediately after the
continue statement
 for structure
 Increment expression executed
 Next, loop-continuation test evaluated

Dr. Muniba Ashfaq


EXAMPLE PROGRAM TO DEMONSTRATE THE
CONTINUE STATEMENT IN FOR REPETITION
STRUCTURE
1 // Fig. 2.27: fig02_27.cpp
2 // Using the continue statement in a for structure.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 // loop 10 times
Skips to next iteration of the
12 for ( int x = 1; x <= 10; x++ ) { loop.
13
14 // if x is 5, continue with next iteration of loop
15 if ( x == 5 )
16 continue; // skip remaining code in loop body
17
18 cout << x << " "; // display value of x
19
20 } // end for structure
21
22 cout << "\nUsed continue to skip printing the value 5"
23 << endl;
24
25 return 0; // indicate successful termination
26
27 } // end function main

Dr. Muniba Ashfaq


OUTPUT

Dr. Muniba Ashfaq


NESTED LOOP
 A loop within another loop is called a nested
loop.
  The inner loop gets executed first, satisfying
all the set of conditions that prevailed within
the loop followed by an outer loop set of
conditions.

Dr. Muniba Ashfaq


SYNTAX (NESTED FOR LOOP)
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more
//statements.
}

Dr. Muniba Ashfaq


FLOWCHART (NESTED FOR
LOOP)

Dr. Muniba Ashfaq


SYNTAX (NESTED WHILE LOOP)
while(condition)
{
while(condition)
{
statement(s);
}
statement(s); // you can put more
//statements.
}

Dr. Muniba Ashfaq


FLOWCHART (NESTED WHILE
LOOP)

Dr. Muniba Ashfaq


SYNTAX (NESTED DO WHILE
LOOP)
do
{
statement(s); // you can put more
//statements.
do
{
statement(s);
} while( condition );
} while( condition );

Dr. Muniba Ashfaq


FLOWCHART (NESTED DO WHILE
LOOP)

Dr. Muniba Ashfaq


C++ PROGRAM TO DISPLAY 7
DAYS OF 3 WEEKS
#include <iostream>
using namespace std;
int main()
{
int weeks = 3, days_in_week = 7;

for (int i = 1; i <= weeks; ++i)


{
cout << "Week: " << i << endl;
for (int j = 1; j <= days_in_week; ++j)
{
cout << " Day:" << j << endl;
}
}
return 0;
}

Dr. Muniba Ashfaq


OUTPUT

Dr. Muniba Ashfaq


C++ PROGRAM TO DISPLAY A PATTERN
WITH 5 ROWS AND 3 COLUMNS
#include <iostream>
using namespace std;
int main()
{
int rows = 5; int columns = 3;

for (int i = 1; i <= rows; ++i)


{
for (int j = 1; j <= columns; ++j)
{
cout << "* ";
}
cout << endl;
}
return 0;
}

Dr. Muniba Ashfaq


OUTPUT

Dr. Muniba Ashfaq


MODULAR PROGRAMMING
WITH FUNCTIONS
 Best way to construct a large program is to construct it from
smaller pieces or components (modules)
 Each piece is more manageable than the original program

 Modules in c++ are functions and classes

 Function is a group of statements that is executed when it is


called from some point of the program

 Functions allow the programmer to modularize a program,


accessing all the potential that structured programming can offer
in C++

 Function can be called multiple times in a program

Dr. Muniba Ashfaq


MODULAR PROGRAMMING
WITH FUNCTIONS
 C++ programs can be written by combining
 pre-packaged functions
 Programmer defined functions

 Pre- packaged functions


 Are available in standard C++ library
 Provided as part of the C++ programming environment
 C++ library provides rich collection of functions for performing
 Common mathematical calculations
 String manipulations
 Character manipulations
 Input/output, error checking and many other useful operations

Dr. Muniba Ashfaq


FUNCTION LIBRARIES
 Predefined functions are found in libraries

 The library must be “included” in a program


to make the functions available

 An include directive tells the compiler which


library header file to include.

 To include the math library containing sqrt():


#include <cmath>

 Newer standard libraries, such as cmath, also require


the directive
using namespace std;

Dr. Muniba Ashfaq


MODULAR PROGRAMMING
WITH FUNCTIONS
 Math library functions
 Allow the programmer to perform common mathematical
calculations
 To use math library functions including the header file
<cmath>

 Example

cout << sqrt( 900.0 );

 Calls the sqrt (square root) function.


 The preceding statement would print 30
 The sqrt function takes an argument of type double
 And returns a result of type double, as do all functions in the math
library

Dr. Muniba Ashfaq


MODULAR PROGRAMMING
WITH FUNCTIONS
 Function call arguments can be
 Constants
sqrt( 4 );

 Variables
sqrt( x );

 Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3y + 6 );

Dr. Muniba Ashfaq


COMMONLY USED MATH LIBRARY
FUNCTIONS
Me th o d De sc rip tio n Exa m p le
ceil( x ) rounds x to the smallest integer ceil( 9.2 ) is 10.0
not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential function ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0
not greater than x floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 )
point number is 1.992
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x sin( 0.0 ) is 0
(x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x tan( 0.0 ) is 0
(x in radians)
Dr. Muniba Ashfaq
PROGRAM EXAMPLE TO OBSERVE PREDEFINED
FUNCTIONS
1. //program to find the square root of any number
2. //by calling a predefined math function for square root
3. #include <iostream>
4. #include <cmath> //math library header file
5. using namespace std;
6. int main()
7. {
8. double x;
9. cout<<"enter a number to find its sqrt";
10. cin>>x;

11. cout<<sqrt(x);// calling predefined function for square root


12.

13. return 0;
14. }

Square root of 9.9 is 3.14643

Dr. Muniba Ashfaq


FUNCTION DEFINITIONS

 For programmer defined functions the important components are


 Function definition
 Function prototype

41
FUNCTION DEFINITION
 Describes how the function does its task
 Can appear before or after the function is called
 Format
return-value-type function-name( parameter-list )
{
declarations and statements
}
 Function-name
 is any valid identifier e.g. square
 Return-value-type
 is the data type of the result returned from the function to the caller
 Return value type void indicated that the function does not return a vlaue
 Parameter-list
 Is a comma-separated list of the arguments
 containing the declarations (data type needed for each argument) of the
parameters received by the function when it is called
 If the function does not receive any values, parameter-list is void or simply
left empty

42
FUNCTION DEFINITION
 Example function
int square( int y )
{

return y * y;
}
 return keyword
 Format return expression;
 Returns the value calculated by the function
 Returns data, and control goes to function’s caller
 If no data to return, use return;

 Function ends when reaches right brace


 Control goes to caller

 Functions cannot be defined inside other functions

43
FUNCTION PROTOTYPE
 Must appear in the code before the function can be called
 The compiler use the function prototypes to validate function
call
 Format /syntax
 Return-value-type Function_Name(Parameter_List);

 Function prototype tells the compiler


 The function’s name
 Type of data returned by the function (void if return nothing)
 Number of parameters the function accepts to receive
 Types of parameters
 The order in which these parameters are expected
 Function prototype is not required if the function definition
appears before the first use function’s first use in the program.
 In such case the function definition also acts as the function
prototype

44
EXAMPLE PROGRAM
1 // program calculate the square of integers 1 to 10
2 // Creating and using a programmer-defined function.
3 #include <iostream> Function prototype: specifies
4 data types of arguments and
5 using std::cout;
6 using std::endl;
return values. square
7 expects and int, and returns
8 int square( int ); // function prototype
an int.
9
Parentheses () cause function
10 int main()
11 { to be called. When done, it
12 // loop 10 times and calculate and output returns the result.
13 // square of x each time
14 for ( int x = 1; x <= 10; x++ )
15 cout << square( x ) << " "; // function call
16
17 cout << endl;
18
19 return 0; // indicates successful termination
20
21 } // end main
23 // square function definition returns square of an integer
24 int square( int y ) // y is a copy of argument to function
25 {
Definition of square. y is a
26 return y * y; // returns square of y as an int
27 copy of the argument passed.
28 } // end function square Returns y * y, or y squared.
45
OUTPUT

1 4 9 16 25 36 49 64 81 100

46
FUNCTION PROTOTYPE
 Prototype must match function definition

 Function prototype
double maximum( double, double, double );
 Definition
double maximum( double x, double y, double z )
{

}
 observe this in the following program example
 This example program uses a programmer-defined function
maximum to determine and return the largest of three integers

47
EXAMPLE PROGRAM
1 // using programmer defined function
2 // Finding the maximum of three floating-point numbers.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 double maximum( double, double, double ); // function prototype
10
11 int main()
12 {
13 double number1;
14 double number2;
Function maximum takes 3
15 double number3;
16 arguments (all double) and
17 cout << "Enter three floating-point numbers: "; returns a double.
18 cin >> number1 >> number2 >> number3;
19
20 // number1, number2 and number3 are arguments to
21 // the maximum function call
22 cout << "Maximum is: "
23 << maximum( number1, number2, number3 ) << endl;
24
25 return 0; // indicates successful termination

48
EXAMPLE PROGRAM
26
27 } // end main Comma separated list for
28 multiple parameters.
29 // function maximum definition;
30 // x, y and z are parameters
31 double maximum( double x, double y, double z )
32 {
33 double max = x; // assume x is largest
34
35 if ( y > max ) // if y is larger,
36 max = y; // assign y to max
37
38 if ( z > max ) // if z is larger,
39 max = z; // assign z to max
40
41 return max; // max is largest value
42
43 } // end function maximum

output

49

You might also like