// Arithmeticintsum=1+2;// Additionintdiff=5-3;// Subtractionintprod=2*3;// Multiplicationdoublequot=10/2;// Divisionintmod=10%3;// Modulus// Assignmentintx=10;x+=5;// x = x + 5x-=3;// x = x - 3x*=2;// x = x * 2x/=2;// x = x / 2// ComparisonboolisEqual=(1==1);// trueboolisNotEqual=(1!=2);// trueboolisGreater=(5>3);// trueboolisLesser=(3<5);// true
Control Structures
// Conditional Statementsif(a>b){// code if true}elseif(a==b){// code if equal}else{// code if false}// Switch Statementswitch(a){case1:// code for case 1break;case2:// code for case 2break;default:// default code}// Loops// For Loopfor(inti=0;i<5;i++){// code}// While Loopwhile(a<10){// codea++;}// Do-While Loopdo{// codea++;}while(a<10);
Functions
// Function Definitionintadd(intx,inty){returnx+y;}// Function Callintresult=add(2,3);
Arrays
intarr[3]={1,2,3};// Access ElementsintfirstElement=arr[0];// Loop through Arrayfor(inti=0;i<3;i++){cout<<arr[i]<<endl;}
Vectors (STL)
#include<vector>#include<iostream>usingnamespacestd;vector<int>vec={1,2,3};// Access ElementsintfirstElement=vec[0];// Add Elementsvec.push_back(4);// Remove Elementsvec.pop_back();// Loop through Vectorfor(inti=0;i<vec.size();i++){cout<<vec[i]<<endl;}
#include<fstream>#include<iostream>usingnamespacestd;// Write to FileofstreamoutFile("file.txt");outFile<<"Hello, World!"<<endl;outFile.close();// Read from FileifstreaminFile("file.txt");stringcontent;getline(inFile,content);inFile.close();
Classes
// Class DefinitionclassPerson{public:stringname;intage;Person(stringn,inta){name=n;age=a;}voidgreet(){cout<<"Hello, "<<name<<"!"<<endl;}};// InheritanceclassStudent:publicPerson{public:stringgrade;Student(stringn,inta,stringg):Person(n,a){grade=g;}voidstudy(){cout<<name<<" is studying."<<endl;}};// Create ObjectStudentstudent("John",20,"A");student.greet();student.study();
Exception Handling
try{// code that might throw an exceptionif(b==0){throwruntime_error("Cannot divide by zero");}intresult=a/b;}catch(construntime_error&e){// code that runs if exception occurscout<<"Error: "<<e.what()<<endl;}catch(...){// code that runs for any other exceptioncout<<"An unknown error occurred."<<endl;}
Templates
// Function Templatetemplate<typenameT>Tadd(Tx,Ty){returnx+y;}intresultInt=add<int>(2,3);// 5doubleresultDouble=add<double>(2.5,3.5);// 6.0// Class Templatetemplate<typenameT>classBox{public:Tvalue;Box(Tv):value(v){}TgetValue(){returnvalue;}};Box<int>intBox(123);Box<string>strBox("Hello");