Brief Note of C++ CH

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 91

Chapter Two

Structure of C++ program


Basics of C++

Documentation Section: comment parts, which are ignored by


compiler. The comments are used to describe the functionality of
each statement in the program

Syntax: //This statement is a single line comment

/*This is multiline comment*/

Link section: link the necessary files and libraries to current


files by the preprocessor.

Syntax: #include<file or library name>

Fundamental of programming I 2
Cont..

Definition Section: It is possible to define symbolic constants.

Syntax: #define identifier constant

Global declaration Section: variables declared under this section are


available throughout the program.

main ( ) function:

 the execution of the program starts from main function.

 Every program must have only one main function.

All other functions are called either directly or indirectly from main.

Fundamental of programming I 3
Syntax and Semantics

 Syntax :

consists of the rules for the correct use of the language.

This involves the correct grammatical construction and


arrangement of the language, correct spelling.

Fundamental of programming I 4
Cont..

Semantics:
deal with the meanings given to syntactically correct
constructs of the language.
is defined in terms of the program’s run-time behavior
A program could be syntactically correct yet meaningless
Example
sum=0;
while (sum!=-1)
sum=sum+10;

Fundamental of programming I 5
The parts of a simple C++ Program

 C++ program file should be saved with file name

extension “ .CPP ”

#-is a signal to the preprocessor

include - is a preprocessor instruction that directs the

compiler to include a copy of the file specified in the angle

brackets in the source code.

Fundamental of programming I 6
Cont..

{ } : signals the beginning of the main function body and the

end of the main function body

; statement ends with semicolon

Cout: is an object used for printing data to the screen.

followed by the insertion operator also called output

redirection operator (<<)

Syntax: cout<<Object;
Fundamental of programming I 7
Cont..

Cin:
used for taking input from the keyboard. followed by
the input redirection operator (>>) also called
extraction operator.
take value from the keyboard and store it in the
memory
• Syntax: cin>>Object

Fundamental of programming I 8
Comments on C++ programs
 text which explains some aspect of a program.

Ignored by the compiler

C++ provides two types of comment

Single Line Comment:

Example

cout<<var1; //this line prints the value of var1

Fundamental of programming I 9
Cont..
Multiple Line Comment:

Eg:

/*this is a kind of comment where

Multiple lines can be enclosed in

one C++ program */

Fundamental of programming I 10
Variables and Constants

Variable:

is a reserved place in memory to store information in.

are used for holding data values

All variables have three important properties:

Fundamental of programming I 11
Cont..

• Data Type:describes the property of the data and the


size of the reserved memory
• Name: used to refer to the value in the variable
• Value: assigning a new value to the variable

Fundamental of programming I 12
Declaring Variables

Variables can be created in a process known as


declaration.
Syntax: Datatype Variable_Name;

Keywords

 having a predefined meaning in the language and we


cannot use them as variable names or any other purpose
other than their predefined usage.

Fundamental of programming I 13
Initializing Variables

When declaring a variable, its value is by default


undetermined.

When a variable is assigned a value at the time of


declaration, it is called variable initialization

The syntax is:

Data Type variable name = initial value;

Fundamental of programming I 14
Scope of Variables

 There are two types of variable visibilities.

 Global variables: are variables that can be referred/


accessed anywhere in the code, when any function, as long
as it is declared first.

• A variable declared before any function immediately after


the include statements are global variables.

Fundamental of programming I 15
Example
Let's see an example of a global variable.
#include <iostream>
using namespace std;
int g;
int main()
{
int a = 4;
g=a*2
; cout << g << endl;
return 0;
}

Here, g is a global variable since it is declared outside of the main function. Thus unlike the
local variable 'a' which can only be used in the function main, 'g' can be used throughout the
program and can be used in all the functions in the program.
Fundamental of programming I 16
Cont..

Local Variables:

• the scope of the local variable is limited to the code level or


block within which they are declared.

Fundamental of programming I 17
#

