0% found this document useful (0 votes)
43 views

Processing A C++ Program

1. A C++ program goes through several processing steps including editing, preprocessing, compiling, linking, loading, and execution. 2. The basic elements of a C++ program include functions, predefined functions like main(), syntax rules, and semantic rules. 3. Key components of a C++ program include comments, tokens like symbols, reserved words, and identifiers, and whitespaces to separate elements.

Uploaded by

Abu Kafsha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Processing A C++ Program

1. A C++ program goes through several processing steps including editing, preprocessing, compiling, linking, loading, and execution. 2. The basic elements of a C++ program include functions, predefined functions like main(), syntax rules, and semantic rules. 3. Key components of a C++ program include comments, tokens like symbols, reserved words, and identifiers, and whitespaces to separate elements.

Uploaded by

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

Basic Elements in C++ First Class

Processing a C++ Program


C++: is a programming language.
Programming language: A set of rules, symbols, and special words.
Source program: A program written in a high-level language.
The following steps, as shown in figure 1, are necessary to process 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.

4- The programs that you write are developed using an integrated


development environment (IDE). The IDE contains many programs that
are useful in creating your program. Once the program is developed and
successfully compiled, you must still bring the code for the resources used
from the IDE into your program to produce a final program that the
computer can execute. This prewritten code (program) resides in a place
called the library. A program called a linker combines the object
program with the programs from libraries to create the executable code.

5- You must next load the executable program into main memory for
execution. A program called a loader accomplishes this task.

6- The final step is to execute the program.

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

Figure 1: processing a C++ program

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.

using namespace std;


allows you to use cout and endl without the prefix std:: . It means that if you do
not include this statement, then cout should be used as std::cout and endl should
be used as std::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.

In the previous example, a C++ program contains various types of


expressions such as:

• String expression : Anything in double quotes is a string


• Arithmetic expression : 7 + 8 is an arithmetic expression.
• Constant expression : like 5
• Variable expression: like num

3
Basic Elements in C++ First Class

The Basics of a C++ Program


1- A C++ program is a collection of one or more subprograms, called
functions. Some functions, called predefined or standard functions.

2- Every C++ program has a function called main. Thus, if a C++ program
has only one function, it must be the function main.

3- To write meaningful programs, you must learn the programming


language’s special symbols, words, syntax rules, and semantic rules.

• Syntax rules tell you which statements (instructions) are legal, or


accepted by the programming language, and which are not.
• Semantic rules tell you which determine the meaning of the
instructions.

Function: is a collection of statements, and when it is executed, it accomplishes


something.

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:

• Mathematical symbols: include ( + - * / ) for addition, subtraction,


multiplication, and division.

• Punctuation marks: include ( . ; ? , ). These marks are taken from


English grammar. Note that the comma is also a special symbol. In C++,
commas are used to separate items in a list. Semicolons are used to end a
C++ statement. Note that a blank, which is not shown above, is also a
special symbol.

• Comparison symbols: include ( < <= > >= != == ) for less


than, less and equal, greater than, greater and equal, not equal, equal).

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

Table (1) shows some Illegal Identifier Description.

Illegal Identifier Description


employee Salary There can be no space between employee and Salary.
Hello! The exclamation mark cannot be used in an identifier
one + two The symbol + cannot be used in an identifier.
2nd An identifier cannot begin with a digit.
Table 1: Examples of Illegal Identifiers

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:

1- Write a program in C++ to calculate an area of any triangle.


(Hint: area = 1/2 * base * height)

2- Write a program in C++ to calculate the circumference of any rectangle.


Hint: cir = (width + height) * 2

3- Write a program in C++ to calculate the circumference and area of any


square. (hint: area = side * side
cir = side * 4 )

4- Write a program in C++ to calculate the value of Z where


Z = 1/2 * X * Y

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:

1. Simple data type


2. Structured data type
3. Pointers

C++ Data Types

Simple Structured Pointers

Figure 2: C++ data types

Simple Data Types


