C++ Basic Constructs
Console Input and Output
Console Input / Output
• I/O objects cin, cout
• Defined in the C++ library called <iostream>
• Earlier C++ versions has <iostream.h>, but new
versions drop “.h”.
• Must have these lines (called pre- processor
directives) at the start of the file:
– #include <iostream>
Tells C++ to use appropriate library so we can use the I/O
objects cin, cout
using namespace std;
When we include a new style header in our program, the contents of
that header are contained in the std namespace.
Earlier, the names of the C++ library functions, etc. were put into
the global namespace, but, with the use of new style headers, the
contents of these headers were placed in the std namespace.
#include<iostream.h>
Replaced with
#include<iostream>
using namespace std;
Console Output
Output using Insertion Operator
**cout: Standard Output Stream
Console Output
• What can be outputted?
– Any data can be outputted to display screen
• Variables
• Constants
• Literals
• Expressions (which can include all of above)
cout << numberOfGames << " games played.";
2 values are outputted:
"value" of variable numberOfGames,
literal string " games played."
• Cascading: multiple values in one cout
Separating Lines of Output
• New lines in output
– Recall:"\n" is escape sequence for the char "newline"
• A second method: object endl
• Examples:
cout << "Hello World\n";
• Sends string "Hello World" to display, & escape sequence "\n",
skipping to next line
cout << "Hello World" << endl;
• Same result as above
Input Using cin
• cin for input
• Differences:
– ">>" (extraction operator) points opposite
• Think of it as "pointing toward where the data goes"
– Object name "cin" used instead of "cout"
– No literals allowed for cin
• Must input "to a variable"
• cin >> num;
– Waits on-screen for keyboard entry
– Value entered at keyboard is "assigned" to num
Console Input
Input using Extraction Operator
**cin: Standard Input Stream
Prompting for Input: cin and cout
• Always "prompt" user for input
cout << "Enter number of entries: ";
cin >> numOfentries;
– Note no "\n" in cout. Prompt "waits" on same line for
keyboard input as follows:
Enter number of entries: ____
• Underscore above denotes where keyboard entry is made
#include<iostream>
using namespace std;
int main()
{
char str[40];
int m1,m2,m3,avg;
cout<<“Enter your name:”;
cin>>str;
cout<< “Enter marks of three subjects:”;
cin>>m1>>m2>>m3;
avg= (m1+m2+m3)/3;
cout<< “Your name is”<<str;
cout<< endl<<“Your average marks are”<<avg;
return 0;
}
Output is:
Enter your name: Anu
Enter marks of three subjects: 44 72 64
Your name is Anu
Your average marks are 60
Output is:
Enter your name: Ram
Enter marks of three subjects: 44 72 64
Your name is Ram
Your average marks are 60
C++ Tokens
C++ Tokens
Tokens are the minimal chunk of program that have meaning to the
compiler – the smallest meaningful symbols in the language.
C++ Keywords
C++ Identifiers
• User defined names
• Rules
– An identifier can consist of alphabets, digits and/or
underscores.
– It must not start with a digit.
– C++ is case sensitive i.e., upper case and lower
case letters are considered differently.
– It should not be a reserved word/ declared
keyword.
C++ Identifiers
C++ Variables
– A memory location to store data for a program
– Must declare all data before use in program
Simple Data Types (1 of 2)
Simple Data Types: (2 of 2)
Literal Data
• Literals
– Examples:
• 2 // Literal constant int
• 5.75 // Literal constant double
• ‘Z’ // Literal constant char
• "Hello World" // Literal constant string
• Cannot change values during execution
• Called "literals" because you "literally typed"
them in your program!
Escape Sequences
• "Extend" character set
• Backslash, \ preceding a character
– Instructs compiler: a special "escape character" is
coming
– Following character treated as "escape sequence
char"
Some Escape Sequences (1 of 2)
Some Escape Sequences (2 of 2)
C++ Constants
• Naming your constants
• Use named constants instead
– Meaningful name to represent data
const int NUMBER_OF_STUDENTS = 24;
• Called a "declared constant" or "named constant"
• Now use it’s name wherever needed in program
Usage of Named Constant
Different Types of Operators
Precedence of Operators (1 of 4)
Precedence of Operators (2 of 4)
Precedence of Operators (3 of 4)
Precedence of Operators (4 of 4)
:: Operator
#include<iostream>
using namespace std;
int a=10;
int main()
{
int a=15;
cout<<“\nLocal a=“<<a<<“Global a=“<<::a;
::a=20;
cout<<“\nLocal a=“<<a<<“Global a=“<<::a;
return 0;
}
Output
Local a=15 Global a=10
Local a=15 Global a=20
Output
Local a=15 Global a=10
Local a=15 Global a=20
:: Operator
If we attempt to access the variable a in the function, we always access the
local variable.
The rule says that whenever there is a conflict between a local and global
variable, the local variable gets the priority.
The global variable is inaccessible, when a local variable of the same name is
available within the function.
This is achieved through scope resolution operator.
Control Structures
Control Structures
Branching Mechanisms
• if-else statements
– Choice of two alternate statements based
on condition expression
– Example:
if (hrs > 40)
grossPay = rate*40 + 1.5*rate*(hrs-40);
else
grossPay = rate*hrs;
if-else Statement Syntax
• Formal syntax:
if (<boolean_expression>)
{
<yes_statement>
}
else
{
<no_statement>
}
Common Pitfalls
• Operator "=" vs. operator "=="
• One means "assignment" (=)
• One means "equality" (==)
– VERY different in C++!
– Example:
if (x = 12) Note operator used!
Do_Something
else
Do_Something_Else
Conditional Operator
• Also called "ternary operator"
– Allows embedded conditional in expression
– Essentially "shorthand if-else" operator
– Example:
if (n1 > n2)
max = n1;
else
max = n2;
– Can be written:
max = (n1 > n2) ? n1 : n2;
• "?" and ":" form this "ternary" operator
Nested Statements
• if-else statements contain smaller statements
– Can also contain any statement at all, including another if-
else stmt!
– Example:
if (marks > 80)
if (marks >= 85)
cout << "Your grade is A";
else
cout << " Your grade is A-”;
– Note proper indenting!
Multiway if-else Example
The switch Statement
• A new stmt for controlling multiple branches
• Uses controlling expression which returns bool data
type (true or false)
switch Statement Syntax
The switch Statement in Action
The switch: multiple case labels
• Execution "falls thru" until break
– switch provides a "point of entry"
– Example:
case ‘A’:
case ‘a’:
cout << "Excellent: you got an \" A \" ! \n";
break;
case ‘B’:
case ‘b’:
cout << "Good: you got a \" B \" ! \n";
break;
– Note multiple labels provide same "entry"
Loops
• 3 Types of loops in C++
– while
• Most flexible
• No "restrictions"
– do-while
• Least flexible
• Always executes loop body at least once
– for
• Natural "counting" loop
while Loops Syntax
do-while Loop Syntax
while Loop Example
• Consider:
count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}
– Loop body executes how many times?
do-while Loop Example
count = 0; // Initialization
do
{
cout << "Hi "; // Loop Body
count++; // Update expression
} while (count < 3); // Loop Condition
– Loop body executes how many times?
– do-while loops always execute body at least once!
for Loop Syntax
for (Init_Action; Bool_Exp; Update_Action)
Body_Statement
OR
for (Init_Action; Bool_Exp; Update_Action)
{
Body_Statements
}
for Loop Example
• for (count=0;count<3;count++)
{
cout << "Hi "; // Loop Body
}
• How many times does loop body execute?
• Initialization, loop condition and update all "built
into" the for-loop structure!
• A natural "counting" loop
Nested Loops
• Recall: ANY valid C++ statements can be
inside body of loop
• This includes additional loop statements!
– Called "nested loops"
• Requires careful indenting:
for (outer=0; outer<5; outer++)
for (inner=7; inner>2; inner--)
cout << outer << inner;
– Notice no { } since each body is one statement
The break and continue Statements
• Flow of Control
– Recall how loops provide "graceful" and clear flow of
control in and out
– In RARE instances, can alter natural flow
• break;
– Forces loop to exit immediately.
• continue;
– Skips rest of loop body
• These statements violate natural flow
– Only used when absolutely necessary!
Functions
• Function is a self contained block of
statements that perform a coherent task of
some kind.
• Every C++ program can be a thought of the
collection of functions.
• main( ) is also a function.
Types of Functions
• Library functions
– These are the in- -built functions of ‘C++ ’library.
– These are already defined in header files.
• User defined functions.
– Programmer can create their own function in C++
to perform specific task
a) Actual arguments:-the arguments of calling
function are actual arguments.
b) Formal arguments:-arguments of called
function are formal arguments.
c) Argument list:-means variable name enclosed
within the paranthesis. They must be
separated by comma
d) Return value:-it is the outcome of the
function. the result obtained by the function is
sent back to the calling function through the
return statement.
Function Declaration
ret_type func_name(data_type par1,data_type
par2);
Or ret_type func_name(data_type,data_type);
Function Defination
ret_type func_name(data_type par1,data_type par2)
{
}
Function Call
func_name(par1, par2);
Function prototype
• A prototype statement helps the compiler to check
the return type and arguments type of the function.
• A prototype function consist of the functions return
type, name and argument list.
• If before function call the definition for function
isn’t there then prototype must be provided before
the call so that compiler can recognize the function it
is calling.
• Example
– int sum( int x, int y);
#include<iostream>
using namespace std;
int main()
{
clrscr();
void sum(int, int); // function declaration
int a, b, c;
cout<<“enter the two no”;
cin>>a>>b>>c;
sum(a,b); // function calling
return 0;
}
void sum( int x, int y) // function definition
{
c=x+y;
cout<< “ sum is”<<c;
}
#include<iostream>
using namespace std;
int main()
{
int a=10,b=20;
int sum(int, int);
int c=sum(a,b); /*actual arguments
cout<<“sum is” << c;
return 0;
}
int sum(int x, int y) /*formal arguments
{
int s;
s=x+y;
return(s); /*return value
}
Categories of functions
• A function with no parameter and no return
value
• A function with parameter and no return value
• A function with parameter and return value
• A function without parameter and return value
A function with no parameter and no return
value
#include<iostream>
using namespace std;
int main()
{
clrscr();
void print(); // declaration
cout<<“no parameter and no return value”;
print(); // calling
return 0;
}
void print() // definition
{
for(int i=1;i<=30;i++)
{
cout<<“*”;
}
cout<<“\n”;
}
A function with parameter and no return value
#include<iostream>
using namespace std;
int main()
{
int a=10,b=20;
void mul(int,int);
mul(a,b); /*actual arguments
return 0;
}
void mul (int x, int y) /*formal arguments
{
int s;
s=x*y;
cout<<“mul is” << s;
}
A function without parameter and return value
#include<iostream>
using namespace std;
int main()
{
int a=10,b=20;
int sum();
int c=sum();
cout<<“sum is”<< c;
return 0;
}
int sum()
{
int x=10,y=30;
return(x+y); /*return value
}
A function with parameter and return value
#include<iostream>
using namespace std;
int main()
{
int a=10,b=20,c;
int max(int,int);
c =max(a,b);
cout<<“greatest no is” <<c;
return 0;
}
int max(int x, int y)
{
if(x>y)
return(x);
else
{
return(y);
}
}
Some important points
• A function declaration, definition, and call
must match in number, type and order of
actual and formal arguments.
• A function can be called from other function
but a function cannot be defined inside another
function.
• The actual arguments in a function can be
variables, constants, or expression where as
formal arguments must be variables.