Example : Local variable


#include <iostream>
using namespace std;
void test();
int main()
{
// local variable to main()
int var = 5;
}
void test()
{ // local variable to test()
int var1;
var1 = 6;
// illegal: var not declared inside test()
cout << var;
}

Fundamental of programming I 18
Characters
• Char in C++ are represented as any value inside a single
quote

• Example: ‘x’, ‘A’, ‘5’, ‘a’, etc.

Expressions and Statements

• All C++ statements end with a semicolon(;).

• An expression is any computation which yields a value.

Fundamental of programming I 19
Operators

is a symbol that makes the machine to take an action.

C++ provides several categories of operators.

• Assignment operator

• Arithmetic operator

• Relational operator

Fundamental of programming I 20
Cont..

• Logical operator

• Increment/decrement operator

• The size of operator

Fundamental of programming I 21
Assignment operator (=)
Syntax: Operand1=Operand2;
Operand1 : is always a variable
Operand2: can be one or combination of:
 A literal constant: Example: x=12;
 A variable: Example: x=y;
 An expression: Example: x=y+2;

Fundamental of programming I 22
Cont..
Compound assignment operators: (+=, -=, *=, /=, %=, >>=,
<<=, &=, ^=)

• is the combination of the assignment operator with other


operators like arithmetic and bit wise operators.

Example:

• sum+= i; sum= sum+ i;

• a -= 5; a = a – 5;

• a /= b; a = a / b;

• price *= units + 1 price = price * (units + 1);


Fundamental of programming I 23
Arithmetic operators (+, -, *, /, %)
Integer division always results in an integer outcome.
Division of integer by integer will not round off to the next
integer.
Example
9/2 gives 4 not 4.5
-9/2 gives -4 not -4.5
remainder or modulo (%): is an operator that gives the
remainder of a division of two integer values.
Example
a = 11 % 3
a is 2

Fundamental of programming I 24
Relational operator (==, !=, > , <, >=, <=)

is a comparison of two expressions

The result of a relational operator is a Boolean value that


can only be true or false

Example

• (7 = = 5)would return false or returns 0

• (5 > 4) would return true or returns 1

• ‘A’ < ‘F’ would return true or 1. it is like (65 < 70)

Fundamental of programming I 25
Logical Operators (!, &&, ||)
Logical negation (!)
• is a unary operator.

• negates the logical value of its operand.

• If its operand is non zero, it produces 0, and if it is 0 it


produce 1.

Example :

  !20 //gives 0

Fundamental of programming I 26
Cont..
Logical AND (&&)
• produces 0 if one or both of its operands evaluate to 0
otherwise it produces 1.

Example :

10 && 5 //gives 1

10 && 0 // gives 0

Fundamental of programming I 27
Cont..

Logical OR (||)
• produces 0 if both of its operands evaluate to 0 otherwise, it
produces 1.

Example :

10 || 5.5 //gives 1

10 && 0 // gives 1

Fundamental of programming I 28
Increment/Decrement Operators: (++) and (--)
The auto increment (++): adding 1 from a numeric variable.

auto decrement (--) :subtracting 1 from a numeric variable.

Example

• If a=10 a++ gives 11 and a-- gives 9

Fundamental of programming I 29
Prefix and Postfix:
prefix :

• is written before the variable.

• is evaluated before the assignment.

postfix :

• appears after the variable name.

• is evaluated after the assignment.


• Prefix and postfix operators can not be used at once on a single

variable.
Fundamental of programming I 30
Example

int k = 5;

(auto increment prefix) y= ++k + 10; //gives 16 for y

(auto increment postfix) y= k++ + 10; //gives 15 for y

(auto decrement prefix)y= --k + 10; //gives 14 for y

(auto decrement postfix) y= k-- + 10; //gives 15 for y

Fundamental of programming I 31
The size of() Operator

used for calculating the size of any data item or type.


It takes a single operands
The outcome is totally machine dependent.