The simple data type is the fundamental data type in C++ because it becomes
a building block for the structured data type. The most important categories of
simple data:
1. int
Integers in C++ (take 4 bytes), as in mathematics, are numbers such as the
following:
-6728, -67, 0, 78, 36782, +763
Note the following two rules from these examples:
1. Positive integers do not need a + sign in front of them.
2. No commas are used within an integer. Recall that in C++, commas are
used to separate items in a list. So 36,782 would be interpreted as two
integers: 36 and 782.

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.

Structured Data Types (will be explain later).


Pointers (will be explain later).

8
Data Types in C++ First Class

Arithmetic Operators and Operator Precedence


One of the most important uses of a computer is its ability to calculate. You
can use the standard arithmetic operators to manipulate integral and floating-
point data types. There are five arithmetic operators.
+ (addition), - (subtraction or negation), * (multiplication), /(division),
% (mod, (modulus or remainder)).
You can use the operators +, -, *, and / with both integral and floating-point
data types.
You use % with only the integral data type to find the remainder in ordinary
division.

Ex:

• -5 Unary Operator

• 8-7 Binary Operator

The two arithmetic expression is constructed by using arithmetic operators


and numbers. The numbers appearing in the expression are called operands.

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.

For example, using the order of precedence rules,


3*7-6+2*5/4+6
means the following:

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

Two rules apply when evaluating a mixed expression:


1. When evaluating an operator in a mixed expression:
a. If the operator has the same types of operands (that is, either both
integers or both floating-point numbers), the operator is evaluated
according to the type of the operands. Integer operands thus yield an integer
result; floating-point numbers yield a floating-point number.
b. If the operator has both types of operands (that is, one is an integer and
the other is a floating-point number), then during calculation, the integer is
changed to a floating-point number with the decimal part of zero and the
operator is evaluated. The result is a floating point number.
2. The entire expression is evaluated according to the precedence rules; the
multiplication, division, and modulus operators are evaluated before the

10
Data Types in C++ First Class

addition and subtraction operators. Operators having the same level of


precedence are evaluated from left to right. Grouping is allowed for clarity.

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

Allocating Memory with Constants and Variables


When you instruct the computer to allocate memory, you tell it not only what
names to use for each memory location, but also what type of data to store in
those memory locations.

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:

dataType identifier, identifier, . . .;

12
Data Types in C++ First Class

Ex:
double amountDue;
int counter;
char ch;
int x, y;
string name;

Putting Data into Variables


In C++, you can place data into a variable in two ways:
1. Use C++’s assignment statement.
2. Use input (read) statements.

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.

// This program illustrates how data in the variables are manipulated.


#include <iostream>
#include <string>
using namespace std;
int main( )
{
int num1, num2;
double sale;
char first;
string str;
num1 = 4;
cout << "num1 = " << num1 << endl;
num2 = 4 * 5 - 11;

13
Data Types in C++ First Class

cout << "num2 = " << num2 << endl;


sale = 0.02 * 1000;
cout << "sale = " << sale << endl;
first = 'D';
cout << "first = " << first << endl;
str = "It is a sunny day.";
cout << "str = " << str << endl;
return 0;
}
Sample Run:
num1 = 4
num2 = 9
sale = 20
first = D
str = It is a sunny day.

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.

Input (Read) Statement


Previously, you learned how to put data into variables using the assignment
statement. In this section, you will learn how to put data into variables from
the standard input device, using C++’s input (or read) statements.
Putting data into variables from the standard input device is accomplished via
the use of cin and the operator >>. The syntax of cin together with >> is:
cin >> variable >> variable ...;

14
Data Types in C++ First Class

This is called an input (read) statement. In C++, >> is called the stream
extraction operator.

// This program illustrates how input statements work.


#include <iostream>
using namespace std;
int main()
{
int feet;
int inches;
cout << "Enter two integers separated by spaces: ";
cin >> feet >> inches;
cout << endl;
cout << "Feet = " << feet << endl;
cout << "Inches = " << inches << endl;
return 0;
}
Sample Run: In this sample run, the user input is 23 and 7
Enter two integers separated by spaces: 23 7
Feet = 23
Inches = 7

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


