Computer Programmming in C++
Computer Programmming in C++
2
3
4
5
Define the Problem
After careful reading, the problem should be divided into three
separate
component
Input
○ Data provided to the problem
Output
○ What is required from the solution
Processing
○ List of actions needed to produce the required
output
6 Design the Solution
There are more than 1 ways to do that but we will use a graphical approach
which will involve usage of Geometrical Shapes
to represent different kinds of steps in a solution
7
8 Step-2: Design the Solution
17
An algorithm can be written in pseudo code using six (6) basic computer
operations:
A computer can receive information.
Typical pseudocode instructions to receive information are:
Read name
Get name
Read number1, number2
A computer can output (print) information.
Typical pseudocode instructions are:
Print name
Write "The average is", avg
18
How to write Pseudocode(Cont…)
A computer can perform arithmetic operation
Typical pseudocode instructions:
Add number to total, or
Total = Total + Number
Avg = sum/total
A computer can assign a value to a piece of data:
e.g. to assign/give data an initial value:
Initialize total to zero
Set count to 0
To assign a computed value:
Total = Price + Tax
A computer can compare two (2) pieces of information and select one of two actions.
Typical pseudocode e.g.
19 IF number < 0 then
add 1 to neg_number
ELSE
add one to positive number
end-if
A computer can repeat a group of actions.
Typical pseudocode e.g.
REPEAT until total = 50
read number
write number
add 1 to total
end-repeat
OR
WHILE total < = 50 do:
read number
write number
end-while
Algorithmic Structure
20
Punctuation/Separators {}(),;
Punctuation defining the structure of a
program
Whitespace
Spaces of various sorts; ignored by the
Spaces, tabs, newlines, comments
compiler
Identifiers
35 A C++ identifier is a name used to identify a variable, function, class, module, or any other user-
defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers.
C++ is a case-sensitive programming language.
The rules of naming identifiers in C++ :
1. C++ is case-sensitive so that Uppercase Letters and Lower Case letters are different
2. The first character must be alphabit. However, Underscore can be used as first character while
declaring the identifier.
3. Only alphabetic characters, digits and underscore (_) are permitted in C++ language for
declaring identifier.
4. Other special characters are not allowed for naming a variable / identifier
5. Keywords cannot be used as Identifier.
36 Variable
A variable is a temporary container to store information, it is a named location in
computer memory where varying data like numbers and characters can be stored
and manipulated during the execution of the program".
For Example
int my_Age;
int my_Salary;
int _employee;
Variable attributes
A variable in a programming language represents a storage location. In C++,
each variable has six attributes, name, address, type, value, scope and the storage
class.
37 Constants in C++
A constant in C++ means an unchanging value and each constant has a type but does not
have location except the string constant.
Integer Constants
Integer constants consist of one or more digits such as 0,1,2,3,4 or -115. Floating point
constants contain a decimal point such as 4.15, -10.05. It can also be written in scientific
notation such as 1E-35 means 1*10^-35 or -1E35 means 1*10^35.
Character Constants
Character constants specify the numeric value of that particular character such as ‘a’ is the
value of a
String Constants
String constants consist of characters enclosed in double quotes such as
“Hello, World”
The string is stored in the memory and the numeric value of that constant is the address of this
memory. The string constant is suffixed by ‘\0’, (the null character) by the compiler.
Comments
38
Comments are portions of the code ignored by the compiler which allow the user to make
simple notes in the relevant areas of the source code. Comments come either in block form
or as single lines.
Single-line comments (informally, C++ style), start with // and continue until the end of
the line. If the last character in a comment line is a \ the comment will continue in the next
line.
Multi-line comments (informally, C style), start with /* and end with */.
•Reserve Words:
A reserved word is a word that cannot be used as an identifier, such as the
name of a variable, function, or label – it is "reserved from use".
They are reserved because they have been pre-assigned a specific meaning within that
programming language, thus the compiler recognizes those words to mean a specific
thing or action. Within C++ the reserved words are also known as "keywords".
e.g void, main, int etc….
39 C++ Data Types
C++ data Types
Unionn Pointer
Array
Float Double
char integer
40 Basic Data Types
Several of the basic types can be modified using one or more of these typemodifiers:
signed
unsigned
short
long
41 Basic Data Types
a. Character data: Any character of the ASCII character set can be considered as a character data
types and its maximum size can be 1 byte or 8 byte long. ‘Char’ is the keyword used to
represent character data type in C++. Char - a single byte size, capable of holding one
character.
b. Integer data: The keyword ‘int’ stands for the integer data type in C++ and its size is
either 2 or 4 bytes. The integer data type can again be classified as
1. Long int - long integer with more digits
2. Short int - short integer with fewer digits.
3. Unsigned int - Unsigned integer
4. Unsigned short int – Unsigned short integer
5. Unsigned long int – Unsigned long integer
c. Floating point data: - The numbers which are stored in floating point representation with
mantissa and exponent are called floating point (real) numbers. These numbers can be declared as
‘float’ in C++. float – Single – precision floating point number value.
d. Double data : - Double is a keyword in C++to represent double precision floating point
numbers.
42
43 Delimiters
This is symbol that has syntactic meaning and has got significance. These will not specify
any operation to result in a value.
44 Operators
An Operator is a symbol that operates on a certain data type. The data items that operators act upon
are called operands.
Unary operator: Operates on single operand, e.g Increment operator.
Binary Operators: Operates on two operands, e.g Arithmetic operator.
Ternary Operators: Operates on three operands, e.g conditional operator.
operators can be classified into various categories based on their utility and action.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operator
4. Assignment Operator
5. Increment & Decrement Operator
6. Conditional Operator
7. Bitwise Operator
8. Comma Operator
45 1. Arithmetic Operators
The Arithmetic operators performs arithmetic operations. The Arithmetic operators can
operate on any built in data type. A list of arithmetic operators are
Operator Meaning
+ Addition
- Subtraction
*
Multiplication
/ Division
% Modulo
division
2. Relational Operators
46
Relational Operators are used to compare arithmetic, logical and character expressions. The Relational
Operators compare their left hand side expression with their right hand side expression. Then evaluates to
an integer. If the Expression is false it evaluate to “zero”(0) if the expression is true it evaluate to “one”.
Operator Meaning
== Equal to
!= Not equal to
3. Logical Operators
47 A logical operator is used to evaluate logical and relational expressions. The logical operators act upon
operands that are themselves logical expressions. There are three logical operators, Operators Expression
(i) && Logical AND
(ii) || Logical OR
(iii) ! Logical NOT
(i) Logical And (&&): A compound Expression is true when two expression when two expressions are
true. The && is used in the following manner.
Exp1 && Exp2.
The result of a logical AND operation will be true only if both operands are true.
The results of logical operators are:
Exp1 Op. Exp2: Result
True && True True
True && False False
False && False False
False && True False
Example: a = 5; b = 10; c = 15;
Exp1 && Exp2 Result
1. ( a< b ) && ( b < c ) => True
48 3. Logical Operators
(ii) Logical OR: A compound expression is false when all expression are false otherwise the compound
expression is true. The operator “||” is used as It evaluates to true if either exp-1 or exp-2 is true. The truth
table of “OR” is
Exp1|| Exp2
Exp1 Operator Exp2 Result:
True || True True
True || False True
False || True True
False || False False
Example: a = 5; b = 10; c = 15;
Exp1 Exp2 Result
1. ( a< b ) || ( b < c ) => True
2. ( a> b ) || ( b < c ) => True
3. ( a< b ) || ( b > c ) => True
4. ( a> b ) || ( b > c ) => False
49 3. Logical Operators
(iii) Logical NOT: The NOT ( ! ) operator takes single expression and evaluates to true(1)
if the expression is false (0) or it evaluates to false (0) if expression is true (1). The general
form of the expression.
! ( Relational Expression )
The truth table of NOT :
Operator. Exp1 Result
! True False
! False True
Example: a = 5; b = 10; c = 15
1. !( a< b ) False
2. !( a> b ) True
4. Assignment Operator
50 An assignment operator is used to assign a value to a variable. The most commonly used assignment
operator is =. The general format for assignment operator is : <Identifer> = < expression >
Where identifier represent a variable and expression represents a constant, a variable or a
Complex expression. If the two operands in an assignment expression are of different data types,
then the value of the expression on the right will automatically be converted to the type of the identifier
on the left.
Example: Suppose that I is an Integer type Variable then
1. I = 3.3 3 ( Value of I )
2. I = 3.9 3 ( Value of I )
3. I = 5.74 5 ( Value of I )
Multiple assignment
< identifier-1 > = < identifier-2 > = - - - = < identifier-n > = <exp>;
Example: a,b,c are integers; j is float variable
1. a = b = c = 3;
2. a = j = 5.6; then a = 5 and j value will be 5.6
51 Compound Assignment Operator
The combination of Arithmatic operator and Assignment operator is called compound
assignment operator.
1. += e.g x+=10 can be written x=x+10
2. -= e.g x-=10 can be written x=x-10
3. *= e.g x*=10 can be written x=x*10
4. /= e.g x/=10 can be written x=x/10
5. %= e.g x%=10 can be written x=x%10
52 5. Increment & Decrement Operator
The increment/decrement operator act upon a Single operand and produce a new value is
also called as “unary operator”. The increment operator ++ adds 1 to the operand and the
Decrement operator – subtracts 1 from the operand.
Syntax: < operator >< variable name >;
The ++ or –- operator can be used in the two ways.
Example : ++ a; Pre-increment (or) a++ Post increment —a; Pre-
Decrement (or) a— Post decrement
1. ++ a Immediately increments the value of a by 1.
2. a ++ The value of the a will be increment by 1 after it is utilized.
53 6. Conditional operator (or) Ternary operator (? :)
It is called ternary because it uses three expressions. The ternary operator acts like If- Else
construction.
The conditional operator consists of 2 symbols the question mark (?) and the colon (:) The
syntax for a ternary operator is as follows.
exp1 ? exp2 : exp3
Example:
1. a = 5 ; b = 3;
( a> b ? cout (“a is larger”) : cout(“b is larger”));
Output is :a is larger
54 Decision Making Statement
Decision making statement is depending on the condition block need to be executed or not
which is decided by condition.
If the condition is "true" statement block will be executed, if condition is "false" then
statement block will not be executed.
In C++ language there are three types of decision making statement.
if
if-else
switch
55 Decision Making Statement
if-then Statement
if-then is most basic statement of Decision making statement. It tells to program to execute
a certain part of code only if particular condition is true.
Syntax
If(condition)
{ .......... .......... }
56 Decision Making Statement
57 Decision Making Statement
Example
#include<stdio.h>
#include<conio.h>
void main()
{ int time=10;
clrscr();
if(time>12)
{ cout<<"Good morning"; }
getch();
}
58 Decision Making Statement
Constructing the body of "if" statement is always optional, Create the body when we are
having multiple statements.
For a single statement, it is not required to specify the body.
If the body is not specified, then automatically condition part will be terminated with next
semicolon ( ; ).
59 Decision Making Statement
if-else statement
In general it can be used to execute one block of In the above syntax whenever
statement among two blocks, in C language if and else condition is true all the if block
are the keyword in C. statement are executed remaining
Syntax statement of the program by
neglecting else block statement. If
if(condition) the condition is false else block
statement remaining statement of
{ ........ statements ........ }
the program are executed by
Else neglecting if block statements.
{ ........ statements ........ }
60 Decision Making Statement
61 Decision Making Statement
Nested if...else
The if...else statement executes two different codes depending upon whether the test expression is true or false.
Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute different codes for
more than two conditions.
Syntax of Nested if...else
if (testExpression1)
{ // statements to be executed if testExpression1 is true }
else if(testExpression2)
{ // statements to be executed if testExpression1 is false and testExpression2 is true }
else if (testExpression 3)
{ // statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true }
else { // statements to be executed if all test expressions are false }
63 Decision Making Statement
Switch Statement
A switch statement work with byte, short, char and int primitive data type, it also works with enumerated types and
string.
Syntax
switch(expression/variable)
{
case value:
//statements
// any number of case statements
break; //optional
default: //optional
//statements
}
65 Decision Making Statement
break;
{ int ch;
case 6:
clrscr();
cout<<"Today is Saturday";
cout<<"Enter any number (1 to 7)";
break;
cin>>ch;
case 7: cout<<"Today is Sunday";
switch(ch)
break;
{ case 1: cout<<"Today is Monday"; break; default: cout<<"Only enter value 1 to 7";
case 2: cout<<"Today is Tuesday"; } getch();
break; }
case 3: cout<<"Today is Wednesday"; Output
break; Enter any number (1 to 7): 5 Today is Friday
68 LOOPS
Types of Loops.
There are three type of Loops available
in 'C' programming language.
while loop
for loop
do-while
70 LOOPS
While loop
In while loop First check the condition if
condition is true then control goes inside
the loop body other wise goes outside
the body. while loop will be repeats in
clock wise direction.
Syntax
while(condition)
{ Statements; ............
Increment/decrement (++ or --);
}
71 LOOPS
#include<iostream.h>
#include<conio.h>
Output:
void main() 1
{
int i; clrscr(); 2
i=1;
while(i<5)
3
{ cout<<endl<<i;
4
i++;
}
getch();
}
72 LOOPS
do-while in C++
A do-while loop is similar to a while loop, except
that a do-while loop is execute at least one time.
A do while loop is a control flow statement that
executes a block of code at least once, and then
repeatedly executes the block, or not, depending on
a given condition at the end of the block (in while).
Syntax
Do
{ Statements;
Increment or Decrements (++ or --)
}
while(condition);
73 LOOPS
#include<iostream.h> #include<conio.h>
Output
void main()
{ int i;
1
clrscr(); 2
i=1;
3
do { cout<<endl<<i; i++; }
while(i<5); 4
getch();
}
74 LOOPS
70 }
getch();
90
}
98
81 Array in C++ Language
{ {
list2[i]=list[i];
Int list[100],list2[100];
}//programology content
int n;
cout<<"copied array "<<endl;
int i,j;
for(i=0;i<n;i++)
cout<<" enter number till you wanna copy "<<endl;
cin>>n; cout<<list2[i]<<endl;
cout<<" enter list programology conetnt"<<endl; }
82 Array in C++ Language
{ { temp=a[j]; a[j]=a[j+1];
a[j+1]=temp;}
int i,a[10],temp,j;
}
clrscr(); }
cout<<"Enter any 10 num in array:\n"; cout<<"\nData after sorting: "; for(j=0;j<10;j++)
for(i=0;i<=10;i++) {cout<<a[j];}
getch(); }
{ cin>>a[i]; }
Enter any 10 num in array: 2 5 1 7 5 3 8 9 11 4
cout<<"\nData before sorting: "; Data After Sorting: 1 2 3 4 5 7 8 9 11
83 Array in C++ Language
Syntax
char variable_name[SIZE];
Char Example
char str[]="abcd";
Initializing Array string
OR
According to array initialization concept char str[5]="abcd";
str[5]; OR
char str[5]={'a','b','c','d','\0'};
OR
char str[]={'a','b','c','d','\0'};
OR
char str[5]={'a','b','c','d','\0'};
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121