SlideShare a Scribd company logo
1 of 19
youtube channel
Ashwini E Ashwiniesware@gmail.com
Chapter 5
Review of C++
• Bjarne Stroustrup is the father of C++
• C++ character set include alphabets,digits,special symbols and whitespaces.
• Tokens are the smallest individual unit in a program.
• Tokens are
❖ Keyword
❖ Identifier
❖ Variables
❖ Constants
❖ Punctuators
❖ Operators
• Keywords are the words having predefined meaning in C++.Also called as Reserved words.
Ex: float, while, if, do, int etc.
• Identifiers are the names given to variables, functions, arrays etc.
• Rules to name identifiers
❖ Identifier should always start with alphabet or underscore
❖ It should not start with digit
❖ It should be a single word
❖ Special characters are not allowed other than underscore
❖ It is case sensitive. Uppercase and lowercase are different.
• Variable is an element of program that changes its value during program execution.
• Variable is the name of the memory location where data can be stored.
• Variable declaration
❖ datatype variablename;
//datatype-type of data,variable can store
//variablename is the name of variable
❖ int a,b; // a and b are integer variables
❖ float x,y; //x and y are float variables
❖ char ch; //ch is a character variable
• Constant is an element of program whose value does not change during execution of a program
• Types of constants
❖ Integer constant
❖ Floating constant
❖ Character constant
❖ String constant
• Integer constant-It is a whole number which can be positive or negative.It donot have a fractional
part. It can be decimal constant, octl constant or hexadecimal constant.
Ex: 98,0743,0X45A,-67,-0342,-0Xabc
• Floating point constant-it represent a number with fractional part
Ex: 345.78
youtube channel
Ashwini E Ashwiniesware@gmail.com
• Character constant-it represents a single alphabet, digit or special symbol enclosed in single
quotes.
Ex: ‘s’, ‘#’, ‘5’
• There are some characters that start with backslash().Such characters are known as escape
sequence. Ex: n, t
• String constant-is a sequence of characters enclosed in double quotes.
“hello”
• Punctuators are the symbols used in C++ as seperators.
Ex:brackets[ ],Parantheses ( ), Braces { },Comma , Semicolon; Colon: Asterix*
• Operators are symbols which represent a particular operation and gives a definite value as
output.The different operators are
❖ Arithmetic operators(+,-,*,/ and %)
❖ Relational operators(<,<=,>,>=,==,!=)
❖ Logical operators(&&,||,!)
❖ Bitwise operators(&,|,^,~,<<,>>)
❖ Special operators(Scope resolution operator)
❖ Assignment operator(=)
• Arithmetic operators are used to perform arithmetic operations for all integer and real numbers.
• Relational operators compare two values and determine the relationship between them. Result of
relational operation is always true(1) or false(0)
• Logical operators are used to combine the outputs of multiple conditions into a single output.
Result of logical operation is always true(1) or false(0)
• Bitwise operators are used to perform operation on bits stored in memory location. This operator
gives C++ the features of low level language also.
• Assignment operator is used to assign a value to a variable.
✓ Based on number of operands, operators are classified into three
✓ They are Unary, Binary and Ternary operators
✓ Unary operator acts on one operand.Ex:increment and decrement operator
✓ Binary operator acts upon two operands.Ex;Arithmetic operators
✓ Ternary operator acts upon three operands.Ex:Conditional operator
✓ Increment operator increases the value of variable by 1
✓ Decrement operator decreases the value of variable by 1
✓ Conditional operator(?:) works on three expressions
Expression1? Expression2: Expression3
If expression1 is true, then expression2 is the result otherwise expression3 is the result.
✓ Operator precedence is the order of evaluating operators in an expression.
✓ A comment helps a person to understand what the program is about. It does not increase the
size of the program, compiler never executes it.
✓ Two types of comments-single line comments and multiline comments
//my first program in C++ single line comment
/* Program to display
One dimensional array*/ multiline comment
youtube channel
Ashwini E Ashwiniesware@gmail.com
Datatypes:
Datatype is the type of data a variable can store.It gives the type of operations that a variable can
perform.
Different datatypes in C++ are
1. Fundamental datatypes
2. Derived datatypes
3. Userdefined datatypes
Fundamental data types: There are five fundamental data types in C++.
1. Integer- Keyword int represents integers. Integers an be positive or negative whoe numbers. 2
bytes are needed to store an integer variable.
2. Float- Keyword float represents real numbers. Float represents single precision real numbers .
double represents double precision real numbers.4 bytes are needed to store an float variable. 8
bytes are needed to store a double variable.
3. Character-- Keyword char represents characters. Characters are single letter, digit or special
symbol. 1 byte is needed to store an integer variable.
4. Void datatype has no values and no operations.
5. Bool-It has the logical value ,true or false.True represents 1 and false represents 0.
Derived datatypes are created using fundamental datatypes.Ex:arrays,functions and pointers
Userdefined datatypes include structures, union,class,enum,typedef etc.
Expressions: syntactically valid combination of operators and operands that computes to a value.
ex:3*x+2 where 3, 2,x are operands and * and + are operators
Types of expressions:
1.Arithmetic expressions
2.Relational expression
3.Logical expressions
Arithmetic expressions use arithmetic operators along with character or numeric operands. There
are three arithmetic expressions in C. They are
a) integer mode expression are formed using integer type constants, variables and operators.
Arithmetic operators like addition, subtraction, multiplication and division and modulus are possible.
ex:12/4 6%7+9
b) real mode expression are formed using real mode constants, variables and operators. Modulus
operator cannot be used in real mode expression.
Ex:9.8*5.7
youtube channel
Ashwini E Ashwiniesware@gmail.com
c) mixed mode expression uses both integer type and floating type variables and constants in the
expression.
ex:9+2.5
Evaluation of arithmetic expression:
The operators in C are evaluated in a specific order. This is known as Precedence of operators.
Precedence level Operators Associativity
1 ( ) Left to Right
2
++, --, - Left to Right
3 *,/,% Left to Right
4 +,- Left to Right
steps in evaluating an arithmetic expression in C
step1: Evaluate any expression inside parantheses.
step2:Perform the multiplication and division operations.If more than one operations appear, then
they should be evaluated from left to right.
step3: perform addition and subtraction operations. If more than one operations appear, then they
should be evaluated from left to right. If more than one operations appear, then they should be
evaluated from left to right.
Relational expression: expressions formed by using relational operators. These expressions have
the truth value either True or False
ex. if a=90, b=70
a-b>=b+10
90-70>=70+10
20>=80 evaluates false
Logical expressions: consists of logical operators, relational operators, constants and variables.
ex: !(n>9) where n=10
!(10>9)= !(true)=false
Type conversions:
The process of converting one predefined data type to another is known as Type conversion. There
are two types of Type conversion.
a) Implicit type conversion
b) Explicit type conversion
Implicit type conversion: when we perform arithmetic manipulation on operands belonging to
different datatypes, they may undergo type conversion automatically before evaluating the final
value.This conversion is performed by the compiler without the knowledge of the programmer.
ex:
if operand1 is float and operand2 is int, then result will be float
if operand1 is float and operand2 is double, then result will be double
if operand1 is int and operand2 is long int, then result will be long int
youtube channel
Ashwini E Ashwiniesware@gmail.com
Explicit type conversion:this type conversion is performed by the user. this conversion forces an
expression to be of a specific type.
ex:
void main()
{
int sum,count;
float avg;
cout<<“Enter sum”;
cin>>sum;
cout<<“Enter count”;
cin>>count;
avg=(float)sum/count;
cout<<”average=“<<avg;
}
Datatype modifiers are unsigned,signed,short,int.
Input and output operators:
Every program performs three basic operations- receives data, manipulates data and output the results.
In C++, input or output is a sequence of bytes called Stream.
A Stream is a sequence of characters from the source to destination. There are two types of streams
1. Input stream
2. Output stream
Input stream is a sequence of characters from an input device to the computer program.
Output stream is a sequence of characters from computer program to an output device.
To receive data from the keyboard and to send data to the screen, every C++ program must use the
header file iostream.h.
Standard Output- cout :
cout I/O stream is used to write output of a program to the screen. It is console output.
Syntax:
cout<<expression or manipulator<< expression or manipulator;
cout is used along with << insertion operator. During program execution it helps to insert an expression
or argument on its right hand side into the output stream.
Ex: cout<<”welcome”;
cout<<123;
cout<<67.89;
cout<<” hello how are you?”;
Standard input-cin
cin stands for Console input. It is used along with extraction operator(>>) to input a value entered by the
user from the keyboard.
Syntax
youtube channel
Ashwini E Ashwiniesware@gmail.com
cin>>variable>>variable…………………..;
Extraction operator should be followed by the variable that store the data received from keyboard. The
extracted data will be stored in the RAM.
Ex:
int number; //declares a variable number of type int
cin>>number; //an integer from keyboard is stored in the variable number
/*program to find sum of two numbers*/
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,sum;
clrscr();
cout<<”enter values of a and b”;
cin>>a>>b;
sum=a+b;
cout<<”sum=”<<sum;
getch();
}
get() and put() functions:
The get() function inputs the very next character, including whitespace characters from the input stream
and stores it in the memory location indicated by the variable.
Ex: cin>>ch1>>ch2>>num;
If the input is A 25
Then, ch1=A ch2=2 and num=5(blank space is skipped by the extraction operator.
We can use get() as follows
cin.get(ch1); //store A in ch1
cin.get(ch2); //store blankspace in ch2
cin>>num; //store 25 in num. we can’t use get() because num is an integer
The put() function is used to print the next output character in the variable on the output device.
Ex:
char ch=’P’;
cout.put(ch);
CONTROL STATEMENTS
The order by which statements in a program are executed is known as Flow of Control.
A statement is an instruction written in a programming language to tell the compiler to do a particular
task.
youtube channel
Ashwini E Ashwiniesware@gmail.com
A group of statements that are separated by semicolon and enclosed within curly braces is called a
compound statement or a block.
The method of execution of statements in a program one after another is called as Sequential
Execution.
Control Statements:
Control statements are the statements that changes the sequence of execution of instructions in a
program.
There are two types of control statements
• Selection statements
• Looping statements/Iteration statements
Selection statements:
These statements allows the programmer to select a statement or group of statements for execution
based on a condition.
Different selection statements are
• If statement
• If.else statement
• Nested if statement
• Else if ladder
• Switch statement
If statement:
Simplest form of if statement.
Also called one way branching
This statement is used to decide whether a statement or group of statements should be executed or not
based on a condition.
if(condition)
{ true
Statement1;
Statement2;
………………….. false
Statement n;
}
Statement n+1;
If else statement
Also called two way branching
It executes some set of statements when condition is true and executes other set of statements when
condition is false.
if(condition)
{ true false
Statement1;
}
else
{
Is
condition Statement1
Statement2
Is condition
youtube channel
Ashwini E Ashwiniesware@gmail.com
Statement2;
}
Statement 3;
Nested if statement
if(expression1)
{
if(expression2) true
Statement1;
else
Statement2;
}
else
false
true
Statement3;
else.if ladder
Syntax:
if(expression1)
Statement1;
else if(expression2)
Statement2;
else if(expression3)
Statement3;
……………………………………….
………………………………………
else
Statement n+1;
Switch statement:
Statement1 Statement2
Statement3
Is condition11?
Statement3 Is condition2?
Statement2
Statement1
youtube channel
Ashwini E Ashwiniesware@gmail.com
Switch statement allows a program to select one statement for execution out of a set of
alternatives. During execution of switch statement, only one of the possible statements will be
executed;remaining statements will be skipped.
Syntax:
switch(expression)
{
case label1: statement1;
break;
case label2: statement2;
break;
case label3: statement3;
break;
.
.
.
default: default block;
}
statement n+1;
working:
1. The expression of switch statement is first evaluated to a single value
2. The value of expression is compared with various case label values.
3. If the value of the expression matches with any case label values, statements in that block are
executed until a break statement is found or end of switch statement is reached.
4. If the value of expression doesnot match any of case labels, then statements following default is
executed.
5. A label is either integer or character value.
Ex: cout<<”enter any number”;
cin>>i;
switch(i)
{
case 1: cout<<”ONE”;
break;
case 2: cout<<”TWO”;
break;
case 3: cout<<”THREE”;
break;
default: cout<<”Number other than one,two and three”;
}
Looping statements:
The statements used to execute the execution of a statement or a group of statements again and again
till a condition is satisfied are called as Looping/Iterative statements.
The process of repeating the execution of some set of statements again and again is called as Looping
youtube channel
Ashwini E Ashwiniesware@gmail.com
Different Looping statements in C++ are
• while loop
• do while loop
• for loop
while loop and do..while loop are used in situations where programmer does not know exactly how
many times the statements have to be executed again and again. It is executed until a condition is
satisfied.
for loop is used when programmer knows number of times the statements have to be repeated in
advance.
While loop:
While loop is also called pre tested loop. In while loop, checking of condition is done at the beginning.
Statements in the block are executed are executed again and again until the condition is true. When
the condition is false, control is transferred out of the while loop.
false false
True
true
Working:
1. Test condition is evaluated.
2. If value of test condition is false, statement 2 is executed and control goes out of the structure.
3. If the value of test condition is true, statements inside the while loop block are executed and control is
transferred to the test condition.
Ex:
Void main()
{
int i=1;
while(i<=5) //welcome will be printed 5 times. No need of writing 5 cout statements
{
cout<<”Welcome”<<endl;
i++;
}}
Do while loop
Also called as post tested loop.In do while loop,first the set of statements inside the do while block is
executed then condition is checked. If the condition is true, control is transferred to the condition again.
Thus statements are executed again and again until the condition is true. When the condition becomes
false, control is transferred out of the do while loop.
Syntax:
do
{
Statement1;
Statement2;
Is
condition?
Statement1
Statement2
Statement1
Statement 2 to n
youtube channel
Ashwini E Ashwiniesware@gmail.com
……………………………….
Statement n;
} while(test condition);
Statement n+1;
true false
Working:
1.the set of statements in the do while block are executed once.
2. the test condition is evaluated.
3. if value of test condition is false, control goes out of the structure
If the value of test condition is true, the control goes back to beginning of loop and statements are
executed again.
Ex:
Program to print welcome five times
int i=1;
do
{
cout<<”welcome”<<endl;
i++;
} while(i<=5);
For loop
For loop is also known as fixed execution loop. The programmer knows exactly how many times the
statements have to be executed again and again.
Syntax:
for(expression1;expression2;expression3)
{
Statement1; false
Statement2;
………………………………..
Statement n;
} true
Statement n+1;
Working:
.
Expression1 represents initialization expression
Expression2 represents final condition
Expression3 represents increment or decrement expression
Step1: First the counter variable is initialized.initialisation takes place only once.
Step2: Expression 2 is executed. The value of counter variable is checked to see it has exceeded the final
value.If not, statements inside for loop are executed once.
Step3:Control is sent back to the beginning of for loop and expression3 is evaluated.Value of counter is
either increased or decreased based on the statement used.
Is test
condition?
Statement n+1
initialisation
Condition?
Statement 1
Statement n
Increment/decrement Statement
n+1
youtube channel
Ashwini E Ashwiniesware@gmail.com
Ex: for(i=0;i<5;i++)
cout<<”welcome”<<endl;
Nested for loop:
One for loop is enclosed within another for loop is called a Nested for loop.
ex:
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cout<<“*”;
cout<<endl;
}
output:
***
***
***
Infinite loop:
A loop which does not end is called an infinite loop. Loop in which there is no expression inside for loop
and loop will execute infinite number of times are infinite loops.
Ex: for( ; ;)
Cout<<”welcome”;
JUMP STATEMENTS
The statements used to unconditionally transfer control within a program are called as Jump statements.
Example for jumping statements are goto,return,break and continue
1. goto statement is a simple statement used to transfer control from one point in a program to any
other point in that program.
2. break statement is used to terminate loops.It can be used within a while,do…while or for
statement. When break is encountered inside any loop, control automatically passes to the first
statement after loop.
3. continue statement is used to take the control back to beginning of the loop, ignoring all the
statements that have not yet been executed.
4. exit() function- is a standard library function used to terminate execution of the program. This
function is defined in the headerfile #include<stdlib.h>
STRING
String: A string is a sequence of characters. Characters include alphabets, numbers or special symbols
enclosed in double quotes.
Ex: “Computer” ex: “s9%h” “HELLO…………………”
String can also be defined as a one dimensional character array where the characters are stored in
consecutive memory locations.
String is a one dimensional character array terminated by a null character ‘0 ’.
youtube channel
Ashwini E Ashwiniesware@gmail.com
String declaration:
syntax:
char variablename[size];
• As string is a character array datatype is char only.
• Variable name is the name of String variable
• Size is the number of characters in the string.
ex: char str[30]; means 30 memory locations are reserved for the elements of str.
String initialization
ex:1. char str[9]=”Computer”;
C o m p u t e r 0
str[0] str[1] str[2] str[3] str[4] str[5] str[6] str[7] str[8]
ex:2 .char string1[ ] ={ ‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’};
char string1[ ]=”computer”;
Inputting a single character:
We can input a single character using get() function
Ex:
char ch;
ch=cin.get();
Outputting a single character:
We can display a single character using put() function
Ex:
char ch=’A’;
cout.put(ch);
Inputting a string:
We can input a string using getline() function
Ex:
cin.getline(string,size); //syntax
cin.getline(str,25);
outputting a string:
We can display a string using write() function
Ex:
cout.write(string,size); //syntax
cout.write(str,25);
youtube channel
Ashwini E Ashwiniesware@gmail.com
String functions:
All the string functions are stored in the header file string.h
String function use example
strlen() Find length of string N=strlen(stringname);
strcat() Joining two strings together strcat(string1,string2)
strcpy() To copy one string to another string strcpy(string1,string2)
strcmp() To compare two strings strcmp(string1,string2)
strcmpi()
To compare two strings strcmpi(string1,string2)
strrev() To reverse characters in a string strrev(string1)
FUNCTIONS
A Function is a named unit of a group of program statements to perform a specific task and return a single value.
Types of function
1. Built in function--- function defined by the C Compiler. Ex: strcpy( ), sqrt( ), printf( )
2. User defined function--- Function defined by the user. Ex: sum( )
Advantages of Functions:
1. Function helps us to avoid repetition of program statements or duplication of code in many places
of a program.
2. Number of lines of code can be reduced.
3. Debugging or correcting errors can be easy
4. When we create a function which is needed by another program, the function can be made
available to that program also. it helps in reusability.
5. A complex program can be divided into modules, where each module performing a specific task.
Each module is independent of other modules so that each can be developed without considering
other modules.
6. If the program is divided into modules, each person in a team can develop separate module, rather
than having a single person working on the complete program.
General Structure of a user defined function:
//function definition
Returntype function name (type arg1, type arg2,……….)
{
Local variable declarations;
Statement1;
youtube channel
Ashwini E Ashwiniesware@gmail.com
Statement2;
…………………………
return(expression);
}
Returntypespecifier: identifies the type of value which is returned back after the function has
performed its task. Ex:int,float,char etc. If the function is not returning any value, the returntypespecifier
will be void.
Functionname: used to uniquely identifying and call a function.
Argumentlist with Declaration: identifies a set of values which are to be passed to the function and
their datatypes also should be mentioned.
Body of the function: It includes declaration of local variables which are declared and used only inside
the function. It also consists of set of executable statements.
Return statement:The last executable statement of the function is the return statement having syntax
return(expression)---- it contains the value that has to be sent back to the main program.
Ex: return(a); return(a+b); return 0; //only one expression canbe included in a return statement.
Function prototype:tells the compiler about name of the function and type of arguments and
return value.
Syntax:
returntype functionname(argument list);
int sum(int,int);
Example program to find sum of two numbers using function
#include<iostream.h>
void main()
{
int a,b,s;
int sum(int,int); //function prototype
cout<<“Enter two numbers”;
cin>>a>>b;
s=sum(a,b); //function call
cout<<”sum=”<<s;
}
int sum(int x,int y) // subfunction heading followed by function body and return statement
{
int c; //local variable
c=x+y;
return( c);
}
youtube channel
Ashwini E Ashwiniesware@gmail.com
Function call: is a statement that transfers control to a function in C. A function is invoked by function call.It
includes name of the function, followed by a list of arguments.
Actual Arguments and Formal Arguments:
Arguments are the values that are passed between calling function and called function during
function call.Arguments are also known as Parameters
Actual arguments Formal Agument
A variable listed in a function call. A variable listed in a function heading.
These contain the inputted vales These arguments are just a copy of values from the
actual arguments
Local variables and Global variables:
Local variables: A variable declared inside a function and cannot be accessed outside that function.
int product(int x, int y)
{
int p; //p is local variable
p=x*y;
return(p);
}
Global variables: A variable declared outside of all the functions in a program and can be accessed anywhere
in the program.
Ex:
int a,b; // a nd b are global variables
main()
{
int p,q; // p and q are local variables
……………….
……………..
}
Different types of User Defined Functions in C:
User defined functions may belong to any of the following categories:
1. Functions with no arguments and no return values
2. Functions with arguments and no return values
3. Functions with arguments and return values
4. Recursive functions
i) Functions with no arguments and no return values
This function performs an independent task. It does not send or receive arguments.
void natural ( )
{
for(int i=1;i<=10;i++)
cout<<setw(3)<<I;
youtube channel
Ashwini E Ashwiniesware@gmail.com
}
ii) Functions with arguments and no return values
In this type the functionreceives some argumentsand doesnot return any value.
void average(int x,int y,int z)
{
float sum,avg;
sum=a+b+c;
avg=sum/3.0;
cout<<”Average=”<<avg;
}
iii) Functions with no arguments and with return values
In this type the function receives no arguments but return a value
int largest()
{
if(a>b)
return(a);
return(b);
}
iv) Functions with arguments and return values
In this type the function receives some arguments and also returns a value
float simpleinterest(float p,float t,float r)
{
int si;
si=p*t*r/100;
return(si);
}
v) Recursive functions:
Functions that call itself are called as Recursive functions.The process of calling a function
by itself is known as Recursion.
Recursive function mst have one or more terminating conditions to terminate
recursion.Otherwise, recursion becomes infinite.
Structures:
Structure is a heterogeneous data type that can store elements of same or different datatype and the
entire structure is referenced by a single name.
Need for structure datatype: When we have a group of elements of different data types to be stored,
we can store it in a single structure element.
youtube channel
Ashwini E Ashwiniesware@gmail.com
Defining a Structure:
Structure definition can be done either before the main( ) function or after the main( ) function.
The process of defining a structure includes giving structure a name and telling the compiler the name
and the datatype of each piece of data that is to be included in the structure. A structure definition always
start with the keyword ‘struct’. All the data members belonging to a structure is called a Template.
Syntax:
struct structurename
{
Datatype member1;
Datatype member2;
………………..
……………..
Datatype member n;
};
Ex: Structure definition showing student details
Struct Student
{
int Rollno;
char name[30];
char Grade;
float fees;
};
//here Rollno,name Grade and fees are members of the structure Student which is a user defined datatype
Note:
Structure definition doesnot create memory space for the structure members. For that we have to
create structure variables. For the above example memory space required is (2 bytes+30 bytes+1
byte+4bytes=37 bytes)
Declaring a structure variable:
A structure variable can be declared using the following syntax
struct structurename variablename;
Eg: struct Student s1; //s1 is the structurevariable that store all the four members and
the total memory space needed for the structure variable is 37 bytes.
S1
1234 anu A 14000
To create one more structure variable to store another set of information we can use the following
struct Student s1,s2; //s1 and s2 are the structurevariables
youtube channel
Ashwini E Ashwiniesware@gmail.com
s1 variable storing one set of information of a student and s2 storing information of another student.
S1
S2
1236 bindu B 15000
Structure initialization:
To initialize a structure variable at the time of declaration we can follow the structure
declaration with a list containing values for each of its fields.
Ex: struct student s1={101,”Santhosh”,’A’,7580.00};
struct student s2={102,”Sunil”,’B’,4000.00};
struct employee e1={145,”Sachin”,”Teamcoach”,200000};
Accessing members of a structure:
To access members of a structure we have to use the dot (.)operator. We cannot use the structure member
directly. To read or print a member we have to use the following syntax
structurevariablename.membername
ex: To read rollno,
cin>>e1.rollno;
cout<<e1.empname;
*********
1234 anu A 14000