in this section, you will learn about two more operators: the increment and
decrement operators. Suppose count is an int variable. The statement:
count = count + 1; or count++;
increments the value of count by 1. To execute this assignment statement, the
computer first evaluates the expression on the right, which is count + 1. It then
assigns this value to the variable on the left, which is count.

Increment and decrement operators each have two forms, pre and post. The
syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++

The syntax of the decrement operator is:


Pre-decrement: – –variable
Post-decrement: variable– –

Let’s look at some examples. The statement:


++count; or: count++;
increments the value of count by 1.

Similarly, the statement:


– –count; or: count– –;
decrements the value of count by 1.

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.

Now, consider the following statements:


x = 5;
y = x++;
As before, the first statement assigns 5 to x. In the second statement, the post-
increment operator is applied to x. To execute the second statement, first the
value of x, which is 5, is used to evaluate the expression, and then the value of
x is incremented to 6. Finally, the value of the expression, which is 5, is stored
in y. After the second statement executes, the value of x is 6, and the value of
y is 5.

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.

On the other hand, after the execution of the following statements:


a = 5;
b = 2 + (a++);
The value of a is 6 while the value of b is 7.

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).

Figure 3: Flow of execution

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:

'R' > 'T' is false


'+' < '*' is false
'A' <= 'a' is true

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";

The following expressions show how string relational expressions evaluate.

Expression Value /Explanation


str1 < str2 true
str1 = "Hello" and str2 = "Hi". The
first characters of str1 and str2 are the
same, but the second character 'e' of
str1 is less than the second character
'i' of str2. Therefore, str1 < str2 is
true.
str1 > "Hen" false
str1 = "Hello". The first two
characters of str1 and "Hen" are the
same, but the third character 'l' of str1
is less than the third character 'n' of
"Hen". Therefore, str1 > "Hen" is
false.
str1 = = "hello" false
str1 = "Hello". The first character 'H'
of str1 is less than the first character
'h' of "hello" because the ASCII value
of 'H' is 72, and the ASCII value of 'h'
is 104. Therefore, str1 == "hello" is
false.

23
Control Structures in C++ First Class

Logical (Boolean) Operators and Logical Expressions


This section describes how to form and evaluate logical expressions that are
combinations of other logical expressions. Logical (Boolean) operators enable
you to combine logical expressions. C++ has three logical (Boolean)
operators, as shown in Table 4.

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

Expression1 Expression2 Expression1 && Expression2


true (nonzero) true (nonzero) true (1)
true (nonzero) false (0) false (0)
false (0) true (nonzero) false (0)
false (0) false (0) false (0)
Table 6: The && (And) Operator

Expression1 Expression2 Expression1 || Expression2


true (nonzero) true (nonzero) true (1)
true (nonzero) false (0) true (1)
false (0) true (nonzero) true (1)
false (0) false (0) false (0)
Table 7: The || (Or) 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

This logical expression yields different results, depending on whether || or &&


is evaluated first. If || is evaluated first, the expression evaluates to false. If
&& is evaluated first, the expression evaluates to true.
An expression might contain arithmetic, relational, and logical operators, as in
the expression: 5 + 3 <= 9 && 2 > 3

To work with complex logical expressions, there must be some priority


scheme for evaluating operators. Table 8 shows the order of precedence of
some C++ operators,

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:

bool found = true;


int age = 20;
double hours = 45.30;
double overTime = 15.00;
int count = 20;
char ch = 'B';
Consider the following expressions:

Expression Value / Explanation


!found false
Because found is true, !found is false.

25
Control Structures in C++ First Class

hours > 40.00 true


Because hours is 45.30 and 45.30 > 40.00 is true, the
expression hours > 40.00 evaluates to true.

!age false
age is 20, which is nonzero, so age is true. Therefore,
!age is false.

!found && (age >= 18) false


!found is false; age > 18 is 20 > 18 is true.
Therefore,!found && (age >= 18) is false && true,
which evaluates to false.

