Programs Using FUNCTIONS
1. Function to find factorial
#include <iostream>
using namespace std;
int factorial(int n) {
int fact = 1;
for(int i = 1; i <= n; i++)
fact *= i;
return fact;
}
int main() {
int num;
cout << "Enter number: ";
cin >> num;
cout << "Factorial = " << factorial(num);
return 0;
}
Logic: Multiply numbers from 1 to n.
2. Function to check prime number
#include <iostream>
using namespace std;
bool isPrime(int n) {
if(n <= 1) return false;
for(int i = 2; i <= n/2; i++) {
if(n % i == 0)
return false;
}
return true;
}
int main() {
int num;
cin >> num;
if(isPrime(num))
cout << "Prime";
else
cout << "Not Prime";
return 0;
}
Logic: Check divisibility.
3. Function to swap two numbers (pass by value)
#include <iostream>
using namespace std;
void swapVal(int a, int b) {
int temp = a;
a = b;
b = temp;
cout << "Inside function: " << a << " " << b << endl;
}
int main() {
int x = 5, y = 10;
swapVal(x, y);
cout << "Outside function: " << x << " " << y;
return 0;
}
Note: Values do NOT change outside.
4. Function using pass by reference
#include <iostream>
using namespace std;
void swapRef(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swapRef(x, y);
cout << "After swap: " << x << " " << y;
return 0;
}
Logic: Reference allows actual change.
5. Function to find largest of three numbers
#include <iostream>
using namespace std;
int largest(int a, int b, int c) {
if(a >= b && a >= c)
return a;
else if(b >= c)
return b;
else
return c;
}
int main() {
int x, y, z;
cin >> x >> y >> z;
cout << "Largest = " << largest(x, y, z);
return 0;
}
Logic: Compare values.
Programs Using POINTERS
1. Basic pointer example
#include <iostream>
using namespace std;
int main() {
int x = 10;
int *ptr = &x;
cout << "Value of x: " << x << endl;
cout << "Address of x: " << &x << endl;
cout << "Pointer value: " << ptr << endl;
cout << "Value using pointer: " << *ptr;
return 0;
}
Concept: *ptr dereferences value.
2. Swap using pointers
#include <iostream>
using namespace std;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
swap(&x, &y);
cout << x << " " << y;
return 0;
}
Logic: Pass address.
3. Pointer with array
#include <iostream>
using namespace std;
int main() {
int arr[5] = {1,2,3,4,5};
int *ptr = arr;
for(int i = 0; i < 5; i++) {
cout << *(ptr + i) << " ";
}
return 0;
}
Concept: Pointer arithmetic.
4. Sum of array using pointer
#include <iostream>
using namespace std;
int main() {
int arr[5] = {1,2,3,4,5};
int *ptr = arr;
int sum = 0;
for(int i = 0; i < 5; i++) {
sum += *(ptr + i);
}
cout << "Sum = " << sum;
return 0;
}
Logic: Traverse using pointer.
5. Pointer to function
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int (*funcPtr)(int, int);
funcPtr = add;
cout << "Result = " << funcPtr(5, 3);
return 0;
}
Concept: Function pointer call.