Print text and multiple statements
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! ";
cout << "Have a good day!";
return 0;
}
Print numbers and calculations
#include <iostream>
using namespace std;
int main() {
cout << 3;
cout << "\n" << 3 + 3;
return 0;
}
New lines and tab
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!\n\n";
cout << "I am learning C++\n";
cout << "Name\tAge\tCity" << endl;
cout << "Ali\t20\tBaghdad" << endl;
cout << "Sara\t19\tErbil" << endl;
return 0;
}
Comments
#include <iostream>
using namespace std;
int main() {
// This is a single-line comment
cout << "Hello World!";
/*
This is a multi-line comment.
*/
return 0;
}
Variables and changing values
#include <iostream>
using namespace std;
int main() {
int myNum = 15;
cout << myNum << endl;
myNum = 10;
cout << myNum << endl;
return 0;
}
Other variable types
#include <iostream>
#include <string>
using namespace std;
int main() {
int myNum = 5;
float myFloatNum = 5.99;
double myDoubleNum = 19.99;
char myLetter = 'D';
string myText = "Hello";
bool myBoolean = true;
cout << myNum << endl;
cout << myFloatNum << endl;
cout << myLetter << endl;
cout << myText << endl;
cout << myBoolean;
return 0;
}
User input – one number
#include <iostream>
using namespace std;
int main() {
int x;
cout << "Type a number: ";
cin >> x;
cout << "Your number is: " << x;
return 0;
}
User input – sum of two numbers
#include <iostream>
using namespace std;
int main() {
int x, y, sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
return 0;
}
Exercise – enter and display a user's name
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
getline(cin, name);
cout << "Your name is: " << name;
return 0;
}Ready to practice this lecture?