!(found && (age >= 18)) false


Now, found && (age >= 18) is true && true, which
evaluates to true. Therefore, !(found &&(age >= 18))
is !true, which evaluates to false.

Selection: if and if...else


Although there are only two logical values, true and false, they turn out to be
extremely useful because they permit programs to incorporate decision
making that alters the processing flow.
In C++, there are two selections, or branch control structures: if statements
and the switch structure. This section discusses how if and if...else
statements can be used to create
• One-way selection.
• Two-way selection.
• Multiple selections.

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).

Figure 4: 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;
}

Sample Run: In this sample run, the user input is shaded.


Enter an integer: -6734
The absolute value of -6734 is 6734
Note: Consider the following C++ statements:
if (score >= 60); //Line 1
grade = 'P'; //Line 2
Because there is a semicolon at the end of the expression (see Line 1), the if statement in
Line 1 terminates. The action of this if statement is null, and the statement in Line 2 is not
part of the if statement in Line 1. Hence, the statement in Line 2 executes regardless of
how the if statement evaluates.

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

Figure 5: two way selection

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

Compound (Block of) Statements


The if and if. . .else structures control only one statement at a time. Suppose,
however, that you want to execute more than one statement if the expression
in an if or if. . .else statement evaluates to true. To permit more complex
statements, C++ provides a structure called a compound statement or a block
of statements. A compound statement takes the following form:

{
statement_1 ;
statement_2 ;
.
.
.
statement_n ;
}

That is, a compound statement consists of a sequence of statements enclosed


in curly braces, {and }.

Example:

if (age >= 18)


{
cout << "Eligible to vote." << endl;
cout << "No longer a minor." << endl;
}
else
{
cout << "Not eligible to vote." << endl;
cout << "Still a minor." << endl;
}

30
Control Structures in C++ First Class

Multiple Selections: Nested if


Some problems require the implementation of more than two alternatives. You
can include multiple selection paths in a program by using an if. . .else
structure if the action statement itself is an if or if. . .else statement. When one
control statement is located within another, it is said to be nested. The next
example illustrates how to incorporate multiple selections using a nested if. .
.else structure.

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 Looping (Repetition) Structure


Sometimes it is necessary to repeat a set of statements several times. If you want
to repeat a set of statements 100 times, you type the set of statements 100 times
in the program. However, this solution of repeating a set of statements is
impractical, if not impossible. Fortunately, there is a better way to repeat a set of
statements. C++ has three repetitions, or looping, structures that allow you to
repeat a set of statements until certain conditions are met.
The general form of the while statement is:

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.

figure 6 : 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;
}

Sample Run: In this sample run, the user input is shaded.


Enter the number of integers in the list: 12
Enter 12 integers.
8 9 2 3 90 38 56 8 23 89 7 2
The sum of the 12 numbers = 335
The average = 27

34
Repetition in C++ First Class

Case 2: Sentinel-Controlled while Loops


You do not always know how many pieces of data (or entries) need to be read,
but you may know that the last entry is a special value, called a sentinel. In this
case, you read the first item before the while statement. If this item does not
equal the sentinel, the body of the while statement executes. The while loop
continues to execute as long as the program has not read the sentinel. Such a
while loop is called a sentinel controlled while loop. In this case, a while loop
might look like the following:

cin >> variable; //initialize the loop control variable


while (variable != sentinel) //test the loop control variable
{
.
.
cin >> variable; //update the loop control variable
.
.
}

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.

//Program: Sentinel-Controlled Loop


const int SENTINEL = -999;
int main()
{
int number; //variable to store the number
int sum = 0; //variable to store the sum
int count = 0; //variable to store the total numbers read

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;
}

Sample Run: In this sample run, the user input is shaded.


Enter integers ending with -999
34 23 9 45 78 0 77 8 3 5 -999
The sum of the 10 numbers is 282
The average is 28

Case 3: Flag-Controlled while Loops


A flag-controlled while loop uses a bool variable to control the loop. Suppose
found is a bool variable. The flag-controlled while loop takes the following
form:

