Tuesday 13 November 2012

C++ Sample programs


Input/Output Instruction

In C, standard input device is keyboard and scanf() is use to receive data from keyboard.
Also, standard output device is monitor and printf() is use to send data/message to monitor.

In C++, printf() can be replaced by ‘cout’:
 cout<<”Hello RAM”;
 This statement introduces two new C++ features, cout and <<.
 cout is a predefined object.
 The operator << is called the insertion or put to operator
 It is used to display message on the screen.

Examples:
printf(“Hello RAM”);
cout<<“Hello RAM”;
printf(“sum of %d and %d is %d”, a, b, c);
cout<<“sum of ”<<a<<“ and “<<b<<“ is “<<c;
printf(“%d”,a+b);
cout<<a+b;



In C++, scanf() can be replaced by ‘cin’:
 cin>>x;
 cin>>y>>z;
 The identifier cin is a predefined object in C++
 The operator >> is known as extraction or get from operator
 It is used to take input from keyboard.

Examples:
scanf(“%d”, &a);
cin>>a;
scanf(“%d%d”, &a, &b);
cin>>a>>b;
scanf(“%d%f”, &a, &c);
cin>>a>>c;


About header file iostream.h
We need to include header file iostream.h, as it contains declarations for the identifier cout and the operator <<. Also it contains declarations for the identifier cin and operator >>.


Sample Program: 
#include<iostream.h>
void main()
{
int x, s;
cout<<”Enter a number”;
cin>>x;
s=x*x;
cout<<”Square of “<<x<<” is “<<s;
}

No comments:

Post a Comment