L2_Intro_to_OOP
L2_Intro_to_OOP
Lecture 2
Basic structure of C++
▪ C++ program has following sections in its basic structure,
▪ Directives/libraries inclusion section
▪ Main function section
▪ Function body section
▪ Directives inclusion section allows to include the required libraries for the
program.
▪ Main function section defines the sequence of code that has to be executed.
▪ Function body section defines the functionality of the functions. It has
declaration and executable statements.
Basic structure of C++
#include <directives> Directives inclusion section
}
Basic structure of C++
#include <directives> It includes the directives/libraries mentioned in angle brackets
int main()
{
Declaration statements
Executable statements
return 0;
}
Basic structure of C++
#include <directives>
This statement informs compiler to use std namespace in which the
using namespace std;
standard C++ libraries are declared.
int main()
{
Declaration statements
Executable statements
return 0;
}
Basic structure of C++
#include <directives>
int main()
Main function definition part.
{
Declaration statements
Executable statements
return 0;
}
Basic Input/Output in C++
The following are operations used for input and output in C++,
int main()
{
cout << "Hello World";
return 0;
}
C++ program to add two
numbers
#include <iostream>
using namespace std;
int main() {
cout << first_number << " + " << second_number << " = " << sum;
return 0;
}
#include <iostream>
using namespace std;
int main() {
else
cout << "Largest number: " << n3;
return 0;
}
WAP in C++ to find the sum of its elements in
an array
#include <iostream.h>
using namespace std
int sum(int arr[], int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
int main()
{
int arr[] = { 12, 3, 4, 15 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Sum of given array is %d", sum(arr, n));
return 0;
}
Basic C++ MCQs
1. Which of the following user-defined
header file extension used in c++? Answer1 : C
a) hg
b) cpp
c) h
d) hf
return 0;
}
References
▪Herbert Schildt, “C++: The complete reference”, Mc Graw Hill Osborne media, 4 th
edition, 2017
▪Robert Lafore, “Object oriented programming in C++”, SAMS, 4 th edition, 2002