Example:

a = size of(char)

b = size of(int)

Fundamental of programming I 32
 
Operator Precedence

Operators in higher levels take precedence over operators in


lower levels.

Fundamental of programming I 33
Precedence Table:

Fundamental of programming I 34
Cont..

Fundamental of programming I 35
Example
•a = = b + c * d

• a = = (b + c) * d

Fundamental of programming I 36
Individual Assignment Two
1. What is the precedence when there are a global variable in
the program with the same name?
2. What is C++?
3. What is the difference between user defined and
predefined headers?
4. What are the different data types present in C++?
5. Write a C++ program to calculate area and perimeter of
parallelogram
6. Write a C++ program to enter velocity, Acceleration and
Time and print the final velocity using the formula:
V = u+a*t

Fundamental of programming I 37
Chapter Three
Control Flow

Fundamental of programming I 38
Control Flow
»Program flow is a general term which describes the order in
which your lines of code are executed. This means that some lines
will only be read once, some multiple times, and others may be
skipped completely, depending on the situation

»Control statements are elements in the source code

that control the flow of program execution. They include


blocks using { and } brackets, loops using for, while and
do while, and decision-making using if and switch.
Fundamental of programming I 39
Cont..

»Control flow or flow of control is the order in which


instructions, statements and function calls being executed or
evaluated when a program is running.

»In C++, flow control in a program is typically


sequential, from one statement to the next(top to
bottom).

Fundamental of programming I 40
Sequential statements 

»Sequential statements define algorithms for the


execution within a process or a subprogram. They
belong to the conventional notions of sequential
flow, control, conditionals, and iterations in the high
level programming languages

Fundamental of programming I 41
Sequential statements 

• Types of Control Flow Statements

• Selection statements/ Conditional statements.

• Iteration statements/ Looping statements.

• Jump statements

Fundamental of programming I 42
Selection statements/ Conditional statements
»Selection statements are statements in a program where there
are points at which the program will decide at runtime
whether some part of the code should or should not be
executed.

»Used for making decisions. Which Depending on the value


of an expression decision can be made.
»There are two types of selection statements in C++, which
are the “if statement” and the “switch statement
Fundamental of programming I 43
If statement
» The different forms of the ‘If” statement will be used to
decide whether to execute part of the program based on a
condition which will be tested either for TRUE or FALSE
result.
»The different forms of the “If” statement are:
• The simple if statement
• The if else statement
• The if else if statement
• Nesting If statements

Fundamental of programming I 44
The simple if statement
»The simple if statement will decide only one part of the
program to be executed if the condition is satisfied or
ignored if the condition fails.
»The General Syntax is:
if (expression)

Statements;

Fundamental of programming I 45
Cont..

»In any “if” statement, first the “expression” will be evaluated


and if the outcome is non zero (which means TRUE), then the
“statements” is executed. Otherwise, nothing happens and
execution resumes to the line immediately after the “if” block.

Example

if(age>18)

cout<<”you are an adult”;

Fundamental of programming I 46
The if else statement
»Another form of the “if” is the “if …else” statement.
»The “if else” statement allows us to specify two alternative
statements:
• One which will be executed if a condition is satisfied and
• Another which will be executed if the condition is not satisfied.
• The General Syntax is:
if (expression)
statements1;
else
statements2;

Fundamental of programming I 47
Cont..

»First “expression” is evaluated and if the outcome is none


zero (true), then “statements1” will be executed. Otherwise,
which means the “expression” is false “statements2” will be
executed.

Example1
if(age>18)// expression
cout<<”you are an adult”;// statements1
else
cout<<”You are a kid”;// statements2
Fundamental of programming I 48
Cont..
Example 2
int x;
cout<<”Enter a number: “;
cin>>x;
if(x%2==0)
cout<<”The Number is Even”;
else
cout<<”The Number is Odd”;

Fundamental of programming I 49
The “if else if” statement

