Lecture 3 Introduction to C++
Lecture 3 Introduction to C++
Computer Programming
CHAPTER 1
INTRODUCTION TO C++
2
Why Use C++
#include <iostream>
is a header file library that lets us work with input and output objects, such as
cout
using namespace std;
means that we can use names for objects and variables from the standard
library.
int main()
The main function where Any code inside its curly brackets { } will be
executed.
5
First Program in C++ (cont.)
Description
The data type specifies the size and type of information the variable will store:
13
Declaring Variables
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = 6;
int sum = x + y;
cout <<“ the sum = “<< sum;
}
17
Declare Multiple Variables
To declare more than one variable of the same type, use a comma-
separated list:
int x = 5, y = 6, z = 50;
cout << x + y + z;
18
Rules for naming variables
You should always declare the variable as constant when you have values that are
unlikely to change
20
User Input
You have already learned that cout is used to output (print) values. Now we will
use cin to get user input.
cin is a predefined variable that reads data from the keyboard with the
extraction operator >>
In the following example, the user can input a number, which is stored in the
variable x Then we print the value of:
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
}
21
Operators
#include <iostream>
using namespace std;
int main() {
int x, y;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
28
Simple Calculator Program
cout << "Sum of the two numbers is: " << x + y <<endl;
cout << "Subtraction of the two numbers is: is: " << x - y <<endl;
cout << "product of the two numbers is: " << x * y <<endl;
cout << "Division of the two numbers is: " << x / y <<endl;
}
29
Program Output Screen
30
End