More Related Content

What's hot (20)

Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C Language
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
Unit 2 python
Unit 2 pythonUnit 2 python
Unit 2 python
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
C Tokens
C TokensC Tokens
C Tokens
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Loops in c++ programming language
Loops in c++ programming language Loops in c++ programming language
Loops in c++ programming language
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
 
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHMCLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
CLASS VIII COMPUTERS FLOW CHART AND ALGORITHM
 
Data types in C
Data types in CData types in C
Data types in C
 
Preprocessor directives in c language
Preprocessor directives in c languagePreprocessor directives in c language
Preprocessor directives in c language
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 

Similar to 2nd PUC Computer science chapter 5 review of c++

Similar to 2nd PUC Computer science chapter 5 review of c++ (20)

C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
C program
C programC program
C program
 
INTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptxINTRODUCTION TO C++.pptx
INTRODUCTION TO C++.pptx
 
Chapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingChapter 2: Elementary Programming
Chapter 2: Elementary Programming
 
PSPC--UNIT-2.pdf
PSPC--UNIT-2.pdfPSPC--UNIT-2.pdf
PSPC--UNIT-2.pdf
 
Introduction
IntroductionIntroduction
Introduction
 
C basics
C basicsC basics
C basics
 
C basics
C basicsC basics
C basics
 