found = false; //initialize the loop control variable


while (!found) //test the loop control variable
{
.
.
if (expression)
found = true; //update the loop control variable
.
.
}

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

Example: Number Guessing Game


The following program randomly generates an integer greater than or equal to 0
and less than 100. The program then prompts the user to guess the number. If the
user guesses the number correctly, the program outputs an appropriate message.
Otherwise, the program checks whether the guessed number is less than the
random number. If the guessed number is less than the random number
generated by the program, the program outputs the message ‘‘Your guess is
lower than the number. Guess again!’’; otherwise, the program outputs the
message ‘‘Your guess is higher than the number. Guess again!’’. The program
then prompts the user to enter another number. The user is prompted to guess the
random number until the user enters the correct number. To generate a random
number, you can use the function rand of the header file cstdlib. For example,
the expression rand() returns an int value between 0 and 32767.

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.

//Flag-controlled while loop.


//Number guessing game.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int num; //variable to store the random number
int guess; //variable to store the number guessed by the user
bool isGuessed; //boolean variable to control the loop
srand(time(0));
num = rand() % 100;
isGuessed = false;
while (!isGuessed)
{
cout << "Enter an integer greater"<< " than or equal to 0 and "<< "less than 100:";
cin >> guess;
cout << endl;
if (guess == num)
{
cout << "You guessed the correct "<< "number." << endl;
isGuessed = true;
}

37
Repetition in C++ First Class

else if (guess < num)


cout << "Your guess is lower than the "<< "number.\n Guess again!"<< endl;
else
cout << "Your guess is higher than "<< "the number.\n Guess again!"<< endl;
} //end while
return 0;
}

Sample Run: In this sample run, the user input is shaded.


Enter an integer greater than or equal to 0 and less than 100: 45
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 20
Your guess is lower than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 35
Your guess is higher than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 28
Your guess is lower than the number.
Guess again!
Enter an integer greater than or equal to 0 and less than 100: 32
You guessed the correct number.

Case 4: EOF-Controlled while Loops


If the data file is frequently altered (for example, if data is frequently added or
deleted), it’s best not to read the data with a sentinel value. Someone might
accidentally erase the sentinel value or add data past the sentinel, especially if
the programmer and the data entry person are different people. Also, it can be
difficult at times to select a good sentinel value. In such situations, you can use
an end-of-file (EOF)-controlled while loop.
Until now, we have used an input stream variable, such as cin, and the extraction
operator, >>, to read and store data into variables. However, the input stream
variable can also return a value after reading data, as follows:
1- If the program has reached the end of the input data, the input stream variable
returns the logical value false.
2- If the program reads any faulty data (such as a char value into an int variable),
the input stream enters the fail state. In this case, the input stream variable
returns the value false.

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:

int sum = 0 , num;


cin >> num;
while (cin)
{
sum = sum + num; //Add the number to sum
cin >> num; //Get the next number
}
cout << "Sum = " << sum << endl;

39
Repetition in C++ First Class

multiple conditions in while loop

example: write a program to find the summation of 10 numbers or find the


summation until reaches to number 7 .

#include<iostream>
using namespace std ;
int main( )
{
int i = 1 , x , sum=0 ;
bool found = false ;

while (i <= 10 && found == false)


{
cout<<"Please Enter Your Number"<<endl ;
cin>> x ;
sum = sum + x ;
if (x==7)
found = true ;
i=i+1;
}

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?

2- Write a program to check a given number if it is prime or not?

3- Write a program that reads your birthday (day-month-year).


Calculate your age in (day – month – year). Hint: remember, you will
benefit from the current date.
40
Repetition in C++ First Class

for Looping (Repetition) Structure


The C++ for looping structure discussed here is a specialized form of the while
loop. Its primary purpose is to simplify the writing of counter-controlled loops.
For this reason, the for loop is typically called a counted or indexed for loop.

The general form of the for statement is:

for (initial statement; loop condition; update statement)


statement ;

Figure 7 shows the flow of execution of a for loop.

Figure 7: for loop

The for loop executes as follows:


1. The initial statement executes.
2. The loop condition is evaluated. If the loop condition evaluates to true:
i. Execute the for loop statement.
ii. Execute the update statement (the third expression in the parentheses).
3. Repeat Step 2 until the loop condition evaluates to false.
The initial statement usually initializes a variable (called the for loop control, or
for indexed, variable).
In C++, for is a reserved word.

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 << " ";

A for loop can have either a simple or compound statement.

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;
}

