Processing A C++ Program
Processing A C++ Program
1- You use a text editor to create a C++ program following the rules, or
syntax, of the high-level language. This program is called the source code,
or source program. The program must be saved in a text file that has the
extension .cpp.
2- In a C++ program, statements that begin with the symbol # are called
preprocessor directives. These statements are processed by a program
called preprocessor.
3- The next step is to verify that the program obeys the rules of the
programming language—that is, the program is syntactically correct—and
the compiler translates the program into the equivalent machine language
which is called object program.
5- You must next load the executable program into main memory for
execution. A program called a loader accomplishes this task.
As a programmer, you need to be concerned only with Step 1. That is, you must
learn, understand, and master the rules of the programming language to create
source programs.
1
Basic Elements in C++ First Class
C++ Program
Step 1
Editor
Step 2
Preprocessor
Syntax
Compiler error
Step 3
Library
Step 4
Linker
Loader Step 5
Execution Step 6
A C++ Program
In this section, you will learn the basic elements and concepts of the C++
programming language to create C++ programs. In addition to giving examples
to illustrate various concepts, you need to know the effect of an output statement,
which is introduced in this program.
Example 1.1
#include <iostream>
using namespace std;
int main()
{
int num;
num = 6;
cout << "My first C++ program." << endl;
cout << "The sum of 2 and 3 = " << 5 << endl;
cout << "7 + 8 = " << 7 + 8 << endl;
cout << "Num = " << num << endl;
return 0;
}
2
Basic Elements in C++ First Class
Sample Run: (When you compile and execute this program, the following four
lines are displayed on the screen.)
My first C++ program.
The sum of 2 and 3 = 5
7 + 8 = 15
Num = 6
#include <iostream>
It is a header file that allows us to use the (predefined object) cout to generate
output and the (manipulator) endl.
int main( )
This is the heading of the function main. The left brace is the beginning of the
(body) of the function main. The right brace matches the left brace and marks the
end of the body of the function main.
cout << it is a C++ output statement. It causes the computer to evaluate the
expression after the pair of symbols << and display the result on the screen.
Note: << is an operator, called the stream insertion operator.
endl causes the insertion point to move to the beginning of the next line.
3
Basic Elements in C++ First Class
2- Every C++ program has a function called main. Thus, if a C++ program
has only one function, it must be the function main.
Comments
• It is a notes which putting on your program to clear something.
• It gives a brief explanation of the program, and explain the meaning of key
statements in a program.
• Comments are for the reader, not for the compiler. So when a compiler
compiles a program to check for the syntax errors, it completely ignores
comments.
• There are two common types of comments in a C++ program
Single-line comments begin with // and can be placed anywhere in the line.
Ex: cout << "7 + 8 = " << 7 + 8 << endl; //prints: 7 + 8 = 15
Multiple-line comments are enclosed between /* and */. The compiler ignores
anything that appears between /* and */. For example, the following is an
example of a multiple-line comment:
/*
You can include comments that can
occupy several lines.
*/
4
Basic Elements in C++ First Class
Token in C++
The smallest individual unit of a program written in any language is called a
token. C++’s tokens are divided into
1- Special symbols.
2- Reserved word.
3- Identifiers.
1- Special symbols
The following are some of special symbols:
2- Reserved words
Reserved words are also called keywords, word symbols cannot be redefined
within any program; that is, they cannot be used for anything other than their
intended use. The letters that make up a reserved word are always lowercase.
Some of the reserved words include the following:
int, float, double, char, const, void, return
3- Identifiers
Identifiers are names of things that appear in programs, such as variables,
constants, and functions. All identifiers must obey C++’s rules for identifiers.
A C++ identifier consists of letters, digits, and the underscore character (_ ) and
must begin with a letter or underscore.
Note: C++ is case sensitive—uppercase and lowercase letters are considered different. Thus,
the identifier NUMBER is not the same as the identifier number. Similarly, the identifiers X
and x are different.
5
Basic Elements in C++ First Class
Whitespaces
Every C++ program contains whitespaces. Whitespaces include blanks, tabs,
and newline characters. In a C++ program, whitespaces are used to separate
special symbols, reserved words, and identifiers. Whitespaces are nonprintable in
the sense that when they are printed on a white sheet of paper, the space between
special symbols, reserved words, and identifiers is white. Proper utilization of
whitespaces in a program is important. They can be used to make the program
readable.
Exercise:
5- Write a program in C++ to find the average of three integer numbers and
print the result.
6
Data Types in C++ First Class
Data Types
Data type: A type of the data to be stored inside the memory.
Or
Data type: refer to an extensive system used for declaring variables or
functions of different types.
C++ data types fall into the following three categories and are illustrated in
figure 2:
7
Data Types in C++ First Class
2. bool
The data type bool (takes 1 byte) has only two values: true and false. Also,
true and false are called the logical (Boolean) values. The central purpose of
this data type is to manipulate logical (Boolean) expressions.
3. char
The data type char (takes 1 byte) is the smallest integral data type. It is mainly
used to represent characters—that is, letters, digits, and special symbols. Thus,
the char data type can represent every key on your keyboard. When using the
char data type, you enclose each character represented within single quotation
marks. Examples of values belonging to the char data type include the
following:
'A', 'a', '0', '*', '+', '$', '&', ' '
Note that a blank space is a character and is written as ' ', with a space between
the single quotation marks.
4. float
The data type float is used in C++ to represent any real number between -
3.4E+38 and 3.4E+38. The memory allocated for a value of the float data type
is four bytes.
5. double
The data type double is used in C++ to represent any real number between -
1.7E+308 and 1.7E+308. The memory allocated for a value of the double data
type is eight bytes.
8
Data Types in C++ First Class
Ex:
• -5 Unary Operator
Order of Precedence
When more than one arithmetic operator is used in an expression, C++ uses
the operator precedence rules to evaluate the expression. According to the
order of precedence rules for arithmetic operators,
*, /, %
are at a higher level of precedence than:
+, -
When operators have the same level of precedence, the operations are
performed from left to right. To avoid confusion, you can use parentheses to
group arithmetic expressions.
9
Data Types in C++ First Class
(((3 * 7) – 6) + ((2 * 5) / 4 )) + 6
= ((21 – 6) + (10 / 4)) + 6 (Evaluate *)
= ((21 – 6) + 2) + 6 (Evaluate /. Note that this is an integer division.)
= (15 + 2) + 6 (Evaluate –)
= 17 + 6 (Evaluate first +)
= 23 (Evaluate +)
Note: Because the char data type is also an integral data type, C++ allows you to perform
arithmetic operations on char data. However, you should use this ability carefully. There is
a difference between the character '8' and the integer 8. The integer value of 8 is 8. The
integer value of '8' is 56, which is the ASCII collating sequence of the character '8'.
When evaluating arithmetic expressions, 8 + 7 = 15;
'8' + '7' = 56 + 55, which yields 111;
'8' + 7 = 56 + 7, which yields 63.
Mixed Expressions
An expression that has operands of different data types is called a mixed
expression. A mixed expression contains both integers and floating-point
numbers. The following expressions are examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 - 13.6 + 18 / 2
10
Data Types in C++ First Class
Ex:
• 3 / 2 + 5.5 = 1 + 5.5
= 6.5
• 4 + 5 / 2.0 = 4 + 2.5
= 6.5
string Type
A string is a sequence of zero or more characters. Strings in C++ are enclosed
in double quotation marks. A string containing no characters is called a null
or empty string. The following are examples of strings. Note that " " is the
empty string.
"Mohammed Ali"
"Welcome to C++"
""
Every character in a string has a relative position in the string. The position of
the first character is 0, the position of the second character is 1, and so on. The
length of a string is the number of characters in it.
Input
As noted earlier, the main objective of a C++ program is to perform
calculations and manipulate data. Recall that data must be loaded into main
memory before it can be manipulated. In this section, you will learn how to
put data into the computer’s memory. Storing data in the computer’s memory
is a two-step process:
1. Instruct the computer to allocate memory.
2. Include statements in the program to put data into the allocated memory.
11
Data Types in C++ First Class
constants
Some data must stay the same throughout a program. In C++, you can use a
named constant to instruct a program to mark those memory locations in
which data is fixed throughout program execution.
Named constant: A memory location whose content is not allowed to change
during program execution.
To allocate memory, we use C++’s declaration statements. The syntax to
declare a named constant is:
const dataType identifier = value;
In C++, const is a reserved word.
C++ programmers typically prefer to use uppercase letters to name a named
constant.
Ex:
const double CONVERSION = 2.54;
const int NO_OF_STUDENTS = 20;
const char BLANK = ' ';
Using a named constant to store fixed data, rather than using the data value
itself, has one major advantage. If the fixed data changes, you do not need to
edit the entire program and change the old value to the new value wherever
the old value is used. Instead, you can make the change at just one place,
recompile the program, and execute it using the new value throughout.
Variables
In some programs, data needs to be modified during program execution. This
type of data must be stored in those memory cells whose contents can be
modified during program execution. In C++, memory cells whose contents
can be modified during program execution are called variables.
Variable: A memory location whose content may change during program
execution.
The syntax for declaring one variable or multiple variables is:
12
Data Types in C++ First Class
Ex:
double amountDue;
int counter;
char ch;
int x, y;
string name;
Assignment Statement
The assignment statement takes the following form:
variable = expression;
In an assignment statement, the value of the expression should match the data
type of the variable. The expression on the right side is evaluated, and its
value is assigned to the variable (and thus to a memory location) on the left
side.
A variable is said to be initialized the first time a value is placed in the
variable. In C++, = is called the assignment operator.
13
Data Types in C++ First Class
Notes:
• This statement is valid in C++:
num = num + 2;
means ‘‘evaluate whatever is in num, add 2 to it, and assign the new value to the
memory location num.’’ The expression on the right side must be evaluated first; that
value is then assigned to the memory location specified by the variable on the left
side. Thus, the sequence of C++ statements:
num = 6;
num = num + 2;
and the statement:
num = 8;
• Suppose that x, y, and z are int variables. The following is a legal statement in C++:
x = y = z;
In this statement, first the value of z is assigned to y, and then the new value of y is
assigned to x.
14
Data Types in C++ First Class
This is called an input (read) statement. In C++, >> is called the stream
extraction operator.
Note: cin (pronounced ‘‘see-in’’), which stands for common input, cout (pronounced
‘‘see-out’’), which stands for common output.
Example:
Suppose you have the following variable declarations:
int a;
double z;
char ch;
The following statements show how the extraction operator >> works.
Statement Input Value Stored in Memory
cin >> a >> ch >> z; 57 A 26.9 a = 57, ch = 'A', z = 26.9
cin >> a >> ch >> z; 57 A a = 57, ch = 'A', z = 26.9
26.9
cin >> a >> ch >> z; 57 a = 57, ch = 'A',
A z = 26.9
26.9
cin >> a >> ch >> z; 57A26.9 a = 57, ch = 'A', z = 26.9
15
Data Types in C++ First Class
Increment and decrement operators each have two forms, pre and post. The
syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++
What is the difference between the pre and post forms of these operators?
The difference becomes apparent when the variable using these operators is
employed in an expression.
Suppose that x is an int variable. If ++x is used in an expression, first the
value of x is incremented by 1, and then the new value of x is used to evaluate
the expression. On the other hand, if x++ is used in an expression, first the
current value of x is used in the expression, and then the value of x is
incremented by 1. The following example clarifies the difference between the
pre- and post-increment operators.
Suppose that x and y are int variables. Consider the following statements:
x = 5;
y = ++x;
16
Data Types in C++ First Class
The first statement assigns the value 5 to x. To evaluate the second statement,
which uses the pre-increment operator, first the value of x is incremented to 6,
and then this value, 6, is assigned to y. After the second statement executes,
both x and y have the value 6.
Example:
Suppose a and b are int variables and:
a = 5;
b = 2 + (++a);
The first statement assigns 5 to a. To execute the second statement, first the
expression 2 +(++a) is evaluated. Because the pre-increment operator is
applied to a, first the value of a is incremented to 6. Then 2 is added to 6 to get
8, which is then assigned to b.
Therefore, after the second statement executes, a is 6 and b is 8.
17
Control Structures in C++ First Class
Control Structures
A computer can process a program in one of the following ways: in sequence;
selectively, by making a choice, which is also called a branch; repetitively, by
executing a statement over and over, using a structure called a loop; or by
calling a function. Figure 3 illustrates the first three types of program flow.
The two most common control structures are selection and repetition.
In selection, the program executes particular statements depending on some
condition(s). In repetition, the program repeats particular statements a certain
number of times based on some condition(s).
Relational Operators
To make decisions, you must be able to express conditions and make
comparisons. A relational operator allows you to make comparisons
(conditions) in a program.
In C++, a condition is represented by a logical (Boolean) expression. An
expression that has a value of either true or false is called a logical (Boolean)
expression. Moreover, true and false are logical (Boolean) values. Suppose i
and j are integers. Consider the expression:
i>j
20
Control Structures in C++ First Class
If this expression is a logical expression, it will have the value true if the value
of i is greater than the value of j; otherwise, it will have the value false.
C++ includes six relational operators that allow you to state conditions and
make comparisons. Table (3) lists the relational operators.
Operator Description
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Table (3): Relational Operators in C++
Notes:
• In C++, the symbol ==, which consists of two equal signs, is called the equality
operator. Recall that the symbol = is called the assignment operator.
• Each of the relational operators is a binary operator; that is, it requires two operands.
These operands must be of data type integers, float, character, and string.
Example:
Expression Meaning Value
8 < 15 8 is less than 15 true
6 != 6 6 is not equal to 6 false
2.5 > 5.8 2.5 is greater than 5.8 false
5.9 <= 7.5 5.9 is less than or equal to 7.5 true
Comparing Characters
For char values, whether an expression using relational operators evaluates to
true or false depends on a machine’s collating sequence. The collating
sequence of some of the characters is:
21
Control Structures in C++ First Class
Now, because 32 < 97, and the ASCII value of ' ' is 32 and the ASCII value of
'a' is 97, it follows that ' ' < 'a' is true. Similarly, using the previous ASCII
values:
note that comparing values of different data types may produce unpredictable
results. For example, the following expression compares an integer and a
character:
8 < '5'
In this expression, on a particular machine, 8 would be compared with the
collating sequence of '5', which is 53. That is, 8 is compared with 53, which
makes this particular expression evaluate to true.
Expressions such as 4 < 6 and 'R' > 'T' are examples of logical (Boolean)
expressions. When C++ evaluates a logical expression, it returns an integer
value of 1 if the logical expression evaluates to true; it returns an integer value
of 0 otherwise. In C++, any nonzero value is treated as true.
22
Control Structures in C++ First Class
Comparing strings
The relational operators can be applied to variables of type string. Variables of
type string are compared character by character, starting with the first
character and using the ASCII collating sequence. The character-by-character
comparison continues until either a mismatch is found or the last characters
have been compared and are equal. The following example shows how
variables of type string are compared.
Example:
Suppose that you have the statements:
string str1 = "Hello";
string str2 = "Hi";
string str3 = "Air";
string str4 = "Bill";
string str5 = "Big";
23
Control Structures in C++ First Class
Operator Description
! Not
&& And
|| Or
Table 4: Logical (Boolean) Operators in C++
Logical operators take only logical values as operands and yield only logical
values as results. The operator ! is unary, so it has only one operand. The
operators && and || are binary operators. Tables 5, 6, and 7 define the
operators ! (not), && (and), || (or).
Expression !(Expression)
true (nonzero) false (0)
false (0) true (1)
Table 5: The ! (Not) Operator
24
Control Structures in C++ First Class
Order of Precedence
Complex logical expressions can be difficult to evaluate. Consider the
following logical expression:
11 > 5 || 6 < 15 && 7 >= 8
Operators Precedence
!, +, - (unary operators) First
*, /, % Second
+, - Third
<, <=, >=, > Fourth
==, != Fifth
&& Sixth
|| Seventh
= (assignment operator) Last
Table 8: Precedence of Operators
Example:
Suppose you have the following declarations:
25
Control Structures in C++ First Class
!age false
age is 20, which is nonzero, so age is true. Therefore,
!age is false.
One-Way Selection
In C++, one-way selections are incorporated using the if statement. The syntax
of one-way selection is:
if (expression)
statement
26
Control Structures in C++ First Class
Note the elements of this syntax. It begins with the reserved word if, followed
by an expression contained within parentheses, followed by a statement. Note
that the parentheses around the expression are part of the syntax. The
expression is sometimes called a decision maker because it decides whether
to execute the statement that follows it. The expression is usually a logical
expression. If the value of the expression is true, the statement executes. If the
value is false, the statement does not execute and the computer goes on to the
next statement in the program. The statement following the expression is
sometimes called the action statement. Figure 4 shows the flow of execution
of the if statement (one-way selection).
Example:
The following C++ program finds the absolute value of an integer.
//Program: Absolute value of an integer
#include <iostream>
using namespace std;
int main()
{
int number, temp;
cout << "Line 1: Enter an integer: ";
cin >> number;
cout << endl;
temp = number;
if (number < 0)
27
Control Structures in C++ First Class
number = -number;
cout << "The absolute value of " << temp << " is " << number << endl;
return 0;
}
Two-Way Selection
to implement two-way selections, C++ provides the if. . .else statement. Two-
way selection uses the following syntax:
if (expression)
statement1;
else
statement2;
Take a moment to examine this syntax. It begins with the reserved word if,
followed by a logical expression contained within parentheses, followed by a
statement, followed by the reserved word else, followed by a second
statement. Statements 1 and 2 are any valid C++ statements. In a two-way
selection, if the value of the expression is true, statement1 executes. If the
value of the expression is false, statement2 executes. Figure 5 shows the flow
of execution of the if. . .else statement (two-way selection).
28
Control Structures in C++ First Class
Example:
//This program is to check a given integer number if it is divisible by 7 or not.
#include <iostream>
using namespace std;
main( )
{
int num;
cout<<”Please Enter The Number” <<endl ;
cin>>num ;
if (num % 7 == 0)
cout << “This number is divisible by 7”;
else
cout << “This number is not divisible by 7”;
system("pause");
return (0);
}
29
Control Structures in C++ First Class
{
statement_1 ;
statement_2 ;
.
.
.
statement_n ;
}
Example:
30
Control Structures in C++ First Class
Example:
This program is to check a given character (symbol) if it is lower case letter,
upper case letter, digit or other symbol?
#include <iostream>
#include<conio.h>
using namespace std;
main( )
{
char ch ;
cout<<”Please Enter Your Character”<<endl ;
cin>>ch ;
if (ch >=’a’ && ch<=’z’)
cout <<”this character is a small character” ;
else
if (ch >=’A’ && ch<=’Z’)
cout <<” this character is a capital character” ;
else
if (ch >=’0’ && ch<=’9’)
cout <<” this character is a digit character”;
else
cout<<”other symbol”;
system("pause");
return (0);
}
Note:
In C++, there is no stand-alone else statement. Every else must be paired with an if. The
rule to pair an else with an if is as follows:
Pairing an else with an if: In a nested if statement, C++ associates an else with the most
recent incomplete if—that is, the most recent if that has not been paired with an else.
31
Repetition in C++ First Class
while (expression)
statement ;
In C++, while is a reserved word. Of course, the statement can be either a simple
or compound statement. The expression acts as a decision maker and is usually
a logical expression. The statement is called the body of the loop. Note that the
parentheses around the expression are part of the syntax. Figure 6 shows the flow
of execution of a while loop.
If the expression evaluates to true, the statement executes. The loop condition
(the expression) is then reevaluated. If it again evaluates to true, the statement
executes again. The statement (body of the loop) continues to execute until the
expression is no longer true. A loop that continues to execute endlessly is called
an infinite loop.
32
Repetition in C++ First Class
Example:
Consider the following C++ program segment: (Assume that i is an int variable.)
i = 0;
while (i <= 20)
{
cout << i << " ";
i = i + 5;
}
Sample Run:
0 5 10 15 20
Notes:
• The variable (i) in the expression is called the loop control variable.
• If you omit the statement: i = i + 5;
from the body of the loop, you will have an infinite loop.
• You must initialize the loop control variable (i) before you execute the loop.
If the statement: i = 0; is omitted, the loop may not execute at all. (Recall that
variables in C++ are not automatically initialized.)
• If you put a semicolon at the end of the while loop, (after the logical expression), then
the action of the while loop is empty or null.
The next few sections describe the various forms of while loops.
Case 1: Counter-Controlled while Loops
In this form you must know exactly how many times certain statements need to
be executed. Suppose that a set of statements needs to be executed N times. You
can set up a counter (initialized to 0 before the while statement) to track how
many items have been read.
Before executing the body of the while statement, the counter is compared with
N. If counter < N, the body of the while statement executes.
example
Suppose you want to add these numbers and find their average. Consider the
following program:
//Program: Counter-Controlled Loop
33
Repetition in C++ First Class
#include <iostream>
using namespace std;
int main( )
{
int limit; //store the number of data items
int number; //variable to store the number
int sum; //variable to store the sum
int counter; //loop control variable
cout << "Enter the number of " << "integers in the list: ";
cin >> limit;
sum = 0;
counter = 0;
cout << "Enter " << limit << " integers." << endl;
while (counter < limit)
{
cin >> number;
sum = sum + number;
counter++;
}
cout << " The sum of the " << limit << " numbers = " << sum << endl;
if (counter != 0)
cout << "The average = "<< sum / counter << endl;
else
cout << "No input." << endl;
return 0;
}
34
Repetition in C++ First Class
Example:
Suppose you want to read some positive integers and average them, but you do
not have a preset number of data items in mind. Suppose the number -999 marks
the end of the data. You can proceed as follows.
cout << "Enter integers ending with "<< SENTINEL << endl;
cin >> number;
while (number != SENTINEL)
{
sum = sum + number;
count++;
cin >> number;
}
35
Repetition in C++ First Class
cout << "The sum of the " << count<< " numbers is " << sum << endl;
if (count != 0)
cout << "The average is "<< sum / count << endl;
else
cout << "No input." << endl;
return 0;
}
The variable found, which is used to control the execution of the while loop, is
called a flag variable.
Next example further illustrates the use of a flag-controlled while loop.
36
Repetition in C++ First Class
The program uses the bool variable isGuessed to control the loop. The bool
variable isGuessed is initialized to false. It is set to true when the user guesses
the correct number.
37
Repetition in C++ First Class
38
Repetition in C++ First Class
3- In cases other than (1) and (2), the input stream variable returns the logical
value true.
You can use the value returned by the input stream variable to determine
whether the program has reached the end of the input data. Because the input
stream variable returns the logical value true or false, in a while loop, it can be
considered a logical expression.
The following is an example of an EOF-controlled while loop:
cin >> variable; //initialize the loop control variable
while (cin) //test the loop control variable
{
.
.
cin >> variable; //update the loop control variable
.
.
}
Notice that here, the variable cin acts as the loop control variable.
The following code uses an EOF-controlled while loop to find the sum of a set of
numbers:
39
Repetition in C++ First Class
#include<iostream>
using namespace std ;
int main( )
{
int i = 1 , x , sum=0 ;
bool found = false ;
if ( found==true)
cout<<"7 is found and the summation = "<<sum ;
else
cout<<"7 is not found and the summation = "<<sum ;
system ("pause") ;
return (0) ;
}
Excersise:
1- Write a program that read N of number. Check if number 3 is
existing in the numbers read?
41
Repetition in C++ First Class
Example
The following for loop prints the first 10 nonnegative integers:
for (i = 0; i < 10; i++)
cout << i << " ";
Examples
1. The following for loop outputs Hello! and a star (on separate lines) five times:
for (i = 1; i <= 5; i++)
{
cout << "Hello!" << endl;
cout << "*" << endl;
}
42
Repetition in C++ First Class
• In a for statement, you can omit all three statements—initial statement, loop
condition, and update statement. The following is a legal for loop:
for ( ; ; )
cout << "Hello" << endl;
This is an infinite for loop, continuously printing the word Hello.
Example:
In this example, a for loop reads five numbers and finds their sum and average.
Consider the following program code, in which i, newNum, sum, and average
are int variables.
sum = 0;
for (i = 1; i <= 5; i++)
{
cin >> newNum;
sum = sum + newNum;
}
average = sum / 5;
cout << "The sum is " << sum << endl;
cout << "The average is " << average << endl;
Example:
The following C++ program finds the sum of the first n positive integers.
//Program to determine the sum of the first n positive integers.
#include <iostream>
using namespace std;
int main()
{
int counter; //loop control variable
int sum; //variable to store the sum of numbers
int n; //variable to store the number of first positive integers to be added
cout << "Enter the number of positive integers to be added: ";
cin >> n;
sum = 0;
for (counter = 1; counter <= n; counter++)
sum = sum + counter;
cout << "The sum of the first " << n<< " positive integers is " << sum;
return 0;
}
43
Repetition in C++ First Class
44
Repetition in C++ First Class
example
Suppose you want to create the following multiplication table:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
The multiplication table has five lines. Therefore we use a for statement to
output these lines as follows:
for (i = 1; i <= 5; i++)
//output a line of numbers
In the first line, we want to print the multiplication table of one, in the second
line we want to print the multiplication table of 2, and so on. Notice that the first
line starts with 1 and when this line is printed, i is 1. Similarly, the second line
starts with 2 and when this line is printed, the value of i is 2, and so on. If i is 1, i
* 1 is 1; if i is 2, i * 2 is 2; and so on. Therefore, to print a line of numbers, we
can use the value of i as the starting number and 10 as the limiting value. That is,
consider the following for loop:
for (j = 1; j <= 10; j++)
cout << i * j<<" ";
Let us take a look at this for loop. Suppose i is 1. Then we are printing the first
line of the multiplication table. Also, j goes from 1 to 10 and so this for loop
outputs the numbers 1 through 10, which is the first line of the multiplication
table. Similarly, if i is 2, we are printing the second line of the multiplication
table. Also, j goes from 1 to 10, and so this for loop outputs the second line of
the multiplication table, and so on. A little more thought produces the following
nested loops to output the desired grid:
45
Repetition in C++ First Class
Example
Consider the following data:
65 78 65 89 25 98 -999
87 34 89 99 26 78 64 34 -999
23 99 98 97 26 78 100 63 87 23 -999
62 35 78 99 12 93 19 -999
The number -999 at the end of each line acts as a sentinel and therefore is not
part of the data. Our objective is to find the sum of the numbers in each line and
output the sum.
This particular data set has four lines of input. So we can use a for loop or a
counter controlled while loop to process each line of data. Let us use a while
loop to process these four lines. It follows that the while loop takes the following
form:
counter = 0; //line 1
while (counter < 4) //line 2
{ //line 3
//process the line //line 4
//output the sum //line 5
counter++; //line 6
} //line 7
Let us now concentrate on processing a line. Each line has a varying number of
data items. For example, the first line has six numbers, the second line has eight
numbers, and so on. Because each line ends with -999, we can use a sentinel-
controlled while loop to find the sum of the numbers in each line. (Remember
how a sentinel-controlled loop works.) Consider the following while loop:
sum = 0; //line 4
cin>> num; //line 5
while (num != -999) //line 6
{ //line 7
sum = sum + num; //line 8
cin>> num; //line 9
} //line 10
46
Repetition in C++ First Class
The statement in Line 4 initializes sum to 0, and the statement in Line 5 reads
and stores the first number of the line into num. The Boolean expression num !=
-999 in Line 6 checks whether the number is -999. If num is not -999, the
statements in Lines 8 and 9 execute.
The statement in Line 8 updates the value of sum; the statement in Line 9 reads
and stores the next number into num. The loop continues to execute as long as
num is not -999. It now follows that the nested loop to process the data is as
follows. (Assume that all variables are properly declared.)
counter = 0; //Line 1
while (counter < 4) //Line 2
{ //Line 3
sum = 0; //Line 4
cin>> num; //Line 5
while (num != -999) //Line 6
{ //Line 7
sum = sum + num; //Line 8
cin >> num; //Line 9
} //Line 10
cout << "Line " << counter + 1<< ": Sum = " << sum << endl; //Line 11
counter++; //Line 12
} //Line 13
while (N >= 1)
{
//process each factorial
//apply the sum
// N = N – 1 ;
}
47
Repetition in C++ First Class
#include <iostream>
int main ( )
{
int i , j , fact , N , sum=0 ;
j = 1; fact = 1 ;
while (j <= N)
{
fact = fact * j ; process each factorial
j=j+1;
}
N=N–1;
}
Excersice :
1- Wrie a program to computer the following series:
4 4 4 4 4 4
Z=4− 3
+5−7+ 9
− 11 + 13
(use for statement)
48
Repetition in C++ First Class
Sol
#include <iostream.h>
#include<conio.h>
main( )
{
clrscr( );
int N ;
char ch ;
cout<<”Please Enter The Number of Character”<<endl ;
cin>>N , i ;
i=1;
While (i <= N)
{
cout<<”Please Enter Your Character”<<endl ;
cin>>ch ;
if (ch >=’a’ && ch<=’z’)
cout <<”this character is a small character” ;
else if (ch >=’A’ && ch<=’Z’)
cout <<” this character is a capital character” ;
else if (ch >=’0’ && ch<=’9’)
cout <<” this character is a digit character”;
else
cout<<”other symbol”;
i=i+1;
}
getch( );
return 0;
}
49
Repetition in C++ First Class
5- Write a program to read a number of marks for a student, for each mark,
check and print the following
50...59 print (Accept)
60...69 print (Medium)
70...79 print(Good)
80...89 print(Very Good)
90...100 print (Excellent)
0...50 print (Fail)
Sol
#include <iostream.h>
#include<conio.h>
main( )
{
clrscr( );
int N , i;
char ch ;
cout<<”Please Enter The Number Marks”<<endl ;
cin>>N ;
i=1;
While (i <= N)
{
cout<<”Please Enter Your Mark”<<endl ;
cin>>Mark ;
if (Mark >=50 && Mark <=59)
cout <<”Accept” ;
else if (Mark >=60 && Mark <=69)
cout <<”Medium” ;
else if (Mark >=70 && ch<=79)
cout <<”Good”;
else if (Mark >=80 && Mark <=89)
cout<<”Very Good”;
else if (Mark >=90 && Mark <=100)
cout<<”Excellent “ ;
else
cout<<”Fail” ;
i=i+1;
}
getch( );
return 0;
}
50
Repetition in C++ First Class
Sol
#include <iostream.h>
#include<conio.h>
main( )
{
clrscr( );
int X , Y ,i , Pow = 1 ;
cout<<”Please Enter The Number of X and Y”<<endl ;
cin>>X >>Y ;
for(i=1 ; i<Y ; i++)
Pow = Pow * X ;
cout<< X<<” to The Power ”<<Y<<” = “ << Pow ;
return (0) ;
}
51