Fundamentals of C Programming Language
Fundamentals of C Programming LanguageFundamentals of C Programming Language
Fundamentals of C Programming Language
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving Techniques
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C Language
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
c-programming
c-programmingc-programming
c-programming
 
C programming
C programming C programming
C programming
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
 
Getting started with c++.pptx
Getting started with c++.pptxGetting started with c++.pptx
Getting started with c++.pptx
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 

More from Aahwini Esware gowda

2nd puc computer science chapter 8 function overloading
 2nd puc computer science chapter 8   function overloading 2nd puc computer science chapter 8   function overloading
2nd puc computer science chapter 8 function overloadingAahwini Esware gowda
 
2nd PUC computer science chapter 6 oop concept
2nd PUC computer science chapter 6   oop concept2nd PUC computer science chapter 6   oop concept
2nd PUC computer science chapter 6 oop conceptAahwini Esware gowda
 
2nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 12nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 1Aahwini Esware gowda
 
2nd PUC computer science chapter 2 boolean algebra
2nd PUC computer science chapter 2  boolean algebra 2nd PUC computer science chapter 2  boolean algebra
2nd PUC computer science chapter 2 boolean algebra Aahwini Esware gowda
 
2nd PUC computer science chapter 2 boolean algebra 1
2nd PUC computer science chapter 2  boolean algebra 12nd PUC computer science chapter 2  boolean algebra 1
2nd PUC computer science chapter 2 boolean algebra 1Aahwini Esware gowda
 
