C++ beginner s2-basic
Type
int iValue = 10;
bool bValue = true;
string sName = "Jason";
char cValue = 'g';
cout << "Size of int: " << sizeof(unsigned int) << endl;
cout << "Size of short int: " << sizeof(short int) << endl;
Precision
#include <iomanip>
float fValue = 76.4;
cout << fixed << fValue << endl; // 76.400002
cout << scientific << fValue << endl; // 7.640000e+01
long double lValue = 123.456789876543210;
cout << setprecision(20) << fixed << lValue << endl; // 123.45678987654321190348
if else
if (iValue == 1) {
cout << "Adding new record..." << endl;
} else if (iValue == 10) {
cout << "Deleting record..." << endl;
} else {
cout << "Invalid option." << endl;
}
while
int i = 0;
while(i < 5) {
cout << "Hello " << i << endl;
i++;
}
do while
const string password = "hello";
string input;
do {
cout << "Enter your password > " << flush;
cin >> input;
if(input != password) {
cout << "Access denied." << endl;
}
} while (input != password);
for
for (int i = 0; i < 10; i++) {
cout << "Hello " << i << endl;
}
continue / break
for(int i=0; i<5; i++) {
cout << "i is: " << i << endl;
if (i == 1) { continue; } // continue & skip "Looping ..."
if (i == 3) { break; } // break for loop
cout << "Looping ..." << endl;
}
array
int values[3];
values[0] = 88;
values[1] = 123;
values[2] = 7;
int values[] = {4, 7, 3, 4};
int arr_len = sizeof(values)/sizeof(int);
for(unsigned int i=0; i < arr_len; i++) {
cout << values[i] << " " << flush;
}
multi-dim array
string animals[][3] = {
{ "fox", "dog", "cat" },
{ "mouse", "squirrel", "parrot" }
};
for(unsigned int i=0; i< sizeof(animals)/sizeof(animals[0]); i++) {
for(unsigned int j=0; j< sizeof(animals[0])/sizeof(string); j++) {
cout << animals[i][j] << " " << flush;
}
cout << endl;
}
switch
int value = 4;
switch (value) {
case 4:
cout << "Value is 4." << endl;
break;
case 5:
cout << "Value is 5." << endl;
break;
default:
cout << "Unrecognized value." << endl;
}
Last updated
Was this helpful?