C++ Data Types, Input & Output, Operators & Control Flow Statements
C++ Data Types, Input & Output, Operators & Control Flow Statements
While writing program in any language, you need to use various variables to store
various information. Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve some space in
memory.
You may like to store information of various data types like character, wide character,
integer, floating point, double floating point, boolean etc. Based on the data type of a
variable, the operating system allocates memory and decides what can be stored in
the reserved memory.
(or)
Data types define the type of data a variable can hold, for example an integer
variable can hold integer data, a character type variable can hold character
data etc.
Type Keyword
Boolean bool
Character char
Integer int
Valueless void
Several of the basic types can be modified using one or more of these type modifiers
• signed
• unsigned
• short
• long
The following table shows the variable type, how much memory it takes to store the
value in memory, and what is maximum and minimum value which can be stored in
such type of variables.
to 3.402823466 E + 38 (7 digits)
The size of variables might be different from those shown in the above table,
depending on the compiler and the computer you are using.
Following is the example, which will produce correct size of various data types on
your computer.
#include <iostream>
using namespace std;
int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
#include <iostream>
int main()
return 0;
The std is a short form of standard, the std namespace contains the built-in classes
and declared functions. we can find all the standard types and functions in the C++
"std" namespace.
Namespace is a new concept introduced by the ANCI C++ standards committee. This
defines scope for the identifiers that are used in a program. For using the identifiers
defined in the namespace scope we must include the using directive. This will bring all
the identifiers defined in std to the current global scope.
int main() The main() function is the entry point of every program in C++
language. The default return type for all function in C++ is int. Therefore every main()
in C++ should end with a return(0) statement, otherwise a warning or an error might
occur.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to
C++ Programming." on the console.
The cout is a predefined object of ostream class. It is connected with the standard
output device, which is usually a display screen. The cout is used in conjunction with
stream insertion operator (<<) to display the output on a console
#include <iostream>
int main( )
int age;
cout << "Your age is: " << age << endl;
The endl is a predefined object of ostream class. It is used to insert a new line characters
and flushes the stream.
#include <iostream>
int main( )
Comments
C++ introduces a new comment symbol // (double slash). Comments start with a double
slash symbol and terminate at the end of the line. A comment may start anywhere in the
line
// this is an example of
The C comment symbols /*, */ are still valid and are more suitable for multiline comments
Example:
/* this is an example of
[data_type] [variable_name];
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<" Enter first number :";
cin>>a;
cout<<" Enter second number:";
cin>>b;
Example program:
// program to read two numbers from the keyboard and display their average
#include <iostream>
int main()
float n1,n2,sum,average;
sum=n1+n2;
average=sum/2;
return 0;
Output:
Sum=14
Average=7
Cascading of I/O operators
first sends the string “Sum=” to cout and then sends the value of sum. Finally, it sends the
newline character so that the next output will be in the new line. The multiple use of << in
one statement is called cascading. When cascading an output operator, we should ensure
necessary blank spaces between different items. Using the cascading technique, the last two
statements can be combined as follows:
This is one statement but provides two lines of output. If we want only one line of output,
the statement will be:
The values are assigned from left to right. That is, if we key in two values, say 10 and 20,
then 10 will be assigned to n1 and 20 to n2.
Constants
Constants refers to fixed values that do not change during the execution of a
program.
Declaration of a constant :
#include <iostream>
using namespace std;
int main()
{
const int max_length=100; // integer constant
const char choice='Y'; //character constant
const char title[]="www.includehelp.com"; //string constant
const float temp=12.34; // float constant
cout<<"max_length :"<<max_length<<endl;
cout<<"choice :"<<choice<<endl;
cout<<"title :"<<title<<endl;
cout<<"temp :"<<temp<<endl;
return 0;
}
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and
other operators one by one.
Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then −
Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.
Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then −
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for
&, |, and ^ are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table.
Assume variable A holds 60 and variable B holds 13, then −
| Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is 0011 1101
either operand.
~ Binary Ones Complement Operator is unary (~A ) will give -61 which is 1100 0011 in 2's
and has the effect of 'flipping' bits. complement form due to a signed binary
number.
<< Binary Left Shift Operator. The left operands
value is moved left by the number of bits A << 2 will give 240 which is 1111 0000
specified by the right operand.
Assignment Operators
There are following assignment operators supported by C++ language −
Misc Operators
The following table lists some other operators that C++ supports.
Sr.No Operator & Description
1
sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer, and
will return 4.
2
Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of
Y.
3
,
Comma operator causes a sequence of operations to be performed. The value of the entire
comma expression is the value of the last expression of the comma-separated list.
4
. (dot) and -> (arrow)
Member operators are used to reference individual members of classes, structures, and unions.
5
Cast
Casting operators convert one data type to another. For example, int(2.2000) would return 2.
6
&
Pointer operator & returns the address of a variable. For example &a; will give actual address
of the variable.
7
*
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.
In C++ programming language, the new and delete operators are mainly utilized
for dynamic memory allocation and deallocation. They enable us to dynamically
allocate and free the memory, which means that we can create objects whose size
and lifetime may be defined at runtime
Definition
The new operator is mainly utilized to allocate memory for an object or an array of
objects. It returns a pointer to the allocated memory. On the other hand, the delete
operator is mainly utilized to deallocate memory that was previously allocated with
new. It frees the memory pointed to by the pointer and sets the pointer to null.
Syntax
delete pointer_variable;
Control Structures
Usually Computer executes the instructions or statements of a program one by one in a
sequential manner. There are many situations in which this sequential execution need to be
altered with a few instructions being executed only when a condition is satisfied. There may
also be occasions when it may be necessary to execute a group of instructions repeatedly for
a fixed number of times or until some condition is satisfied. Under such situations programmer
may require to include control statements in his program. These control statements allow him
to alter the sequential order of execution.
The control constructs in C++ can be classified under the following four groups.
a) if:
syn:
if(condition)
Statements;
The condition must be placed within parentheses and the statement end with a
semicolon. The construct is executed in two steps. First, the condition is evaluated. In the
second step, a statement or a group of statements are executed if the evaluation is true.
If the condition evaluates false the statement or the entire block of statement within the
braces is skipped without execution.
b) if-else:
syn:
if(condition)
Statements;
else
Statements;
First the condition is evaluated. If it is true, then the statements with in if block are
executed. If it is false, then the statements with in else block are executed. The if block is
called True block and the else block is called false block.
c) Nested If-Else:
When a serried of decisions are involved, we may have to use more than one if…else
statement in nested form.
Syn:1 if(condition) Syn:2
{ if(condition)
if(condition) {
{ if(condition)
{
Statements;
Statements;
}
}
else
else
{
{
Statements; Statements;
} }
} }
else else
{ {
if(condition) Statements;
{ }
Statements;
else
Statements;
}
Syn:3 Syn:4
if(condition) if(condition)
{ {
Statements; Statements;
} }
else else
{ {
if(condition) if(condition)
{ {
Statements; Statements;
} }
else else
{ {
Statements; if(condition)
} {
}
statements;
else
statements;
/* W.A.P to accept age of a person from the user and display the status of that
person */
#include <iostream>
using namespace std;
int main()
{
int age;
cout<<"Enter u r age";
cin>>age;
if(age<=5)
{
cout<<"U r a child";
}
else
{
if(age<=12)
{
cout<<"U r a young";
}
else
{
if(age<=19)
{
cout<<"U r a teenager";
}
else
{
if(age<=35)
{
cout<<"U r a middleager";
}
else
{
cout<<"U r a adult";
}
}
}
}
getch();
}
a) Switch-case:
Syn:
switch(expression)
{
case value1:
Statements;
case value2:
Statements;
case value3:
Statements;
.
.
.
.
default:
Statements;
}
The switch-case statement tests the value of a given variable against a list of case
values and when a match is found, a block of statements associated with that case is
executed.
When the switch is executed, the value of the expression is successively compared
against the values value1, value2,……. If a case is found whose value matches with the value
of the expression, then the block of statements that follows the case are executed.
The break statement at the end of each block signals the end of a particular case and
causes an exit from the switch statement, transferring the control to the statement-x following
the switch.
The default is an optional case. When present, it will be executed if the value of the
expression does not match with any of the case values. If not present, no action takes place
if all matches fail and the control goes to the statements after the switch-case statement.
switch(op)
{
case '+':
cout<<"The sum of two numbers is "<<a+b;
break;
case '-':
cout<<"The subtraction is “<<a-b;
break;
case '*':
cout<<"The multiplication is"<<a*b;
break;
case '/':
cout<<"The division is"<<a/b;
break;
default:
cout<<"Invalid operator";
}
}
Example:
#include <iostream>
using namespace std;
int main(){
int score;
cout << "Score:";
cin >> score;
//Switch
switch(score){
case 0 ... 9:
cout << "b";
break;
case 11 ... 24:
cout << "c";
break;
case 25 ... 49:
cout << "d";
break;
case 50 ... 100:
cout << "e";
break;
default:
cout << "BAD VALUE";
break;
}
cout << endl;
return 0;
}
The loop control structures are useful to execute a statement or a set of statements for
a particular number of times.
The following are the loop Control structures:
1) while
2) do-while
3) for
a) while:
syntax:
while(condition)
{
Statements;
}
The condition is first evaluated and if the condition is true, then the body of the loop is
executed. After execution of the body, the test condition is once again evaluated and if it is
true, the body is executed once again. This process of repeated execution of the body
continues until the test-condition finally becomes false and the control is transferred out of the
loop. On exit, the program continues with the statement immediately after the body of the
loop.
The body of the loop may have one or more statements. The braces are needed only if the
body contains tow or more statements. However, it it’s a good practice to use braces even if
the body has only one statement.
/* W.A.P to find sum of individual digits sum in a given number */
#include <iostream>
Using namespace std;
int main()
{
int num,d,sum=0;
clrscr();
cout<<"Enter any number:";
cin>>num;
while(num!=0)
{
d=num%10;
sum=sum+d;
num=num/10;
}
cout<<"The sum of individual digits in a given number is "<<sum;
}
b) do-while:
syn:
do
Statements;
}
while(condition);
In do-while first the control directly enters into the loop and execute the statements
once, after that it checks the condition. If it is true the statements are executed once again.
So, that the statements are executed repeatedly until the condition becomes false.
Syn:
for(expression1;expression2;expression3)
{
Statements;
}
Here expression1 is called initialization expression, expression2 is called conditional
statements, and expression3 is called incrementation or decrementation statement.
1) The first component of the for, initialization expression is used to set initial value before
the loop begins.
2) The second component, the loop condition that determines the condition that must be
satisfied for the looping to continue. It is evaluated before each iteration. Looping continues
as long as this condition is satisfied. When the loop condition is evaluated as false, execution
of the loop is terminated and execution continues with a statement following the for loop.
3) The third component, increment defines how the init expression will change each time to
the loop is repeated.
4) Jump Constructs:
a) break:
The break statement causes an immediate exit from the do, for, switch or while
statement in which it appears. The program continues executing with the next program
statement following the do, for, switch or while statement block.
break;
If the break statement occurs in a nested loop, the exit is only from the innermost do,
for, while or switch statement which includes the break. The program continues executing
with the next program statement following the do, for, switch or while statement.
The continue statement is used with the loop statements do, for, and while. It
transfers program control to the place in the program where the next iteration of the loop
begins.
Unlike the break statement, the continue statement does not exit the loop entirely,
but courses only the particular iteration to be skipped. The next iteration of the loop is
continued.
Execution of the continue statement in a do while loop causes the execution to resume
with the test part of the loop statement. Execution of the continue statement in a for loop
causes execution to resume with the increment part of the for statement.
/* Demonstration of the continue statement */
#include <iostream>
using namespace std;
int main()
{
int i,num,sum=0;
clrscr();
cout<<"If we want to terminate the loop , enter negative number \n";
for(i=1;i<=100;i++)
{
cout<<"Enter a number";
cin>>num;
if(num<0)
{
continue;
}
sum=sum+num;
}
cout<<"The sum is",<<sum;
}
#include <iostream>
int main()
{
int count = 1;
start: /* label */
if(count>10)
{
goto end;
}
cout<<count<<endl;
++count;
goto start;
end: /* label */
cout<<’\n’;
}