Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Programming Logic and Design

TOPIC TITLE: C++ WHILE STATEMENT


SPECIFIC OBJECTIVES:

At the end of the topic session the students are


expected to:
1. Describe what is C++ while statement.
2. Describe the general format of while
statement.
3. Develop a C++ program using C++ while
statement.
MATERIALS/EQUIPMENT:
1. Powerpoint Presentation
2. PLD Module #15

TOPIC PRESENTATION:

Flow of discussion for C++ While Statement:


1. Introduce C++ while statement.
2. Discuss the syntax of while statement.
3. Discuss sample C++ program using while
statement.

Prepared by : FREDDIE M. TAMAYAO, MENG-CPE, CISSP Page 1 of 5


Programming Logic and Design

C++ While Statement Concept

The second loop available in C++ is the while


loop. The while loop is an entry-controlled loop.
C++ while Loop Syntax

Syntax of the while loop :


while(expression)
{
loop-body ;
}
where the loop-body may contain a single
statement, a compound statement or an empty
statement. The loop iterates while the expression
evaluates to true. When the expression becomes
false, the program control passes to the line after
the loop-body code.
In a while loop, a loop control variable should be
initialized before the loop begins as an
uninitialized variable can be used in the
expression. The loop variable should be updated
inside the body-of-the-while.
C++ while Loop Example

Sample program illustrates the working of a while


loop :
/* C++ Iteration Statements - C++ while Loop */

Prepared by : FREDDIE M. TAMAYAO, MENG-CPE, CISSP Page 2 of 5


Programming Logic and Design

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
unsigned long num, fact=1;
cout<<"Enter a number: ";
cin>>num;
while(num)
{
fact = fact*num;
num--;
}
cout<<"The factorial of the number
is "<<fact;
getch();
}
When the above program compile and executed,
it will produce the following output:

Prepared by : FREDDIE M. TAMAYAO, MENG-CPE, CISSP Page 3 of 5


Programming Logic and Design

The above program inputs an integer num. Then


as long as num is nonzero (according to while
(num)) the loop-body iterates i.e., fact is
multiplied with num and the result is stored back
in fact, followed by the decrement of num. Again
the test-expression (num) is evaluated : if it is
true, the loop repeated otherwise terminated.

Prepared by : FREDDIE M. TAMAYAO, MENG-CPE, CISSP Page 4 of 5


Programming Logic and Design

REFERENCES:

 C++: From Problem Analysis to Program Design

 Introduction to C++ Programming Logic

Prepared by : FREDDIE M. TAMAYAO, MENG-CPE, CISSP Page 5 of 5

You might also like