Level:2 Medium

Welcome back,
This is the continuation of our Cpp Quick reference – From Novice to Expert.
Lets get inside Level 2
LEVEL : 2 | MEDIUM
26. C++ Switch Statement:
#include<iostream>
using namespace std;
int main()
{
char input='z';
switch(input){ //data type of switch input & case should be same
case 'A':{
cout<<'A'<<endl;
break;
}
case'B':{
cout<<'B'<<endl;
break;}
case 'C':{
cout<<'C'<<endl;
break;
}
default:
cout<<"default"<<endl;//if none of the cases matches,default'll be exectd
//no need of break in default case
}
return 0;
}
27. C++ Multiple Return Statements in Functions :
#include<iostream>
using namespace std;
bool check(int);
int main()
{
if(check(18))
cout<<"u r adult"<<endl;
else
cout<<"u r kid"<<endl;
return 0;
}
bool check(int age)
{
if(age>=18)
return true;//u can have many return statements in a pgm, but only one gets executed
else
return false;
}
28. Address operator in C++ _ & Operator :
#include<iostream>
using namespace std;
int main()
{
int age=20,weight=70;
cout<<"value: "<<age<<endl;
cout<<"address: "<<&age<<endl;//address of variable age stored in memory
cout<<"value: "<<weight<<endl;
cout<<"address: "<<&weight<<endl;//address of variable weight stored in memory
//NOTE:useful in pointer concepts
return 0;
}
29. Introduction to C++ Pointers :
#include<iostream>
using namespace std;
int main()
{
int age=20;
bool human=true;
int *ageptr; //syntax: datatype *ptr_name NOTE:datatype->which type of data is stored in d address
bool *humanptr;// here humanptr-> points to a variable human which contains a bool value
ageptr=&age;//initializing a pointer by giving the address of variable
humanptr=&human;//NOTE:no need to put * b4 d ptr_name
cout<<age<<"-->"<<ageptr<<endl;
cout<<human<<"-->"<<humanptr<<endl;//gives u d address
cout<<age<<"-->"<<*ageptr<<endl;
cout<<human<<"-->"<<*humanptr<<endl;// gives u d value stored
return 0;
}
//NOTE: pointers useful in DYNAMIC MEMORY ALLOCATION
30. Passing an Array to a Function in C++ :
#include<iostream>
using namespace std;
void show(int[],int);//ftn prototype
int main()
{
int arr[]={22,33,44,55,66};
int l=5;
show(arr,l);//call d ftn by passing an array to d ftn
return 0;
}
void show(int num[], int len){//array arr[] is passed 2 d ftn
int i;
for(i=0;i<len;i++)
cout<<num[i]<<endl;
}
31. Pass by Reference in C++ :
#include<iostream>
using namespace std;
void display(int *);//ftn prototype
int main()
{
int weight=50;
cout<<"value b4 chnged by ptr in pass_by_ref --> "<<weight<<endl;
display(&weight);
cout<<endl<<"value afte' chnged by ptr in pass_by_ref --> "<<weight<<endl;
return 0;
}
void display(int *ptr){
cout<<endl<<"pass by reference --> "<<*ptr<<endl;
/*pass by ref= passing a pointer 2 a ftn
NOTE:value changed using d ptr'll affect d actual value*/
*ptr=100;
}
32. Relationship between Arrays and Pointers in C++ :
#include<iostream>
using namespace std;
int main()
{
int arr[]={22,33,44,55,66};
cout<<arr[0]<<endl;//prints 1st element
cout<<*arr<<endl;//prints 1st element
cout<<arr[2]<<endl;//prints 3rd element
cout<<*(arr+2)<<endl;//prints 3rd element
//NOTE:array element can be accessed thru' ARRAY INDEX or *VALUE @
return 0;
}
33. Const Keyword with Functions and Arrays in C++ :
#include<iostream>
using namespace std;
/*const--> keep pgming elements constant i.e.,Variables,Pointers, array,ftn arguments,return values,class data members,member ftns,objects +protect array elements */
void display(const int[],int);
int main()
{
const float pi=3.14;//constant variable, cant be changed
NOTE:const variable should be initialized while declaring..!!!
cout<<"pi--> "<<pi<<endl;
//pi=2.1; //ERROR,u cant assign to a variable that is const
int number[]={22,33,44,55,66};
display(number,5);
return 0;
}
/*protect array elements*/
void display(const int arr[],int len){
int counter;
cout<<"array elements:"<<endl;
for(counter=0;counter<len;counter++){
cout<<arr[counter]<<endl;
}
//arr[counter]=99;//ERROR,u cant assign to a variable that is const
}
34. Array Ranges in Functions in C++ :
#include<iostream>
using namespace std;
void display(const int *,const int *);
int main()
{
int arr[]={11,22,33,44,55,66,77,88,99};
display(arr+3,arr+7);//calls array element from range (4-7)
return 0;
}
void display(const int *start,const int *end){
const int *ptr;
for(ptr=start;ptr!=end;ptr++){
cout<<*ptr<<endl;
}
}
35. Introduction to Structures in C++ :
/*arraysame data_type under one group; structuresdiff. data_type under one group*/
#include<iostream>
using namespace std;
struct student{ //structure name(GLOBAL SCOPE, can be accessed thru’out our pgm)
int rollno;//structure member,it can be a VARIABLE, another STRUCTURE or UNION
char sex;//structure member
}bamu,randomGuy;//structure variables(GLOBAL SCOPE)
NOTE:student is a user-defined data_type..!!!
int main()
{
student AuthorRS,ajju;//structure variables(LOCAL SCOPE)
AuthorRS.rollno=123;//assign value to structure variable member
ajju.rollno=456;
bamu.rollno=111;
randomGuy.rollno=222;
cout<<bamu.rollno<<endl<<randomGuy.rollno<<endl;
cout<<AuthorRS.rollno<<endl<<ajju.rollno<<endl;;
return 0;
}
36. Arrow Operator with Pointers to Access Structure Members :
#include<iostream>
using namespace std;
struct student{
int rollno;//structure member
char sex;
};
int main()
{
student AuthorRS;//structure variable
student *AuthorRSptr;//pointer
AuthorRSptr=&AuthorRS; //ptr pointing to the structure variable
AuthorRS.rollno=123;
AuthorRSptr->sex='m';//->ARROW OPERATOR,to access structMember through POINTER to the structVariable
cout<<AuthorRSptr->rollno<<endl;
cout<<AuthorRS.sex<<endl; //. DOT OPERATOR, to access structMember through structVariable
return 0;
}
37. Passing Structure to Functions by Value, Reference :
/*PASS BY VALUE & PASS BY REFERENCE*/
#include<iostream>
using namespace std;
struct student{
int rollno;
char sex;
};
void display(student );//ftn prototype MUST BE done after structure definition
void show(student *);
int main()
{
student AuthorRS;
AuthorRS.rollno=111;
AuthorRS.sex='M';
display(AuthorRS);//struc variable is passed->passing struc to ftn by value
show(&AuthorRS);//address of the struct.var is passed-> passing struc to ftn by ref
return 0;
}
/*pass by value- pass struc variable to a ftn*/
/*NOTE:changes DOES NOT affect d main ftn*/
void display(student s){
cout<<"pass by value"<<endl;
cout<<s.rollno<<endl<<s.sex<<endl;
}
/*pass by reference-pass struc var ADDRESS to a ftn*/
/*NOTE:changes affect d main ftn*/
void show(student *sptr){
cout<<"pass by ref"<<endl;
cout<<sptr->rollno<<endl<<sptr->sex<<endl;
}
38. Nested Structures and C++ Dot Operator :
#include<iostream>
#include<string>//header to use strings
using namespace std;
struct address{
int house_no;//members
string street_name;
};
struct student{
string name;//members
int roll_no;
address addr;//user-defined data_type 'address' variable ->'addr'
};
int main()
{
student AuthorRS;//struct variable
/*assigning value to the struc variables*/
AuthorRS.name="AuthorRS";
AuthorRS.roll_no=123;
AuthorRS.addr.house_no=18;//LOOK CLOSER 🙂
AuthorRS.addr.street_name="DummyPlace";
/*accessing values stored in the struc variable*/
cout<<AuthorRS.name<<endl;
cout<<AuthorRS.roll_no<<endl;
cout<<AuthorRS.addr.house_no<<endl;//LOOK CLOSER
cout<<AuthorRS.addr.street_name<<endl;
return 0;
}
39.a Accessing C++ Nested Structure Members using Arrow Operator :
#include<iostream>
#include<string>
using namespace std;
struct address{
int house_no;
string street;
};
struct student{
string name;
int roll_no;
address addr;//nested structure
};
int main()
{
student AuthorRS;//structure variable
student *AuthorRSptr;//structure pointer
AuthorRSptr=&AuthorRS;//ptr pointing to variable
/*assigning value to variables*/
AuthorRSptr->name="AuthorRS";
AuthorRSptr->roll_no=123;
AuthorRSptr->addr.house_no=18;//AuthorRSptr is a POINTER, so ->ARROW OP addr is a variable, so . DOT OP
AuthorRSptr->addr.street="DummyPlace";
/*accessing d variables*/
cout<<AuthorRSptr->name<<endl;
cout<<AuthorRSptr->roll_no<<endl;
cout<<AuthorRSptr->addr.house_no<<endl;//LOOK CLOSER
cout<<AuthorRSptr->addr.street<<endl;
return 0;
}
39.b Accessing C++ Nested Structure Members using Arrow Operator :
It can be done by alternate way-as follow (ACCESSING WITH POINTERS):
#include<iostream>
#include<string>
using namespace std;
struct address{
int house_no;
string street;
};
struct student{
string name;
int roll_no;
address *addr;//addr is a POINTER
};
int main()
{
student AuthorRS;//structure variable
student *AuthorRSptr;//structure pointer
AuthorRSptr=&AuthorRS;//ptr pointing to variable
/*assigning value to variables*/
AuthorRSptr->name="AuthorRS";
AuthorRSptr->roll_no=123;
/*ATTENTION PLS*/
address assign_addr={18,"kk nagar"};//to assign value to the pointer addr
AuthorRSptr->addr=&assign_addr;//!!! LOOK CLOSER !!!
/*accessing d variables*/
cout<<AuthorRSptr->name<<endl;
cout<<AuthorRSptr->roll_no<<endl;
cout<<AuthorRSptr->addr->house_no<<endl;//LOOK CLOSER
cout<<AuthorRSptr->addr->street<<endl;
return 0;
}
39.c Accessing C++ Nested Structure Members using Arrow Operator :
Yet another alternate way
#include<iostream>
#include<string>
using namespace std;
struct address{
int house_no;
string street;
};
struct student{
string name;
int roll_no;
address *addr;//pointer
};
int main()
{
student rs;//variable
address assign_ad={18,"kk nagar"};//to assign value to the pointer addr
rs.addr=&assign_ad;//ptr points to the variable
cout<<rs.addr->house_no<<endl;
cout<<rs.addr->street<<endl;
return 0;
}
40. C++ Sizeof Operator with Variables, Data types, Structures, Unions :
#include<iostream>
using namespace std;
/*sizeof is compiler operator*/
struct student{
int roll_no;
char gender;
};//see also:compiler optimization
int main()
{
char sex='M';
cout<<"int -->"<<sizeof(int)<<endl;//data_type
cout<<"short int -->"<<sizeof(short int)<<endl;//data_type
cout<<"variable -->"<<sizeof(sex)<<endl;//variable
cout<<"structure -->"<<sizeof(student)<<endl;//structure
return 0;
}
41. Introduction to Unions in C++ :
#include <iostream>
using namespace std;
union emp{
int id;
float salary; //both id and salary share same memory
}rs,bamu; //variables can be created here
/*note: only 4 byte is reserved for this union and both the members share the same block*/
int main()
{
emp AuthorRS; //var can be created here also
AuthorRS.id=891401;
cout << AuthorRS.id<< endl;
return 0;
}
42. New and Delete Operators in C++ _ Dynamic Memory Allocation :
#include <iostream>
using namespace std;
int main()
{
int *pointer; //to return the address of memory allocated
/*syntax: ptr=new datatype*/
pointer=new int;
*pointer=123;
cout<<*pointer<<endl;
delete pointer; //deallocate memory
return 0;
}
43. Dynamically Allocating Arrays Depending on User Input in C++ :
#include <iostream>
using namespace std;
int main()
{
int *pointer=NULL; //pointer points to null
int input,temp,counter;
cout<<"enter how many elements: ";
cin>>input;
pointer=new int[input];//dyn.mem.alloc
for(counter=0;counter<input;counter++){
cout<<"enter element "<<counter+1<<endl;
cin>>temp;
*(pointer+counter)=temp;
}
cout<<"elements are: "<<endl;
for(counter=0;counter<input;counter++){
cout<<"element "<<counter+1<<"-> "<<*(pointer+counter)<<endl;
}
delete []pointer;//dealloc mem
return 0;
}
44. Avoiding Dangling Pointer Reference in C++ :
#include <iostream>
using namespace std;
int main()
{
int *pointer=nullptr; //c++11 feature(nullptr)
pointer=new int; //dyn mem alloc
if(pointer!=nullptr){
*pointer=10;
cout<<*pointer<<endl;
delete pointer;//deallocates mem
pointer=nullptr;//avoid dangling pointer
}else{
cout<<"memory not allocated"<<endl;
}
return 0;
}
45.a Automatic Type Deduction C++11 Feature :
#include <iostream>
using namespace std;
int main()
{
/*note:initialise immediatly MUST!!!*/
auto qty=10;/*compiler automatically deduce
the datatype ,by looking at the initialiser*/
cout<<qty<<endl;
return 0;
}
45.b Automatic Type Deduction C++11 Feature :
#include <iostream>
using namespace std;
int sum(){ //function can be anything,with or without arg
int i,j,res;
i=10,j=5;
res=i+j;
return res;//ftn can return any datatype
}
int main()
{
/*note:initialise immediatly MUST!!!*/
auto qty=sum();/*compiler automatically deduce
the datatype ,by looking at the RETURN TYPE OF THE FUNCTION sum()*/
cout<<qty<<endl;
return 0;
}
–Error if not initialized
#include <iostream>
using namespace std;
int main()
{
/*note:initialise immediatly MUST!!!*/
auto qty;//ERROR
qty=10;//ERROR it should be iniatialised, where it is declared
cout<<qty;
return 0;
}
46.a For Each Loop _ Range Based For Loop C++ 11 feature :
#include <iostream>
using namespace std;
int main()
{
int marks[]={77,88,99,55,66};
for(int ele:marks)//syntax: for(variable:collection) /*but throws ERROR bcoz C++ 11 feature !!!*/
{cout<<ele<<endl;}
return 0;
}
46.b For Each Loop _ Range Based For Loop C++ 11 feature :
alternate way
#include <iostream>
using namespace std;
int main()
{
for(int ele:{77,88,99,55,66}) //we can directly pass range
{cout<<ele<<endl;}
return 0;
}
47. Introduction to Strings in C++ :
#include <iostream>
#include <string>
using namespace std;
int main()
{
//string copy
string name="AuthorRS"; //strcpy string copy of c
string lastname="rs";
cout<<name<<" "<<lastname<<endl;
//string concatenate
cout<<name+lastname<<endl;//strcat of c
//string compare
if(name=="AuthorRS")//strcmp of c
cout<<"name matched"<<endl;
return 0;
}
48. Recursive Function and Recursion in C++ :
#include <iostream>
using namespace std;
int factorial(int n){
if(n==1)
return 1;
else
return n*factorial(n-1);//recursive ftn
}
int main()
{
cout<<factorial(3)<<endl; //3*2*1=6
return 0;
}
49. Function Overloading (COMPILE TIME POLYMORPHISM) in C++ :
#include <iostream>
#include <string>
using namespace std;
void display();
void display(string);//overloaded ftn
/*same ftn_name,return type BUT diff set of parameters*/
/*NOTE: diff return types doesnt mean ftn overloading!!!*/
int main()
{
display();
display("AuthorRS");
return 0;
}
void display(){
cout<<"hi..."<<endl;
}
void display(string name){
cout<<"hi "<<name<<endl;
}
So,..we have reached the end of this level. In our next level we will dive deeper..Please do read the complete series of this blog to reach the Level from Novice to Expert.
If you find any error in SourceCode please let me know in the Comments. Corrections and Improvement Suggestions are highly appreciated. Thanks in advance..
love,
<R.S>
For Complete Sourcecode visit my Github Repo: Link provided in the final module
RS-codes

2 thoughts on “CPP QuickReference – From Novice to Expert- Level2”