Thursday, 13 July 2017

C++ First Program

C++ Program

Before starting the abcd of C++ language, you need to learn how to write, compile and run the first C++ program.
To write the first C++ program, open the C++ console and write the following code:
  1. #include <iostream>  
  2. using namespace std;  
  3. int main( ) {  
  4.   int age;  
  5.    cout << "Enter your age: ";  
  6.    cin >> age;  
  7.    cout << "Your age is: " << age << endl;  
  8. }  
#include<iostream.h> includes the standard input output library functions. It providescin and cout methods for reading from input and writing to output respectively.
#include includes the console input output library functions. The getch() function is defined in conio.h file.
Using namespace std, tells the compiler to use standard namespace. Namespace collects identifiers used for class, object and variables. NameSpace can be used by two ways in a program, either by the use ofusing statement at the beginning, like we did in above mentioned program or by using name of namespace as prefix before the identifier with scope resolution (::) operator.
Example : std::cout << "A";
void main() The main() function is the entry point of every program in C++ language. The void keyword specifies that it returns no value.
cout <<, is used to print anything on screen, same as printf in C language. cin and cout are same asscanf and printf, only difference is that you do not need to mention format specifiers like, %d for int etc, in cout & cin.

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.
Let's see the simple example of standard end line (endl):
  1. #include <iostream>  
  2. using namespace std;  
  3. int main( ) {  
  4. cout << "C++ Tutorial";     
  5. cout << " Javatpoint"<<endl;   
  6. cout << "End of line"<<endl;   
  7. }   
Output:
C++ Tutorial Javatpoint End of line

getch() The getch() function asks for a single character. Until you press any key, it blocks the screen.

No comments:

Post a Comment

Please write your view and suggestion....