0% found this document useful (0 votes)
4 views

Functions Program Chap6

Uploaded by

sajidawajidf27
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Functions Program Chap6

Uploaded by

sajidawajidf27
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

 Functions Program Chap-6

1. Hello World:

#include <iostream>

using namespace std;

void helloWorld() {

cout << "Hello, World!" << endl;

int main() {

helloWorld();

return 0;

2. Addition Function:

#include <iostream>

using namespace std;

int add(int a, int b) {

return a + b;

int main() {

int result = add(5, 7);

cout << "Sum: " << result << endl;


return 0;

3. Factorial Calculation:

#include <iostream>

using namespace std;

int factorial(int n) {

if (n == 0 || n == 1)

return 1;

else

return n * factorial(n - 1);

int main() {

int num = 5;

cout << "Factorial of " << num << ": " << factorial(num) << endl;

return 0;

4. Sum of Two Numbers:

#include <iostream>

// Function to calculate the sum of two numbers

int add(int a, int b) {

return a + b;
}

int main() {

int num1 = 5, num2 = 7;

int result = add(num1, num2);

std::cout << "Sum of " << num1 << " and " << num2 << " is: " << result <<
std::endl;

return 0;
}

5. Sum of Array Elements:


#include <iostream>

int sumArray(const int arr[], int size) {

int sum = 0;

for (int i = 0; i < size; ++i) {

sum += arr[i];

return sum;

int main() {

const int size = 5;


int arr[size] = {1, 2, 3, 4, 5};

std::cout << "Sum of array elements: " << sumArray(arr, size) << std::endl;

return 0;

6. String Reversal:
#include <iostream>

#include <string>

std::string reverseString(const std::string& str) {

std::string reversed;

for (int i = str.length() - 1; i >= 0; --i) {

reversed += str[i];

return reversed;

int main() {

std::string input;

std::cout << "Enter a string to reverse: ";

std::cin >> input;

std::cout << "Reversed string: " << reverseString(input) << std::endl;


return 0;

You might also like