Jul 18, 2024
Basics
Core Concepts
Intermediate Concepts
Text Editor
C++ Compiler
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
``
string characterName;
int characterAge;
cin
for basic data types
int age;
cout << "Enter your age: ";
cin >> age;
getline
for strings
string fullName;
cout << "Enter your full name: ";
getline(cin, fullName);
int num1, num2, sum;
cout << "Enter num1: ";
cin >> num1;
cout << "Enter num2: ";
cin >> num2;
sum = num1 + num2;
cout << "Sum is: " << sum << endl;
if (condition)
// code to execute
else
// alternate code
switch(expression) {
case x: // code
break;
default: // code
}
while (condition)
// code
for (int i = 0; i < n; i++)
// code
do {
// code
} while(condition);
returnType functionName(parameters) {
// code
}
int power(int baseNum, int powNum) {
int result = 1;
for (int i = 0; i < powNum; i++)
result *= baseNum;
return result;
}
int numbers[5] = {1, 2, 3, 4, 5};
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 5; i++)
cout << numbers[i] << endl;
int age = 30;
int *pAge = &age;
cout << *pAge << endl; // Outputs 30
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
class Book {
public:
string title;
string author;
int pages;
};
Book book1;
book1.title = "1984";
book1.author = "George Orwell";
book1.pages = 328;
class Book {
public:
string title;
string author;
int pages;
Book(string aTitle, string anAuthor, int aPages) {
title = aTitle;
author = anAuthor;
pages = aPages;
}
};
Book book1("1984", "George Orwell", 328);
class Student {
public:
string name;
double gpa;
// Constructor
Student(string aName, double aGPA) {
name = aName;
gpa = aGPA;
}
// Object function
bool hasHonors() {
if (gpa >= 3.5)
return true;
return false;
}
};
Student student1("Mike", 3.7);
cout << student1.hasHonors() << endl; // Outputs 1 (true)
class Movie {
private:
string rating;
public:
string title;
string director;
// Setter
void setRating(string aRating) {
if(aRating == "G" || aRating == "PG" || aRating == "PG-13" || aRating == "R")
rating = aRating;
else
rating = "NR";
}
// Getter
string getRating() {
return rating;
}
};
Movie avengers;
avengers.setRating("PG-13");
cout << avengers.getRating(); // Outputs: PG-13
class Chef {
public:
void makeChicken() {
cout << "The chef makes chicken" << endl;
}
void makeSalad() {
cout << "The chef makes salad" << endl;
}
};
class ItalianChef : public Chef {
public:
void makePasta() {
cout << "The chef makes pasta" << endl;
}
};
ItalianChef ic;
ic.makeChicken(); // Outputs: The chef makes chicken
ic.makePasta(); // Outputs: The chef makes pasta
// This is a single-line comment
cout << "Hello"; // Inline comment
/*
This is a multi-line comment
Comments are useful for understanding code
*/