»The third form of the “if” statement is the “if …else if”
statement.
»The “if else if” statement allows us to specify more than
two alternative statements each will be executed based on
testing one or more conditions.

Fundamental of programming I 50
Cont..
The General Syntax is:
if (expression1)
statements1;
else if(expression2)
statements2;
.
.
.
else if(expressionN)
statementsN;
else
statements

Fundamental of programming I 51
Cont..
»First “expression1” is evaluated and if the outcome is none
zero (true), then “statements1” will be executed. Otherwise,
which means the “expression1” then “expression2” will be
evaluated: if the output of expression2 is True then
“statements2” will be executed otherwise the next
“expression” in the else if statement will be executed and so
on.
»If all the expressions in the “if” and “else if” statements are
False then “statements” under else will be executed.
Fundamental of programming I 52
Cont..
Example
if(score >= 90)
cout<< “\n your grade is A”;
else if(score >= 80)
cout<< “\n your grade is B”;
else if(score >= 70)
cout<< “\n your grade is C”;
else if(score >= 60)
cout<< “\n your grade is D”;
else
cout<< “\n your grade is F”;

Fundamental of programming I 53
Nesting If statements within another if statement
»One or more if statements can be nested with in another if
statement.
»The nesting will be used to test multiple conditions to
perform a task.
»It is always recommended to indent nested if statements to
enhance readability of a program