2nd puc computer science chapter 1 backdrop of computers
2nd puc computer science chapter 1  backdrop of computers 2nd puc computer science chapter 1  backdrop of computers
2nd puc computer science chapter 1 backdrop of computers Aahwini Esware gowda
 

More from Aahwini Esware gowda (6)

2nd puc computer science chapter 8 function overloading
 2nd puc computer science chapter 8   function overloading 2nd puc computer science chapter 8   function overloading
2nd puc computer science chapter 8 function overloading
 
2nd PUC computer science chapter 6 oop concept
2nd PUC computer science chapter 6   oop concept2nd PUC computer science chapter 6   oop concept
2nd PUC computer science chapter 6 oop concept
 
2nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 12nd puc computer science chapter 3 data structures 1
2nd puc computer science chapter 3 data structures 1
 
2nd PUC computer science chapter 2 boolean algebra
2nd PUC computer science chapter 2  boolean algebra 2nd PUC computer science chapter 2  boolean algebra
2nd PUC computer science chapter 2 boolean algebra
 
2nd PUC computer science chapter 2 boolean algebra 1
2nd PUC computer science chapter 2  boolean algebra 12nd PUC computer science chapter 2  boolean algebra 1
2nd PUC computer science chapter 2 boolean algebra 1
 
2nd puc computer science chapter 1 backdrop of computers
2nd puc computer science chapter 1  backdrop of computers 2nd puc computer science chapter 1  backdrop of computers
2nd puc computer science chapter 1 backdrop of computers
 