2. Consider the following for loop:


for (i = 1; i <= 5; i++)
cout << "Hello!" << endl;
cout << "*" << endl;
This loop outputs Hello! five times and the star only once. Note that the for loop
controls only the first output statement because the two output statements are not
made into a compound statement. Therefore, the first output statement executes
five times because the for loop body executes five times. After the for loop
executes, the second output statement executes only once. The indentation,
which is ignored by the compiler, is nevertheless misleading.
The following are some comments on for loops:
• If the loop condition is initially false, the loop body does not execute.
• The update expression, when executed, changes the value of the loop control
variable (initialized by the initial expression), which eventually sets the value
of the loop condition to false. The for loop body executes indefinitely if the
loop condition is always true.
• C++ allows you to use fractional values for loop control variables of the
double type (or any real data type). Because different computers can give
these loop control variables different results, you should avoid using such
variables.
• A semicolon at the end of the for statement (just before the body of the loop)
is a semantic error. In this case, the action of the for loop is empty.
• In the for statement, if the loop condition is omitted, it is assumed to be true.

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

Sample Run: In this sample run, the user input is shaded.


Enter the number of positive integers to be added: 100
The sum of the first 100 positive integers is 5050

Nested Control Structures (Nested Loop)


In this section, we give examples that illustrate how to use nested loops to
achieve useful results and process data.
example
Suppose you want to create the following pattern:
*
**
***
****
*****
Clearly, you want to print five lines of stars. In the first line, you want to print
one star, in the second line, two stars, and so on. Because five lines will be
printed, start with the following for statement:
for (i = 1; i <= 5; i++)
The value of i in the first iteration is 1, in the second iteration it is 2, and so on.
You can use the value of i as the limiting condition in another for loop nested
within this loop to control the number of stars in a line. A little more thought
produces the following code:
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
cout << "*";
cout << endl;
}

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:

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


{
for (j = 1; j <= 10; j++)
cout << i * j<<" ";
cout << endl;
}

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

example: Write a program to calculate the following series


S = N! + (N-1)! + (N-2)! + (N-3)! ………. + 1

The algorithm for solving this series is as follows:

cout<< "Please Enter The Value of N"<<endl ;


cin<<N ;

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 ;

cout<<"Please Enter the Value of N"<<endl ;


cin>> N ;
while (N >= 1)
{

j = 1; fact = 1 ;
while (j <= N)
{
fact = fact * j ; process each factorial
j=j+1;
}

Sum = sum + fact ; apply the sum

N=N–1;
}

cout<<"the summation of this series is " <<sum ;


system ("pause");
return (0) ;
}

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)

2- Write a program to find the following series


S = 𝟐𝟐𝟏𝟏 + 𝟐𝟐𝟐𝟐 + 𝟐𝟐𝟑𝟑 … … … + 𝟐𝟐𝟏𝟏𝟏𝟏

3- Write a program to get sum of all odd numbers in a given range.

48
Repetition in C++ First Class

4- Write a program to read a number of character, for each one, check a


character (symbol) if it is lower case letter, upper case letter, digit or other
symbol?

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

6- Write a program to find the factorial of a given number (N!)


Sol
#include <iostream.h>
#include<conio.h>
main( )
{
clrscr( );
int N ,i , fact = 1 ;
cout<<”Please Enter The Number”<<endl ;
cin>>N ;
for(i=N ; i>0 ; i--)
fact = fact * i ;
cout<< ” The Factorial of ”<<N<<” = “ << fact ;
return (0) ;
}

7- Find X to the power Y (X Y ) where X and Y is an integer numbers.

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

You might also like