Fundamental of programming I 54
Cont..
The General Syntax :
if (expression1)
{
if (expression2)
statementsN;
else
statementsM;
}
else
{
if (expression3)
statementsR;
else
statementsT;
}
Fundamental of programming I 55
Cont..
Example if(x>z)
cout<<“X is maximum”;
int main() else
{ cout<<“z is maximum”;
}
int x, y, z; Else{
cout<<”\n Enter the If(y>z)
three tnumbers :”; cout<<“y is maximum”;
Else
cin>>x>>y>>z; cout<<“z is maximum”;
if(x >y) return 0;
}
{

Fundamental of programming I 56
The Switch Statement
»Another C++ statement that implements a selection control
flow is the switch statement (multiple-choice statement).
»The switch statement provides a way of choosing between a
set of alternatives based on the value of an expression. The
general form of the switch statement is:

Fundamental of programming I 57
Cont..

• The switch statement has four components:


• Switch
• Case
• Default
• Break
Where Default and Break are Optional

Fundamental of programming I 58
Cont..
• The General Syntax might be:
switch(expression)
{
case constant1:
statements;
.
.
case constant n:
statements;
default:
statements;
}
Fundamental of programming I 59
Cont..

»The output of “expression” should always be a constant


value.
»First expression is evaluated, and the outcome, which is a
constant value, will compared to each of the numeric
constants in the case labels, in the order they appear, until a
match is found.

Fundamental of programming I 60
Cont..
»After one case is satisfied, execution continues until either a
break statement is encountered or all intervening statements
are executed, which means until the execution reaches the
right French bracket of the switch statement.

»The final default case is optional and is exercised if none of


the earlier cases provide a match. This means that, if the
value of the “expression” is not equal to any of the case
labels, then the statements under default will be executed.
Fundamental of programming I 61
Cont..
Example
switch(operator)
{ case ‘*’: result = operand1 *
operand2;
case ‘+’: result = operand1 + operand2;
break;
break;
case ‘/’: result = operand1 /
case ‘-’ : result = operand1 – operand2;
operand2;
break;
break;
default: cout<<“ unknown
operator:”<<operator<<“\n”;
}

Fundamental of programming I 62
Cont..
Example 2: display 5 working days using switch statement
switch (day){
case 1:
cout<<“the day is Monday:”<<endl;
break;
case 2:
cout<<“the day is tuesday:”<<endl;
break;
case 3:
cout<<“the day is wednesday:”<<endl;
break;
case 4:
cout<<“the day is thursday:”<<endl;
break;
case 3:
cout<<“the day is friday:”<<endl;
break;
default: cout<<“ unknown”<<endl;
}
Fundamental of programming I 63
Loop Statements/ Repetition

»Repetition statements control a block of code to be executed


repeatedly for a fixed number of times or until a certain
condition fails.
»Loops are handy b/c they save time, reduce errors, they
make code more readable.
»There are three C++ repetition statements:
The For Statement or loop
The While statement or loop
The do…while statement or loop

Fundamental of programming I 64
The for statement / loop
 The “for” statement (also called loop) is used to
repeatedly execute a block of instructions until a specific
condition fails.
 The General Syntax is:
for(expression1 ; expression2 ; expression3)
statements;

Fundamental of programming I 65
Cont..

 The for loop has three expressions:


 expression1: is one or more statements that will be
executed only once and before the looping starts.
Expression2: is the part that decides whether to proceed
with executing the instructions in the loop or to stop.
Expression2 will be evaluated each time before the loop
continues. The output of expression2 should be either
non zero (to proceed with the loop) or zero (to stop the
loop) to represent true and false output respectively.
 Expression3: is one or more statements that will be
executed after each iteration.

Fundamental of programming I 66
Cont..
 Thus, first expression1 is evaluated and then each time
the loop is executed, expression2 is evaluated. If the
outcome of expression2 is non zero then statements is
executed and expression3 is evaluated. Otherwise, the
loop is terminated.
 In most programs, the “for loop” will be used for such
expressions where expression1 is initialization,
expression2 is condition and expression3 is either
increment or decrement.

Fundamental of programming I 67
Cont..
 The general format
for(initialization ; condition ; increase/decrease)
statement;
Steps of execution of the for loop:
1. Initialization is executed. (will be executed only once)
2. Condition is checked, if it is true the loop continues,
otherwise the loop finishes and statement is skipped.
3. Statement is executed.
4. Finally, whatever is specified in the increase or decrease
field is executed and the loop gets back to step two.

Fundamental of programming I 68
Cont..
 Example :
for(n=0,i=100; n!=i; n++,i--)
{
//whatever here
}
NB: for loop is used for definite loops when the
number of iteration is known.

Fundamental of programming I 69
Cont..

Example 1

• for statement adds the numbers between 0 and n


int Sum=0;
for(int i=0; i<=n;i++)
{
Sum=Sum+i;
}
cout<<Sum;

Fundamental of programming I 70
Cont..
Example 2
• for statement adds the even numbers between 0 and n
#include<iostream.h>
int main()
{

int Sum=0;
for(int i=1; i<=4; i+=2)
{
Sum=Sum+i;

}
cout<<Sum;
return 0;
}
Fundamental of programming I 71
Cont..
Example 2
• for statement adds the even numbers between 0 and n
#include<iostream.h>
int main()
{

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


{
for(int j=1;j<=4;j++)
{cout <<"* ";
}
cout<<endl;
}
return 0;
}
Fundamental of programming I 72
Cont..
3 rows -> 5 columns
4 rows -> 7 columns
5 rows -> 9 columns
6 rows -> 11 columns
If you have N numbers of rows, then you will have 2N-1
columns

Fundamental of programming I 73
Example 3
#include<iostream.h> for (k=1;k<=2*i-1;k++)
int main() {
{ cout<<"* ";
int i,j,k;
}
for (i=1;i<=5;i++)
cout<<endl;
{
for (j=5;j>i;j--) }
{ return 0;
cout<<" "; }
}

Fundamental of programming I 74
Cont..
Example 2
• #include<iostream.h>
int main()
{

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


{
for(int j=1;j<=2*4-1;j++)
{
if(j>=4-(i-1)&&j<=4+(i-1))
{
cout <<"* “; }
else { cout<<“ “;
}
}
return 0;
}
Fundamental of programming I 75
The while statement

 The while statement (also called while loop) provides a


way of repeating a statement or a block as long as a
condition holds / is true.
 May run zero or more times.
 The general form of the while loop is:
while(expression)
statements;

Fundamental of programming I 76
Cont..

 First expression (called the loop condition) is evaluated. If


the outcome is non zero then statement (called the loop
body) is executed and the whole process is repeated.
Otherwise, the loop is terminated.

Fundamental of programming I 77
Cont..
While loop: Is used when the number of iteration is not
known. Means you do not know how many times the loop
has to be repeated.
// infinite while loop
int x=1;
while(x==1)
{
// body of the loop
}

Fundamental of programming I 78
Cont..

Example
adds the numbers between 0 and 100
number=1;
sum=0;
while(number <= 100)
{
sum += number;
number++;
}

Fundamental of programming I 79
Do…while loop

 The do statement (also called the do while loop) is similar


to the while statement, except that its body is executed first
and then the loop condition is examined.
 In do…while loop, we are sure that the body of the loop
will be executed at least once. Then the condition will be
tested.

 The general form is:


do
{statement;
}while(expression);

Fundamental of programming I 80
Cont..
• First statement is executed and then expression is evaluated. If the
outcome of the expression is nonzero, then the whole process is
repeated. Otherwise the loop is terminated.
Example: adds the numbers between 0 and 100
int number=1;
int sum=0;
do
{sum += number;
number++;
Cout<<sum;
}
while(number <= 100);

Fundamental of programming I 81
Cont..
• First statement is executed and then expression is evaluated. If the
outcome of the expression is nonzero, then the whole process is
repeated. Otherwise the loop is terminated.
Example: adds the numbers between 0 and 100
int number=1;
do
{
// body of loop
}
while(number ==1);
The above condition is always true. Means the loop body will run for
infinite times.

Fundamental of programming I 82
Jump statement in C++

• Are used to manipulate the flow of the program if some


conditions are met.
• It is used to terminating or continues the loop inside a
program or to stop the execution of a function.
• In C++ there are four jump statements: continue, break,
return and goto

Fundamental of programming I 83
The continue statements
• The continue statement
 The continue statement terminates the current iteration of
a loop and instead jumps to the next iteration.
 It is an error to use the continue statement outside a loop.
 In while and do while loops, the next iteration starts from
the loop condition.
 In a “for” loop, the next iteration starts from the loop’s
third expression.

Fundamental of programming I 84
Cont..

• Example

#include<iostream.h>
int main()
{
for(int i=0;i<10;i++)
{ if(i==5)
continue;
cout<<i;
}
return 0;
}

Fundamental of programming I 85
The break statement

 A break statement may appear inside a loop (while, do, or


for) or a switch statement. It causes a jump out of these
constructs, and hence terminates them.
 Like the continue statement, a break statement only applies
to the “loop” or “switch” immediately enclosing it. It is an
error to use the break statement outside a loop or a switch
statement.

Fundamental of programming I 86
Cont..
Example
#include<iostream.h>
int main()
{
for(int i=0;i<10;i++)
{ if(i==5)
break;
cout<<i;
}
return 0;
}

Fundamental of programming I 87
The return statement

 Return: It takes control out of the function itself.


 It is stronger than a break.
 It is used to terminate the entire function after the execution
of the function or after some condition

Fundamental of programming I 88
Cont..
Example
#include<iostream.h>
int main()
{
for(int i=0;i<10;i++)
{ if(i==5)
return 0;
cout<<i;
}
return 0;
}

Fundamental of programming I 89
The return statement

 Go to: This statement is used to jump directly to that part


of the program to which it is being called.  
 Every go to statement is associated with the label which
takes them to part of the program for which they are called.

Fundamental of programming I 90
  
    

Cont..
Example
#include<iostream.h>
int main()
{
int n = 4;

if (n % 2 == 0)
        goto label1;
    else
        goto label2;
label1:
    cout << "Even" << endl;
    return 0;   
label2:
    cout << "Odd" << endl;

Fundamental of programming I 91

You might also like