0% found this document useful (0 votes)
34 views

C++ Data Types, Input & Output, Operators & Control Flow Statements

c++ programming

Uploaded by

yiyoro2061
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

C++ Data Types, Input & Output, Operators & Control Flow Statements

c++ programming

Uploaded by

yiyoro2061
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

C++ Data Types

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.

Data types in C++ are categorised in three groups: Built-in, user-


defined and Derived.

Wide characters are similar to character datatype. The main


difference is that char takes 1-byte space, but wide character takes
2-bytes (sometimes 4-byte depending on compiler) of space in
memory.
Built in data types
Primitive Built-in Types
C++ offers the programmer a rich assortment of built-in as well as user defined data
types. Following table lists down seven basic C++ data types −

Type Keyword

Boolean bool

Character char

Integer int

Floating point float

Double floating point double

Valueless void

Wide character wchar_t

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.

Type Typical Bit Width Typical Range

Char 1byte -127 to 127 or 0 to 255


unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int 2bytes 0 to 65,535

signed short int 2bytes -32768 to 32767

long int 8bytes -2,147,483,648 to 2,147,483,647

signed long int 8bytes same as long int

unsigned long int 8bytes 0 to 4,294,967,295

long long int 8bytes -(2^63) to (2^63)-1

unsigned long long int 8bytes 0 to 18,446,744,073,709,551,615

Float 4bytes 1.175494351 E – 38

to 3.402823466 E + 38 (7 digits)

Double 8bytes 2.2250738585072014 E – 308

to 1.7976931348623158 E + 308 (15 digits)


long double 12bytes Same as double

wchar_t 2 or 4 bytes 0 to 65,535 (1 wide character)

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;
}

User-defined data types


We have three types of user-defined data types in C++
1. struct
2. union
3. enum

Derived data types in C++


We have three types of derived-defined data types in C++
1. Array
2. Function
3. Pointer
Example Programs

#include <iostream>

using namespace std;

int main()

cout << "Welcome to C++ Programming.";

return 0;

#include<iostream> includes the standard input output library functions. It


provides cin and cout methods for reading from input and writing to output
respectively.

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.

Example program using cout and cin

Standard output stream (cout)

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

Standard input stream (cin)


The cin is a predefined object of istream class. It is connected with the standard input
device, which is usually a keyboard. The cin is used in conjunction with stream extraction
operator (>>) to read the input frosm a console.

#include <iostream>

using namespace std;

int main( )

int age;

cout << "Enter your age: ";

cin >> age;

cout << "Your age is: " << age << endl;

Standard end line (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>

using namespace std;

int main( )

cout << "C++ ";

cout << " Java"<<endl;

cout << "End of line"<<endl;

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

Double slash comment is basically a single line comment.


Example:

// this is an example of C++ program to illustrate some of its features

The above example can also be written as a multiline comment as follows

// this is an example of

// C++ program to illustrate

// some of its features

The C comment symbols /*, */ are still valid and are more suitable for multiline comments

Example:

/* this is an example of

C++ program to illustrate

Some of its features */

C++ allows the declaration of a variable anywhere in the scope, this


means that a variable can be declared right at the place of its first use.

Syntax to declare a variable :

[data_type] [variable_name];

Consider the example

#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<" Enter first number :";
cin>>a;
cout<<" Enter second number:";
cin>>b;

int sum; // declaration


sum=a+b;
cout<<" Sum is : "<<sum <<"\n";
return 0;
}

Example program:

// program to read two numbers from the keyboard and display their average

#include <iostream>

using namespace std;

int main()

float n1,n2,sum,average;

cout << ”enter two numbers:” ; //prompt message

cin >> n1; // read numbers from the key board

cin >> n2;

sum=n1+n2;

average=sum/2;

cout << ”Sum =” << sum << ”\n”;

cout << ”Average=” << average << ”\n”;

return 0;

Output:

Enter two numbers: 6.5 7.5

Sum=14

Average=7
Cascading of I/O operators

In the above program, the statement

cout << “Sum = “ << sum << “\n”;

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:

cout << “Sum = “ << sum << ”\n”

<< “Average =” << average << “\n”;

This is one statement but provides two lines of output. If we want only one line of output,
the statement will be:

cout << “Sum = “ << sum << ”,”

<< “Average =” << average << “\n”;

We can also cascade input operator >> as follows

cin >> n1 >> n2;

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 :

const [data_type] [constant_name]=[value];

Consider the example

#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;
}

Explain about the c++ Operators

An operator is a symbol that tells the compiler to perform specific mathematical or


logical manipulations. C++ is rich in built-in operators and provide the following types
of operators −

• 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 −

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200


/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an B % A will give 0


integer division

++ Increment operator, increases integer value A++ will give 11


by one

-- Decrement operator, decreases integer A-- will give 9


value by one

Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

== Checks if the values of two operands are (A == B) is not true.


equal or not, if yes then condition becomes
true.

!= Checks if the values of two operands are (A != B) is true.


equal or not, if values are not equal then
condition becomes true.

> 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.

< Checks if the value of left operand is less (A < B) is true.


than the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if
yes then condition becomes true.

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to 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 −

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then condition
becomes true.

! Called Logical NOT Operator. Use to !(A && B) is true.


