Chapter 6
Introduction to Pogramming
Prepared By TCA Gafoor,
AKM HSS Kottoor,Malappuram
http://www.hsslive.in
Structure of a C++ program
//A sample program to display a string on the
monitor
#include<iostream>//to include header files for working
library functions
Using namespace std;
int main()// It is the function invoked by the compiler first
{
cout <<“My first program in C++”; //to display on
screen
return 0;
}
Pre-processor Directives
• Which gives instruction to compiler to
process the information before actual
program compilation
• Eg;#include<iostream>
• #define
• (NB: No Semi colon(;) required for Pre-
processor directive statements)
Header files
• Header files with contains the information
about functions,objects, datatypes etc
• Eg:
• iostream file contains information about
functions cin and cout
• iostream.h is used for Turbo C++ in
windows
http://akmhsskottoor.webs.com
Using namespace std;
• A program cannot have same name for
more than one identifier (like peoples have
different names in same house).
• using namespace std is used to set the
names of identifiers unique
• If it is not added in code,we must use
std::cin or std::cout for input/output
functions
The main function
• Execution of a c++ program starts from
main() function.
• All statements are written inside the min
function
• (Every function in c++ should return some values,so we must put a data
type before the main function.if we want to return nothing,we can write
return 0 at last )
• int main()
• {
• Statement codes;
• }
Sample program for windows
#include<iostream.h>
void main()
{
cout <<“Hello, Welome to C++”;
}
Sample program for Linux
#include<iostream>
using namespace std;
int main()
{
cout <<“Hello, Welcome to C++”;
}
Guide lines for coding
• Use suitable names for identifiers:
• (it is better to use salary=amount-tax
• in the place s=a-t)
• Use clear and simple expression
• (it is better to use ans=x%y
• in the place ans=x-(x/y)*y) ,both gives same result when proper data type
used
• Use Comments:use of comments make the codes easy to
under stand for others.Comments can be written by putting a (//) mark or
writing inside(/* …………… */)
• Use Relevant indentation(Spacing): use
proper spacing between codes makes it better to communicate
Variable initialisation
• Variables are identifiers of memory location.
• That is, variables are the names given to
storage location by which the contents of
those locations can be referenced.
• Variables are to be declared in the program
prior to its use in it.
• Eg: int a=10;
• Float pi=3.14;
Variables
• The syntax is:
datatype Variablename;
• Examples:
• Int num;
• float p,q,root;
• int sum=10;
• const float pi = 3.14;
• In the third example the variable ‘sum’ is assigned with a
value 10, which is called the variable initialization. The
fourth statement declares pi as a constant with value 3.14,
which cannot be changed during the program exeution.
Data Type Modifiers
• Type modifiers are the keyword used
along with the basic data types to change
the size,range of data handled by the
basic types.
• The type modifiers of C++ are
– signed, Int: a can store up to 32767
Unsigned int: can store up to 65535
– unsigned, Long int: can store up to 21474883647
– long and
– short.
Operators
• Consider the expression or statement or
operation
• Sum=A+B*C
• Here sum, A, B, C are operands, =, +, * are
operators
• The symbols that used in an operations are
called operators.
• An operation requires operator and operands
• Operands are the data on which the specified
task is carried out.
Arithmetic assignment operators
• An arithmetic operator(+,-,*,/,%) and
Assignment operator(=) can be mixed to
form another meaning (+=,-+,*=,/=,%=)
• Eg: a+=10 a=a+10
• P*=10 P=P *10
Increment / Decrement Operators
• The Increment operator (++) adds 1 to its
operand and Decrement operator (--)
subtracts 1 from its operand.
• int a=5, b=3
• ++a;
• b++;
• a--;
Increment / Decrement Operators
• The values of a and b will be 6 and 2
respectively after the execution of these
statements. i.e., ++a; is equivalent to
a=a+1 (7); and --b; is same as b=b-1 (1);
Prefix and Postfix form
• There are two forms for these operators: postfix (a++
and b --) & prefix (++a and --b).
• c = a++, c = ++a; and c = b-- , c = --b are different.
• If a= 5 and b=3
• In the first case c = 5 and c = 6, but in the latter case
c=3 and c=2.
• The statement c=a++; is equivalent to the statement
sequence c=a; a=a+1; (use and change method)
• But the statement b=++a; is equivalent to the
statement sequence a=a+1; c=a; (change and use
method)
Comma Operator
• It is used to string together several expressions.
The group of expressions separated by commas
will be evaluated from left to right in sequence
and the result of the right most expression will be
value of the total comma separated expression.
• For example, b=(a=1,a+1); will assign 1 to a
first and then evaluates a+1 to 2 which will be
stored in b. (Here parentheses is must because
comma operator has lower precedence than
assignment operator).
Precedence of operators
• ++ (post increment), -- (post decrement)
• ++ (pre increment), -- (pre decrement), sizeof(), ! (not), - (unary minus),
+ (unary plus)
• (multiply), / (divide), % (modulus)
• + (add), -(subtract)
• < (less than), <= (less or equal), > (greater than), >= (greater than or
equal)
• = = (equal), ! = (not equal)
• && (Logical AND)
• || (logical OR)
• ? : (Conditional expression)
• =(simple assignment) and arithmetic assignment opetors (+=, -=,*=,/=,
%=)
• , (comma operator)
Type Conversion
• Consider the following code snippet.
int a=5, b=2;
float ans;
ans=a/b;
cout <<ans;
• When constants and variables of
different types are mixed in an expression
proper type conversion methods are applied
to get the correct result.
Type Conversion
• Type conversion is the process of converting
predefined data types into another data type
in a particular expression. Type conversions
are of two kinds:
• Implicit type conversion (type promotion)
• Explicit type conversion (type casting)
type promotion
• Here the conversion is done by the
complier without programmer’s instruction.
In this case the complier converts all
operands up to the type of the largest
operand.
Int a,b,c;
c=a+b;
• When we input a=3 and b=6.987 the result
is 9, here the float type is converted n to in
by the compiler.
Implicit type conversion
(type promotion)
• Example
Char ch; int a; float f; double db; long double
ld;
exp=ch*a-f/db+(f+a)-db/id;
• After evaluation of the above expression
the data type of exp is long double.
Explicit type conversion
(type casting)
• Here the user is responsible for the conversion to a
specific type.
int a=5, b=2;
float ans;
ans=a/b;
cout <<ans;
• Here the result become 2
• The problem in the above code fragment can be
overridden by the following statement.
• ans=(float)a/b;
• Then the result become 2.5
C++ Short hands
a=a+1; can be written as a+=1;
x-=10 ; is same as x=x-10;
If A=10
B=A++ (here B=10 & A=11) because use
then change method (post fix form)
If A=10
B=++A (here B=11 & A=11) because
change then use method (prefix form)
Sample Programs
Write a program to find sum and average
of 3 numbers
//Sum and Average of 3 numbers
#include<iostream.h>
void main()
{
int a,b,c,sum,avg;
cout<<"Enter 3 Numbers:";
cin>>a>>b>>c;
sum=a+b+c;
avg=sum/3;
cout<<"Sum="<<sum;
cout<<"\nAverage="<<avg;
} http://akmhsskottoor.webs.com
Program to find simple
interest for a an amount
//Simple interest
#include<iostream>
using namespace std;
int main()
{
int p,n,r,si;
cout<<"Enter Principal Amount:";
cin>>p;
cout<<"Enter Number of years:";
cin>>n;
cout<<"Enter Rate of Interest:";
cin>>r;
si=p*n*r/100;
cout<<"Simple interest="<<si;
} http://akmhsskottoor.webs.com
Program to swap the content
(interchange) of two variables
//Swapping the contents of two variables
#include<iostream>
using namespace std;
int main()
{
int a,b,temp;
cout<<"ENTER TWO INTEGER NUMBERS:";
cin>>a>>b;
cout<<"BEFORE SWAPPING A="<<a<<"\tB="<<b;
temp=a;
a=b;
b=temp;
cout<<"\nAFTER SWAPPING A="<<a<<"\tB="<<b;
} http://akmhsskottoor.webs.com
Program to print ASCII code
of a inputted number
//To print ASCII of a number
#include<iostream>
using namespace std;
int main()
{
int a;
char ch;
cout<<"ENTER A NUMBER:";
cin>>a;
ch=a;
cout<<"ASCII VALUE OF "<<a<<"="<<ch;
}
Program to print Next character of
an inputted character
//To print next character
#include<iostream>
using namespace std;
int main()
{
char ch;
cout<<"ENTER A CHARACTER:";
cin>>ch;
ch=ch+1;
cout<<"NEXT CHARACTER IS:"<<ch;
}
http://akmhsskottoor.webs.com
Program to find biggest from 2
numbers by using conditional
operator
//Biggest from two numbers
#include<iostream>
using namespace std;
int main()
{
int a,b,big;
cout<<"Enter two numbers:";
cin>>a>>b;
big=(a>b)?a:b;
cout<<"Biggest number is: "<<big;
} http://akmhsskottoor.webs.com
Program to display the time
corresponding to a integer number
// Time
#include<iostream>
using namespace std;
int main()
{
int time, hr, mts, sec;
clrscr();
cout<<"Enter the time in seconds:";
cin>>time;
hr=time/3600;
time=time%3600;
mts=time/60;
sec=time%60;
cout<<"Time is:"<<hr<<" Hrs:"<<mts<<" Mins: "<<sec<<"
Secs";
getch(); http://akmhsskottoor.webs.com
Chapter at a glimpse
Concepts of data types,
built in data types, int, char, float, double, void,
constants: integer, character, escape sequence: \n, \t, \a, \r, floating point
constants,
variables of built in data types,
access modifier,
const,
type modifiers, signed, unsigned, long, short,
operators: arithmetic, unary+ and unary -, Increment decrement, relational,
logical, conditional,
precedence of operators,
Expressions
, type conversions: implicit and explicit methods,
C++ short hands,
assignment statement,
variable initialization,
type compatibility. http://akmhsskottoor.webs.com
Model Questions
1. You are supplied with a list of tokens in C++ program. Identify,
Classify, and categorize them under proper headings. Explain each
category with its features.
tot_mark, age, M5, break, (), int, pay, ;, cin
2. In C++ the size of the string “book” is 5 and that of “book\n”
is 6. Check the validity of the above statement. Justify your answer.
3. Is Ox85B a valid integer constant in C++? Justify your answer.
4. Pick the odd man out. Justify.
totsal, tot_sal, TOTSAL, _totsal
totsal5, tot5_sal, saltot, tot.sal
5. Write a C++ statement to print the following sentence. Justify.
“\ is a special character”
http://akmhsskottoor.webs.com
6. Following is a simple program in C++. Identify the errors and correct the code.
*#include<iostream>
using namespace std;
int main()
{
*/It is a simple program*/
cout<< “Welcome to C++”
cout<< “The End”
}
7. Trace out and correct the errors in the following code fragments.
a) cout<< “mark=”45;
b) cin<< “Hello World!”;
c) cout>> “x+y”;
d) cout<< ‘Good’<< ‘Moning’
8. A C++ program code is given below to find the value of X using the expression X= a2+b2 where, a,
b are variables.
#include<iostream>
using namespace std;
int main()
{
int a,b;
float x;
cout<< “enter the values of a and b:”;
cin>a>b;
x=a*a + b*b / 2*a;
cout>>x;
}
Predict the type of errors during compilation, execution and verify the output. Also write the output of
two sets of input values.
a) a=4 b=8 http://akmhsskottoor.webs.com
b) a=0 b=2
10. A list of data items are given below.
45, 8.432, M, 0.124, 8, 0, 8.1x1031, 1010, a, 0.00025, 9.2x10120, 0471, -846, 342, 123E03
a) Categories and explain the above with proper headings of fundamental data type.
11. Write valid reasons for the following.
a) Char num=66;
Char num= ‘B’;
b) 35 and 35L are different.
c) The number 14, O16 and OxE are one and the same.
d) Char data type is often said to be an integer type.
e) To store the value 4.15 float data type is preferred over double.
12. A student executes a program to find factorial of a number. Its output is correct for
numbers up to 7, after that he gets wrong answer. Help him to overcome this problem.
#include<iostream>
using namespace std;
int main()
{
int n, fact;
fact=1;
cout<< “Enter an integer number:”;
cin>>n;
while(n)
{
Fact=fact*n;
n--;
}
cout<<fact;
} http://akmhsskottoor.webs.com
13. Match the following.
a) 142789 i) Signed int
b) 240 ii) Double
c) -150 iii) Long int
d) 8.4x10-4000 iv) float
e) 0 v) long double
f) 0.0008 vi) Unsigned short
g) -127 vii) short int
h) 2.8x10308 viii) signed char
14. Suggest most suitable derived data types in C++ for storing the
following data items or statements.
a) Age of 50 students in a class
b) Address of a memory variable
c) A set of instructions to find out the factorial of a number.
d) An alternate name for a previously defined variable.
e) Price of 100 products in a consumer store.
f) Name of a student.
15. A C++ programmer wishes to use the identifier pi in his program code
wherever the value 3.14 appears. Write the C++ statement which is used
for this purpose. http://akmhsskottoor.webs.com
Chapter Ends
Prepared By TCA Gafoor,
AKM HSS Kottoor,Malappuram
http://www.hsslive.in