Recently uploaded

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 

Recently uploaded (20)

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 

2nd PUC Computer science chapter 5 review of c++

  • 1. youtube channel Ashwini E Ashwiniesware@gmail.com Chapter 5 Review of C++ • Bjarne Stroustrup is the father of C++ • C++ character set include alphabets,digits,special symbols and whitespaces. • Tokens are the smallest individual unit in a program. • Tokens are ❖ Keyword ❖ Identifier ❖ Variables ❖ Constants ❖ Punctuators ❖ Operators • Keywords are the words having predefined meaning in C++.Also called as Reserved words. Ex: float, while, if, do, int etc. • Identifiers are the names given to variables, functions, arrays etc. • Rules to name identifiers ❖ Identifier should always start with alphabet or underscore ❖ It should not start with digit ❖ It should be a single word ❖ Special characters are not allowed other than underscore ❖ It is case sensitive. Uppercase and lowercase are different. • Variable is an element of program that changes its value during program execution. • Variable is the name of the memory location where data can be stored. • Variable declaration ❖ datatype variablename; //datatype-type of data,variable can store //variablename is the name of variable ❖ int a,b; // a and b are integer variables ❖ float x,y; //x and y are float variables ❖ char ch; //ch is a character variable • Constant is an element of program whose value does not change during execution of a program • Types of constants ❖ Integer constant ❖ Floating constant ❖ Character constant ❖ String constant • Integer constant-It is a whole number which can be positive or negative.It donot have a fractional part. It can be decimal constant, octl constant or hexadecimal constant. Ex: 98,0743,0X45A,-67,-0342,-0Xabc • Floating point constant-it represent a number with fractional part Ex: 345.78
  • 2. youtube channel Ashwini E Ashwiniesware@gmail.com • Character constant-it represents a single alphabet, digit or special symbol enclosed in single quotes. Ex: ‘s’, ‘#’, ‘5’ • There are some characters that start with backslash().Such characters are known as escape sequence. Ex: n, t • String constant-is a sequence of characters enclosed in double quotes. “hello” • Punctuators are the symbols used in C++ as seperators. Ex:brackets[ ],Parantheses ( ), Braces { },Comma , Semicolon; Colon: Asterix* • Operators are symbols which represent a particular operation and gives a definite value as output.The different operators are ❖ Arithmetic operators(+,-,*,/ and %) ❖ Relational operators(<,<=,>,>=,==,!=) ❖ Logical operators(&&,||,!) ❖ Bitwise operators(&,|,^,~,<<,>>) ❖ Special operators(Scope resolution operator) ❖ Assignment operator(=) • Arithmetic operators are used to perform arithmetic operations for all integer and real numbers. • Relational operators compare two values and determine the relationship between them. Result of relational operation is always true(1) or false(0) • Logical operators are used to combine the outputs of multiple conditions into a single output. Result of logical operation is always true(1) or false(0) • Bitwise operators are used to perform operation on bits stored in memory location. This operator gives C++ the features of low level language also. • Assignment operator is used to assign a value to a variable. ✓ Based on number of operands, operators are classified into three ✓ They are Unary, Binary and Ternary operators ✓ Unary operator acts on one operand.Ex:increment and decrement operator ✓ Binary operator acts upon two operands.Ex;Arithmetic operators ✓ Ternary operator acts upon three operands.Ex:Conditional operator ✓ Increment operator increases the value of variable by 1 ✓ Decrement operator decreases the value of variable by 1 ✓ Conditional operator(?:) works on three expressions Expression1? Expression2: Expression3 If expression1 is true, then expression2 is the result otherwise expression3 is the result. ✓ Operator precedence is the order of evaluating operators in an expression. ✓ A comment helps a person to understand what the program is about. It does not increase the size of the program, compiler never executes it. ✓ Two types of comments-single line comments and multiline comments //my first program in C++ single line comment /* Program to display One dimensional array*/ multiline comment
  • 3. youtube channel Ashwini E Ashwiniesware@gmail.com Datatypes: Datatype is the type of data a variable can store.It gives the type of operations that a variable can perform. Different datatypes in C++ are 1. Fundamental datatypes 2. Derived datatypes 3. Userdefined datatypes Fundamental data types: There are five fundamental data types in C++. 1. Integer- Keyword int represents integers. Integers an be positive or negative whoe numbers. 2 bytes are needed to store an integer variable. 2. Float- Keyword float represents real numbers. Float represents single precision real numbers . double represents double precision real numbers.4 bytes are needed to store an float variable. 8 bytes are needed to store a double variable. 3. Character-- Keyword char represents characters. Characters are single letter, digit or special symbol. 1 byte is needed to store an integer variable. 4. Void datatype has no values and no operations. 5. Bool-It has the logical value ,true or false.True represents 1 and false represents 0. Derived datatypes are created using fundamental datatypes.Ex:arrays,functions and pointers Userdefined datatypes include structures, union,class,enum,typedef etc. Expressions: syntactically valid combination of operators and operands that computes to a value. ex:3*x+2 where 3, 2,x are operands and * and + are operators Types of expressions: 1.Arithmetic expressions 2.Relational expression 3.Logical expressions Arithmetic expressions use arithmetic operators along with character or numeric operands. There are three arithmetic expressions in C. They are a) integer mode expression are formed using integer type constants, variables and operators. Arithmetic operators like addition, subtraction, multiplication and division and modulus are possible. ex:12/4 6%7+9 b) real mode expression are formed using real mode constants, variables and operators. Modulus operator cannot be used in real mode expression. Ex:9.8*5.7
  • 4. youtube channel Ashwini E Ashwiniesware@gmail.com c) mixed mode expression uses both integer type and floating type variables and constants in the expression. ex:9+2.5 Evaluation of arithmetic expression: The operators in C are evaluated in a specific order. This is known as Precedence of operators. Precedence level Operators Associativity 1 ( ) Left to Right 2 ++, --, - Left to Right 3 *,/,% Left to Right 4 +,- Left to Right steps in evaluating an arithmetic expression in C step1: Evaluate any expression inside parantheses. step2:Perform the multiplication and division operations.If more than one operations appear, then they should be evaluated from left to right. step3: perform addition and subtraction operations. If more than one operations appear, then they should be evaluated from left to right. If more than one operations appear, then they should be evaluated from left to right. Relational expression: expressions formed by using relational operators. These expressions have the truth value either True or False ex. if a=90, b=70 a-b>=b+10 90-70>=70+10 20>=80 evaluates false Logical expressions: consists of logical operators, relational operators, constants and variables. ex: !(n>9) where n=10 !(10>9)= !(true)=false Type conversions: The process of converting one predefined data type to another is known as Type conversion. There are two types of Type conversion. a) Implicit type conversion b) Explicit type conversion Implicit type conversion: when we perform arithmetic manipulation on operands belonging to different datatypes, they may undergo type conversion automatically before evaluating the final value.This conversion is performed by the compiler without the knowledge of the programmer. ex: if operand1 is float and operand2 is int, then result will be float if operand1 is float and operand2 is double, then result will be double if operand1 is int and operand2 is long int, then result will be long int
  • 5. youtube channel Ashwini E Ashwiniesware@gmail.com Explicit type conversion:this type conversion is performed by the user. this conversion forces an expression to be of a specific type. ex: void main() { int sum,count; float avg; cout<<“Enter sum”; cin>>sum; cout<<“Enter count”; cin>>count; avg=(float)sum/count; cout<<”average=“<<avg; } Datatype modifiers are unsigned,signed,short,int. Input and output operators: Every program performs three basic operations- receives data, manipulates data and output the results. In C++, input or output is a sequence of bytes called Stream. A Stream is a sequence of characters from the source to destination. There are two types of streams 1. Input stream 2. Output stream Input stream is a sequence of characters from an input device to the computer program. Output stream is a sequence of characters from computer program to an output device. To receive data from the keyboard and to send data to the screen, every C++ program must use the header file iostream.h. Standard Output- cout : cout I/O stream is used to write output of a program to the screen. It is console output. Syntax: cout<<expression or manipulator<< expression or manipulator; cout is used along with << insertion operator. During program execution it helps to insert an expression or argument on its right hand side into the output stream. Ex: cout<<”welcome”; cout<<123; cout<<67.89; cout<<” hello how are you?”; Standard input-cin cin stands for Console input. It is used along with extraction operator(>>) to input a value entered by the user from the keyboard. Syntax
  • 6. youtube channel Ashwini E Ashwiniesware@gmail.com cin>>variable>>variable…………………..; Extraction operator should be followed by the variable that store the data received from keyboard. The extracted data will be stored in the RAM. Ex: int number; //declares a variable number of type int cin>>number; //an integer from keyboard is stored in the variable number /*program to find sum of two numbers*/ #include<iostream.h> #include<conio.h> void main() { int a,b,sum; clrscr(); cout<<”enter values of a and b”; cin>>a>>b; sum=a+b; cout<<”sum=”<<sum; getch(); } get() and put() functions: The get() function inputs the very next character, including whitespace characters from the input stream and stores it in the memory location indicated by the variable. Ex: cin>>ch1>>ch2>>num; If the input is A 25 Then, ch1=A ch2=2 and num=5(blank space is skipped by the extraction operator. We can use get() as follows cin.get(ch1); //store A in ch1 cin.get(ch2); //store blankspace in ch2 cin>>num; //store 25 in num. we can’t use get() because num is an integer The put() function is used to print the next output character in the variable on the output device. Ex: char ch=’P’; cout.put(ch); CONTROL STATEMENTS The order by which statements in a program are executed is known as Flow of Control. A statement is an instruction written in a programming language to tell the compiler to do a particular task.
  • 7. youtube channel Ashwini E Ashwiniesware@gmail.com A group of statements that are separated by semicolon and enclosed within curly braces is called a compound statement or a block. The method of execution of statements in a program one after another is called as Sequential Execution. Control Statements: Control statements are the statements that changes the sequence of execution of instructions in a program. There are two types of control statements • Selection statements • Looping statements/Iteration statements Selection statements: These statements allows the programmer to select a statement or group of statements for execution based on a condition. Different selection statements are • If statement • If.else statement • Nested if statement • Else if ladder • Switch statement If statement: Simplest form of if statement. Also called one way branching This statement is used to decide whether a statement or group of statements should be executed or not based on a condition. if(condition) { true Statement1; Statement2; ………………….. false Statement n; } Statement n+1; If else statement Also called two way branching It executes some set of statements when condition is true and executes other set of statements when condition is false. if(condition) { true false Statement1; } else { Is condition Statement1 Statement2 Is condition
  • 8. youtube channel Ashwini E Ashwiniesware@gmail.com Statement2; } Statement 3; Nested if statement if(expression1) { if(expression2) true Statement1; else Statement2; } else false true Statement3; else.if ladder Syntax: if(expression1) Statement1; else if(expression2) Statement2; else if(expression3) Statement3; ………………………………………. ……………………………………… else Statement n+1; Switch statement: Statement1 Statement2 Statement3 Is condition11? Statement3 Is condition2? Statement2 Statement1
  • 9. youtube channel Ashwini E Ashwiniesware@gmail.com Switch statement allows a program to select one statement for execution out of a set of alternatives. During execution of switch statement, only one of the possible statements will be executed;remaining statements will be skipped. Syntax: switch(expression) { case label1: statement1; break; case label2: statement2; break; case label3: statement3; break; . . . default: default block; } statement n+1; working: 1. The expression of switch statement is first evaluated to a single value 2. The value of expression is compared with various case label values. 3. If the value of the expression matches with any case label values, statements in that block are executed until a break statement is found or end of switch statement is reached. 4. If the value of expression doesnot match any of case labels, then statements following default is executed. 5. A label is either integer or character value. Ex: cout<<”enter any number”; cin>>i; switch(i) { case 1: cout<<”ONE”; break; case 2: cout<<”TWO”; break; case 3: cout<<”THREE”; break; default: cout<<”Number other than one,two and three”; } Looping statements: The statements used to execute the execution of a statement or a group of statements again and again till a condition is satisfied are called as Looping/Iterative statements. The process of repeating the execution of some set of statements again and again is called as Looping
  • 10. youtube channel Ashwini E Ashwiniesware@gmail.com Different Looping statements in C++ are • while loop • do while loop • for loop while loop and do..while loop are used in situations where programmer does not know exactly how many times the statements have to be executed again and again. It is executed until a condition is satisfied. for loop is used when programmer knows number of times the statements have to be repeated in advance. While loop: While loop is also called pre tested loop. In while loop, checking of condition is done at the beginning. Statements in the block are executed are executed again and again until the condition is true. When the condition is false, control is transferred out of the while loop. false false True true Working: 1. Test condition is evaluated. 2. If value of test condition is false, statement 2 is executed and control goes out of the structure. 3. If the value of test condition is true, statements inside the while loop block are executed and control is transferred to the test condition. Ex: Void main() { int i=1; while(i<=5) //welcome will be printed 5 times. No need of writing 5 cout statements { cout<<”Welcome”<<endl; i++; }} Do while loop Also called as post tested loop.In do while loop,first the set of statements inside the do while block is executed then condition is checked. If the condition is true, control is transferred to the condition again. Thus statements are executed again and again until the condition is true. When the condition becomes false, control is transferred out of the do while loop. Syntax: do { Statement1; Statement2; Is condition? Statement1 Statement2 Statement1 Statement 2 to n
  • 11. youtube channel Ashwini E Ashwiniesware@gmail.com ………………………………. Statement n; } while(test condition); Statement n+1; true false Working: 1.the set of statements in the do while block are executed once. 2. the test condition is evaluated. 3. if value of test condition is false, control goes out of the structure If the value of test condition is true, the control goes back to beginning of loop and statements are executed again. Ex: Program to print welcome five times int i=1; do { cout<<”welcome”<<endl; i++; } while(i<=5); For loop For loop is also known as fixed execution loop. The programmer knows exactly how many times the statements have to be executed again and again. Syntax: for(expression1;expression2;expression3) { Statement1; false Statement2; ……………………………….. Statement n; } true Statement n+1; Working: . Expression1 represents initialization expression Expression2 represents final condition Expression3 represents increment or decrement expression Step1: First the counter variable is initialized.initialisation takes place only once. Step2: Expression 2 is executed. The value of counter variable is checked to see it has exceeded the final value.If not, statements inside for loop are executed once. Step3:Control is sent back to the beginning of for loop and expression3 is evaluated.Value of counter is either increased or decreased based on the statement used. Is test condition? Statement n+1 initialisation Condition? Statement 1 Statement n Increment/decrement Statement n+1
  • 12. youtube channel Ashwini E Ashwiniesware@gmail.com Ex: for(i=0;i<5;i++) cout<<”welcome”<<endl; Nested for loop: One for loop is enclosed within another for loop is called a Nested for loop. ex: for(i=0;i<3;i++) { for(j=0;j<3;j++) cout<<“*”; cout<<endl; } output: *** *** *** Infinite loop: A loop which does not end is called an infinite loop. Loop in which there is no expression inside for loop and loop will execute infinite number of times are infinite loops. Ex: for( ; ;) Cout<<”welcome”; JUMP STATEMENTS The statements used to unconditionally transfer control within a program are called as Jump statements. Example for jumping statements are goto,return,break and continue 1. goto statement is a simple statement used to transfer control from one point in a program to any other point in that program. 2. break statement is used to terminate loops.It can be used within a while,do…while or for statement. When break is encountered inside any loop, control automatically passes to the first statement after loop. 3. continue statement is used to take the control back to beginning of the loop, ignoring all the statements that have not yet been executed. 4. exit() function- is a standard library function used to terminate execution of the program. This function is defined in the headerfile #include<stdlib.h> STRING String: A string is a sequence of characters. Characters include alphabets, numbers or special symbols enclosed in double quotes. Ex: “Computer” ex: “s9%h” “HELLO…………………” String can also be defined as a one dimensional character array where the characters are stored in consecutive memory locations. String is a one dimensional character array terminated by a null character ‘0 ’.
  • 13. youtube channel Ashwini E Ashwiniesware@gmail.com String declaration: syntax: char variablename[size]; • As string is a character array datatype is char only. • Variable name is the name of String variable • Size is the number of characters in the string. ex: char str[30]; means 30 memory locations are reserved for the elements of str. String initialization ex:1. char str[9]=”Computer”; C o m p u t e r 0 str[0] str[1] str[2] str[3] str[4] str[5] str[6] str[7] str[8] ex:2 .char string1[ ] ={ ‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’}; char string1[ ]=”computer”; Inputting a single character: We can input a single character using get() function Ex: char ch; ch=cin.get(); Outputting a single character: We can display a single character using put() function Ex: char ch=’A’; cout.put(ch); Inputting a string: We can input a string using getline() function Ex: cin.getline(string,size); //syntax cin.getline(str,25); outputting a string: We can display a string using write() function Ex: cout.write(string,size); //syntax cout.write(str,25);
  • 14. youtube channel Ashwini E Ashwiniesware@gmail.com String functions: All the string functions are stored in the header file string.h String function use example strlen() Find length of string N=strlen(stringname); strcat() Joining two strings together strcat(string1,string2) strcpy() To copy one string to another string strcpy(string1,string2) strcmp() To compare two strings strcmp(string1,string2) strcmpi() To compare two strings strcmpi(string1,string2) strrev() To reverse characters in a string strrev(string1) FUNCTIONS A Function is a named unit of a group of program statements to perform a specific task and return a single value. Types of function 1. Built in function--- function defined by the C Compiler. Ex: strcpy( ), sqrt( ), printf( ) 2. User defined function--- Function defined by the user. Ex: sum( ) Advantages of Functions: 1. Function helps us to avoid repetition of program statements or duplication of code in many places of a program. 2. Number of lines of code can be reduced. 3. Debugging or correcting errors can be easy 4. When we create a function which is needed by another program, the function can be made available to that program also. it helps in reusability. 5. A complex program can be divided into modules, where each module performing a specific task. Each module is independent of other modules so that each can be developed without considering other modules. 6. If the program is divided into modules, each person in a team can develop separate module, rather than having a single person working on the complete program. General Structure of a user defined function: //function definition Returntype function name (type arg1, type arg2,……….) { Local variable declarations; Statement1;
  • 15. youtube channel Ashwini E Ashwiniesware@gmail.com Statement2; ………………………… return(expression); } Returntypespecifier: identifies the type of value which is returned back after the function has performed its task. Ex:int,float,char etc. If the function is not returning any value, the returntypespecifier will be void. Functionname: used to uniquely identifying and call a function. Argumentlist with Declaration: identifies a set of values which are to be passed to the function and their datatypes also should be mentioned. Body of the function: It includes declaration of local variables which are declared and used only inside the function. It also consists of set of executable statements. Return statement:The last executable statement of the function is the return statement having syntax return(expression)---- it contains the value that has to be sent back to the main program. Ex: return(a); return(a+b); return 0; //only one expression canbe included in a return statement. Function prototype:tells the compiler about name of the function and type of arguments and return value. Syntax: returntype functionname(argument list); int sum(int,int); Example program to find sum of two numbers using function #include<iostream.h> void main() { int a,b,s; int sum(int,int); //function prototype cout<<“Enter two numbers”; cin>>a>>b; s=sum(a,b); //function call cout<<”sum=”<<s; } int sum(int x,int y) // subfunction heading followed by function body and return statement { int c; //local variable c=x+y; return( c); }
  • 16. youtube channel Ashwini E Ashwiniesware@gmail.com Function call: is a statement that transfers control to a function in C. A function is invoked by function call.It includes name of the function, followed by a list of arguments. Actual Arguments and Formal Arguments: Arguments are the values that are passed between calling function and called function during function call.Arguments are also known as Parameters Actual arguments Formal Agument A variable listed in a function call. A variable listed in a function heading. These contain the inputted vales These arguments are just a copy of values from the actual arguments Local variables and Global variables: Local variables: A variable declared inside a function and cannot be accessed outside that function. int product(int x, int y) { int p; //p is local variable p=x*y; return(p); } Global variables: A variable declared outside of all the functions in a program and can be accessed anywhere in the program. Ex: int a,b; // a nd b are global variables main() { int p,q; // p and q are local variables ………………. …………….. } Different types of User Defined Functions in C: User defined functions may belong to any of the following categories: 1. Functions with no arguments and no return values 2. Functions with arguments and no return values 3. Functions with arguments and return values 4. Recursive functions i) Functions with no arguments and no return values This function performs an independent task. It does not send or receive arguments. void natural ( ) { for(int i=1;i<=10;i++) cout<<setw(3)<<I;
  • 17. youtube channel Ashwini E Ashwiniesware@gmail.com } ii) Functions with arguments and no return values In this type the functionreceives some argumentsand doesnot return any value. void average(int x,int y,int z) { float sum,avg; sum=a+b+c; avg=sum/3.0; cout<<”Average=”<<avg; } iii) Functions with no arguments and with return values In this type the function receives no arguments but return a value int largest() { if(a>b) return(a); return(b); } iv) Functions with arguments and return values In this type the function receives some arguments and also returns a value float simpleinterest(float p,float t,float r) { int si; si=p*t*r/100; return(si); } v) Recursive functions: Functions that call itself are called as Recursive functions.The process of calling a function by itself is known as Recursion. Recursive function mst have one or more terminating conditions to terminate recursion.Otherwise, recursion becomes infinite. Structures: Structure is a heterogeneous data type that can store elements of same or different datatype and the entire structure is referenced by a single name. Need for structure datatype: When we have a group of elements of different data types to be stored, we can store it in a single structure element.
  • 18. youtube channel Ashwini E Ashwiniesware@gmail.com Defining a Structure: Structure definition can be done either before the main( ) function or after the main( ) function. The process of defining a structure includes giving structure a name and telling the compiler the name and the datatype of each piece of data that is to be included in the structure. A structure definition always start with the keyword ‘struct’. All the data members belonging to a structure is called a Template. Syntax: struct structurename { Datatype member1; Datatype member2; ……………….. …………….. Datatype member n; }; Ex: Structure definition showing student details Struct Student { int Rollno; char name[30]; char Grade; float fees; }; //here Rollno,name Grade and fees are members of the structure Student which is a user defined datatype Note: Structure definition doesnot create memory space for the structure members. For that we have to create structure variables. For the above example memory space required is (2 bytes+30 bytes+1 byte+4bytes=37 bytes) Declaring a structure variable: A structure variable can be declared using the following syntax struct structurename variablename; Eg: struct Student s1; //s1 is the structurevariable that store all the four members and the total memory space needed for the structure variable is 37 bytes. S1 1234 anu A 14000 To create one more structure variable to store another set of information we can use the following struct Student s1,s2; //s1 and s2 are the structurevariables
  • 19. youtube channel Ashwini E Ashwiniesware@gmail.com s1 variable storing one set of information of a student and s2 storing information of another student. S1 S2 1236 bindu B 15000 Structure initialization: To initialize a structure variable at the time of declaration we can follow the structure declaration with a list containing values for each of its fields. Ex: struct student s1={101,”Santhosh”,’A’,7580.00}; struct student s2={102,”Sunil”,’B’,4000.00}; struct employee e1={145,”Sachin”,”Teamcoach”,200000}; Accessing members of a structure: To access members of a structure we have to use the dot (.)operator. We cannot use the structure member directly. To read or print a member we have to use the following syntax structurevariablename.membername ex: To read rollno, cin>>e1.rollno; cout<<e1.empname; ********* 1234 anu A 14000