You are on page 1of 6

Ministry of Higher Education and Scientific Research

Al- Esraa University College


Dep. of Computer Engineering

Lecture 10

MSc. Abeer Mohammed

2022/2021
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2 nd Stage Al- Esraa University Collage

Function
Ex 10: Write C++ Program to Find Average of N Numbers Using
Functions?

#include<iostream>
using namespace std;
double average(double n1[], int size)
{
double sum = 0;
for (int i = 0; i < size; ++i)
{
sum += n1[i];
}
return sum / size;
}
int main()
{
int size;
double avg;
cout << "Enter size of array: ";
cin >> size;
double arr[5];
cout << "Enter array elements: ";
for (int i = 0; i < size; ++i)
{
cin >> arr[i];
}

2
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2 nd Stage Al- Esraa University Collage

avg = average(arr, size);


cout << "Average = " << avg << endl;
return 0;
}

Ex 11: C++ program to check prime number using function ?

#include<iostream>

using namespace std;

void isPrime(int n)

bool isPrime = true;

for (int i = 2; i <= n / 2; i++)

if (n % i == 0)

isPrime = false;

break;

if (isPrime)

3
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2 nd Stage Al- Esraa University Collage

cout << "This is a prime number";

else

cout << "This is not a prime number";

int main()

int n;

cout << "\n Enter any no : ";

cin >> n;

isPrime(n);

return 0;

Ex 12: C++ program for swapping between two string using


functions?

#include <iostream>
#include <string>
using namespace std;
int main() {
string str1;
string str2;

4
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2 nd Stage Al- Esraa University Collage

cout << "Enter first string" << endl;


cin >> str1;
cout << "Enter second string" << endl;
cin >> str2;
cout << "SWAP BETWEEN STRING" << endl;
str1.swap(str2);
cout << str1 << "\n";
cout << str2 << "\n";
return 0;
}

Ex 13: C++ program to find area of the circle using function?

#include <iostream>
using namespace std;

5
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2 nd Stage Al- Esraa University Collage

float area(float radius_circle);


int main() {
float radius;
cout << "Enter the radius of circle: ";
cin >> radius;
cout << "Area of circle: " << area(radius) << endl;
return 0;
}
float area(float radius_circle)
{
float area_circle;
area_circle = 3.14 * radius_circle * radius_circle;
return area_circle;
}

You might also like