Skip to main content

Introduction To C++ Programming - Part 1.

Hello World:
// File name: hello_world.cpp
// A simple C++ program which prints "Hello World!" on the screen.

#include <iostream>        // header file to support the C++ I/O system.
using namespace std;     // telling the compiler to use namespace "std",
// where the entire C++ library is declared.
int main() {
cout << "Hello World!" <<  endl;
/*
cout is the standard output device on the screen.
<< causes the expression on its right to be directed to the device on its left.
return 0; indicates the successful termination of the "main" function.
*/
return 0;
}
Output:
Hello World!

Variables And Constants:
// File name: variable.cpp
// Demonstrate the use of variables and constants.

#include <iostream>
using namespace std;
const int CONST_VAL = 5; // declaring a constant. Its value can't be changed.

int main() {
int    iValue;    // an integer variable
float  fValue;  // a floating point variable
char   cValue;  // a character variable

iValue = 1234;     // assigns 1234 to iValue
fValue = 1234.56; // assigns 1234.56 to fValue
cValue = 'A';     // assigns A to cValue

//now print them out on the screen
cout << "Integer value is: " << iValue << endl;
cout << "Float value is: " << fValue <<  endl;
cout << "Character value is: " << cValue << endl;
cout << "The constant is: " << CONST_VAL << endl;
return 0;
}
Output:
Integer value is: 1234
Float value is: 1234.56
Character value is: A
The constant is: 5

Basic Input/Output:
// File name: basicIO.cpp
// Convert gallons to liters.

#include <iostream>
using namespace std;

int main() {
float gallons, liters;

cout << "Enter number of gallons: " << endl;
cin >> gallons; // Read the inputs from the user

liters = gallons * 3.7854; // convert to liters
cout << "Liters: " << liters << endl;
return 0;
}
Output:
Enter number of gallons: 14
Liters: 52.9956