reverses the logical state of its operand. If a
condition is true, then Logical NOT operator
will make false.

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for
&, |, and ^ are as follows −

p q p&q p|q p^q

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 −

Operator Description Example

& Binary AND Operator copies a bit to the


(A & B) will give 12 which is 0000 1100
result if it exists in both operands.

| Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is 0011 1101
either operand.

^ Binary XOR Operator copies the bit if it is


(A ^ B) will give 49 which is 0011 0001
set in one operand but not both.

~ 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.

>> Binary Right Shift Operator. The left


operands value is moved right by the
A >> 2 will give 15 which is 0000 1111
number of bits specified by the right
operand.

Assignment Operators
There are following assignment operators supported by C++ language −

Operator Description Example


= Simple assignment operator, Assigns values C = A + B will assign value of A + B into
from right side operands to left side operand. C

+= Add AND assignment operator, It adds right


operand to the left operand and assign the C += A is equivalent to C = C + A
result to left operand.

-= Subtract AND assignment operator, It subtracts


right operand from the left operand and assign C -= A is equivalent to C = C - A
the result to left operand.

*= Multiply AND assignment operator, It multiplies


right operand with the left operand and assign C *= A is equivalent to C = C * A
the result to left operand.

/= Divide AND assignment operator, It divides left


operand with the right operand and assign the C /= A is equivalent to C = C / A
result to left operand.

%= Modulus AND assignment operator, It takes


modulus using two operands and assign the C %= A is equivalent to C = C % A
result to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

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.

new and delete operators (or) Memory management operators

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

The syntax for the new operator is:

pointer_variable = new data_type;


The syntax for the delete operator is:

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.

1.Conditional control structures


Here the condition is tested for whether the result is true or false and the action is taken
according to these tow results. There are three structures available under this group.
a) if
b) if-else
c) nested if-else

2.Multiple branching control structure


In this case a selection is made from several alternatives available, and a group of
instructions pertaining to the selected alternative only executed. There is only one type under
this group using tow keywords.
a) switch-case

3.Loop Control structures


This is for repeated execution of group of instructions till a condition evaluates to a
true. There are three types available under this group.
a) while
b) do-while
c) for

4.Jump Control structures


These statements cause the control to pass to any desired location in the program.
They are:
a) break
b) continue
c) goto

1.Conditional Control Structures:

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.

/* W.A.P To check weather the given number is even or odd number */


#include <iostream>
using namespace std;
int main()
{
int num,r;
cout<<Enter any number";
cin>>num;
r=num%2;
if(r==0)
{
cout<<"The given number is even number";
}
else
{
cout<<"The given number is odd number”;
}
}

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();
}

2) Multiple Branching Control Structure:

a) Switch-case:
Syn:
switch(expression)
{
case value1:
Statements;
case value2:
Statements;
case value3:
Statements;

.
.
.
.
default:
Statements;
}

The if is the single-selection structure and the if-else double-selection structure.

Switch is a multiple-selection structure to handle decision-making. The switch


structure consists of a series of case labels, and an optional default case.

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.

The expression is an integer expression or characters. Value1,value2,…..are


constants or constant expressions and are known as case labels. Each of these values
should be unique within a switch statement. Block1,block2,…….are statements lists and may
contain zero or more statements. There is no need to put braces around these blocks. Note
that case labels end with a colon (:).

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.

/* W.A.P to perform arithmetic operations on two numbers using switch case


structure */
#include <iostream>
using namespace std;
int main()
{
int a,b;
char op;
clrscr();
cout<<"Enter any two numbers";
cin>>a>>b;
cout<<"Enter an operator";
cin>>op;

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;
}

3) Loop control structures:

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.

/* W.A.P to display first 'N' numbers */


#include <iostream>
using namespace std;
int main()
{
int n,i;
clrscr();
cout<<"Enter N value\n";
cin>>n;
i=1;
do
{
cout<<i;
i=i+1;
}
while(i<=n);
}

Differences Between While and do-while:


In while loop, if the condition becomes false at first checking the statements are not
executed at least once.
In do-while, the statements are executed at least once, what ever may be the condition,
because in do-while, the control directly enters into the loop and execute the statements once,
after that it checks the condition.
c) for loop:

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.

/* W.A.P to display first 'N' numbers using for loop */


#include <iostream>
using namespace std;
int main()
{
cout<<"Enter N value \n";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<i;
}
}

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.

The general form is,

break;

Break Statement in nested loops:

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.

/* Demonstration of the break 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)
{
break;
}
sum=sum+num;
}
cout<<"The sum is"<<sum;
}

b) The continue 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;
}

c) The goto Statement:

This is an unconditional branching statement and its use is discouraged in structured


programming. But C does allow use of goto statement. In a language that provides the various
loop statements like for, while and do while as well as the switch statement, there is normally
no need to use the goto statement. A complicated situation can be managed with break and
continue statements. If we want to come out of several nested loops at one stroke, the use of
goto statement may be useful. The general form of got statement is
goto label;

Here label is an identifier which identifies the statement to which is to be passed.


Control can be passed to any part of the current function in which the got appears.
/* Demonstrating goto statement */

#include <iostream>
int main()
{
int count = 1;
start: /* label */
if(count>10)
{
goto end;
}
cout<<count<<endl;
++count;
goto start;
end: /* label */
cout<<’\n’;
}

You might also like