0% found this document useful (0 votes)
9 views72 pages

CPP Book

The document contains multiple C++ programming tasks that cover various concepts such as functions, recursion, linear and binary search, and array manipulation. It includes examples of programs for adding and subtracting numbers, checking for prime numbers, calculating fractions, summing ranges, and searching through arrays. Additionally, it discusses call by value vs call by reference, and provides implementations for counting zeros in an integer and checking for palindromes.

Uploaded by

farhafouadd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views72 pages

CPP Book

The document contains multiple C++ programming tasks that cover various concepts such as functions, recursion, linear and binary search, and array manipulation. It includes examples of programs for adding and subtracting numbers, checking for prime numbers, calculating fractions, summing ranges, and searching through arrays. Additionally, it discusses call by value vs call by reference, and provides implementations for counting zeros in an integer and checking for palindromes.

Uploaded by

farhafouadd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

CPP

Function
1. Write a program that reads two integer numbers
from a user and call a function to add these two
numbers and call another function to sub these
numbers using local and global variables.
int sum (int x, int y)
{

return x+y;

}
int diff (int x, int y)
{

return x-y;

}
int main ()
{
int x,y;
cin >> x>>y;
cout << diff(x,y)<<" "<< sum(x,y);
}
\\
int x,y;
int sum ()
{

return x+y;

}
int diff ()
{

return x-y;

}
int main ()
{

cin >> x>>y;


cout << diff()<<" "<< sum();
}

2. Write a program to read a positive number and


then test the number is prime or not using function.

#include <iostream>
using namespace std;

// Function to check if a number is prime


int isPrime(int n) {
if (n < 2) return 0; // Numbers less than 2 are not
prime

for (int i = 2; i * i <= n; i++) {


if (n % i == 0)
return 0; // Not prime
}
return 1; // Prime
}

int main() {
int num;

cout << "Enter a positive number: ";


cin >> num;

if (num <= 0) {
cout << "Invalid input! Please enter a positive
number.\n";
return 0; // Exit program if the input is invalid
}

// Check and display result using normal function


if (isPrime(num) == 1)
cout << num << " is a prime number.\n";
else
cout << num << " is not a prime number.\n";

return 0;
}

3. Write a program to calculate the result of the


following equation using two functions only
((3+4+5+6)/(9*11*13*15)-(7*10*13*…*19)/(10+15+20+
…+40))

#include <iostream>
using namespace std;
double firstFraction( )
{
double sum=0,product=1 ; int x ;
​ for(x = 3 ; x <= 6 ; x++)
​ {​ sum += x ;​ }
​ ​ for(x = 9 ; x <= 15 ; x+=2)
​ {​ product*= x ;​}
​ return sum/product;
}
double secondFraction( )
{
double sum=0,product=1 ; int x ;
​ for(x = 7 ; x <= 19 ; x+=3)
​ {product*= x ;​}
​ ​ for(x = 10 ; x <= 40 ; x+=5)
​ {​ sum += x ;​ }
​ return product / sum ;
}
int main ()
{
cout << firstFraction( ) - secondFraction( );
}

4. Write a program to add numbers from A to B


using function, note: user will enter values of A and
B.

int sumrangge( int A,int B)


{ int x;
int sum=0;
for (x=A;x<=B;x++)
sum+=x;
return sum;
}

int main ()
{int A,B;
cin >> A>>B;
cout << sumrangge( A, B) ;
}

passing an array to functions for setting values in the array


and then printing those values

#include <iostream>
using namespace std;

void set(int arr[], int s)


{
for (size_t i = 0; i < s; i++)
{
cout << "Enter array value: ";
cin >> arr[i];
}
}

void print(int arr[], int s)


{
for (size_t i = 0; i < s; i++)
{
cout << arr[i] << " ";
}
}

int main()
{
int a[5];
set(a, 5);
print(a, 5);

return 0;
}

Call By Reference vs Call By Value

#include <iostream>
using namespace std;

void swap(int x, int y)


{
int z = x;
x = y;
y = z;
}

int main()
{
int x = 10, y = 20;
swap(x, y);
cout << "x= " << x << " y= " << y << endl;
return 0;
}

//x= 10 y= 20 Output

///

#include <iostream>

using namespace std;

void swap(int&x, int&y)

int z = x;

x = y;

y = z;

int main()

{
int x = 10, y = 20;

swap(x, y);

cout << "x= " << x << " y= " << y << endl;

return 0;

//x= 20 y= 10 output

As you can see, the result of calling the swap() function is different depending on

whether it is called by value or by reference.

………………………………………………………………….

Write a program to add +1,+2 to two integer using function

#include <iostream>

using namespace std;

void fun(int&x, int&y)


{

x += 1;

y += 2;

int main()

int k = 50, r = 10;

fun(k, r);

cout << "K= " << k << " R= " << r << endl;

return 0;

//K= 51 R= 12
LINEAR SEARCH
Write a program to fill an array with size 20 by positive random.
numbers between 5 and 100.Then read a key number from the
user and search for this key number using linear search.

✅ Generates an array of 20 random numbers between 5 and


✅ Allows the user to input a key number
100

✅ Searches for the key using linear search


#include <iostream>
#include <ctime>
using namespace std;
void fillarray (int arr[], int size)
{
srand (time(0));
for (int i=0;i<=size; i++)
arr[i]=5+rand()%(100-5+1);
}
void disarray (int arr[], int size)
{

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


cout<<arr[i];
}
int linearsearch (int arr[], int size, int key)
{
for (int i=0; i<=size;i++)
if (arr[i]==key) return i;
return -1;
}

int main ()
{
int size=20;
int arr[size];
int key;
fillarray(arr,size);
disarray(arr,size);
cin>> key;
linearsearch (arr,size,key);
if (linearsearch (arr,size,key) != -1) {
cout << "Number " << key << " found at index " <<
linearsearch (arr,size,key)<< endl;
} else {
cout << "Number " << key << " not found in the array." << endl;
}
}
b. Write a function to fill an array with random numbers.
Write another function to search for a number in array
using linear search.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

// Function to fill the array with random numbers


void fillArray(int arr[], int size, int minVal, int maxVal) {
srand(time(0)); // Seed random generator
for (int i = 0; i < size; i++) {
arr[i] = minVal + rand() % (maxVal - minVal + 1);
}
}

// Function to perform linear search


int linearSearch(int arr[], int size, int key) {
for (int i = 0; i < size; i++) {
if (arr[i] == key)
return i; // Return index if found
}
return -1; // Not found
}

// Function to display array


void displayArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
const int size = 20;
int arr[size];
int key;

// Fill the array with random numbers between 5 and 100


fillArray(arr, size, 5, 100);

// Display the generated array


cout << "Generated array: ";
displayArray(arr, size);

// Read the key to search


cout << "Enter a number to search: ";
cin >> key;

// Search for the key in the array


int result = linearSearch(arr, size, key);

// Display the result


if (result != -1) {
cout << "Number " << key << " found at index " << result <<
endl;
} else {
cout << "Number " << key << " not found in the array." << endl;
}

return 0;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
#include<iostream>
using namespace std;

int linearSearch(int arr[], int n, int key)


{
​ for (int i = 0; i < n; i++)
​ {
​ ​ if (arr[i] == key)
​ ​ ​ return i;
​ }
​ return-1;
}

int main()
{
​ int arr[] = { 90,10,40,70,5 };
​ int n = sizeof(arr) / sizeof(arr[0]);//5*4=20 => 20/4 =>5

​ int num;
​ cout << "Enter an Integer :";
​ cin >> num;

​ int result = linearSearch(arr,n,num);


​ if (result == -1)
​ ​ cout << "The Number : (" << num << ") Was Not Found."
<< endl;
​ else
​ ​ cout << "The Number : (" << arr[result] << ") Was Found
At Index : (" <<result<<")"<< endl;

​ return 0;
}

Binary Search
#include<iostream>
using namespace std;
int binarySearch(int arr[], int l, int h, int element)
{
​ while (l <= h) {
​ ​
​ ​ int m = (l + h) / 2;

​ ​
​ ​ if (arr[m] == element)
​ ​ ​ return m;

​ ​ if (arr[m] > element)


​ ​ ​
​ ​ h = m - 1;

​ ​ else

​ ​ l = m + 1;

​ }

​ return -1;
}

/*
int binarySearchRec(int arr[], int l, int h, int element)
{
​ if (h >= l) {
​ ​ int mid = (l + h) / 2;

​ ​ if (arr[mid] == element)
​ ​ ​ return mid;

​ ​ if (arr[mid] > element)


​ ​ ​ return binarySearch(arr, l, mid - 1, element);

​ ​ return binarySearch(arr, mid + 1, h, element);


​ }
​ return -1;
}
*/

int main()
{
​ int arr[] = { 2, 3, 4, 10, 40 };
​ int n = sizeof(arr) / sizeof(arr[0]);

​ int num;
​ cout << "Enter an Integer :";
​ cin >> num;

​ int result = binarySearch(arr, 0, n - 1, num);


​ if(result == -1)
​ ​ cout << "The Number : (" << num << ") Was Not Found." << endl;
​ else
​ ​ cout << "The Number : (" << arr[result] << ") Was Found At Index
: (" << result << ")" << endl;

​ return 0;
}

a- You are working as a software developer for a library


management system. The library stores all its books by their
ISBN numbers, which are unique identifiers for each book.
These ISBN numbers are stored in ascending order in an array.
Your task is to write a C++ program that uses binary search to
find the index of a book given its ISBN number. If the ISBN is
not found, return -1. Example Input: ISBNs = [1001, 1010, 1050,
1100, 1200, 1305, 1500], target = 1100 Output: 3.

Recursive
function calculates the sum of the first n natural numbers.

#include <iostream>
using namespace std;
int sum(int n)
{
if (n == 1)
return 1;
else
return n + sum(n - 1);
}

int main()
{
cout << sum(5) << endl;
return 0;
}

takes two integer parameters, x and y, which represent the range of

numbers to sum.

#include <iostream>

using namespace std;


int sum(int x, int y)

if (x == y)

return x;

else

return y + sum(x, y - 1);

int main()

cout << sum(4, 6) << endl;

return 0;

—--------------------------------------------

*****
****

***

**

#include <iostream>

using namespace std;

void f(int n)

if (n < 0)

return;

else

for (size_t i = 0; i < n; i++)

{
cout << "*";

cout << endl;

f(n - 1);

int main()

f(5);

return 0;

}
recursive function that calculates the factorial of a

number

#include <iostream>

using namespace std;

int fact(int n)

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

return 1;

else

return n*fact(n - 1);

int main()

{
cout << fact(5) << endl;

return 0;

Using loops

int main(void)

int n, k, factorial;

cout << "Please enter value of n: ";

cin >> n;

factorial = 1;

for (k = n; k >= 1; k--)

factorial = factorial * k;

}
cout << "Factorial " << n << " = " << factorial << "\n";

return 0;

B. Write a program to count and print the number

of zeros

in an integer number which will be entered by the

user

using a recursive function.

#include <iostream>

using namespace std;

int countZeros(int n) {
if (n == 0) return 1; // Base case for input 0

if (n < 10) return 0; // Base case: single nonzero digit

return (n % 10 == 0) + countZeros(n / 10);

int main() {

int num;

cout << "Enter an integer number: ";

cin >> num;

int zeroCount = (num == 0) ? 1 : countZeros(num);

cout << "Number of zeros: " << zeroCount << endl;


return 0;

D. Implement binary search using recursion.

Make sure your

function correctly handles cases where the target

value

does not exist in the array.

#include <iostream>

using namespace std;

int binarySearch(int arr[], int l, int h, int element) {


if (l > h)

return -1; // Base case: element not found

int m = (l + h) / 2;

if (arr[m] == element)

return m; // Element found at index m

if (arr[m] > element)

return binarySearch(arr, l, m - 1, element); // Search in the left half

return binarySearch(arr, m + 1, h, element); // Search in the right half

int main() {
int arr[] = {2, 3, 4, 10, 40};

int n = sizeof(arr) / sizeof(arr[0]);

int num;

cout << "Enter an integer: ";

cin >> num;

int result = binarySearch(arr, 0, n - 1, num);

if (result == -1)

cout << "The number (" << num << ") was not found." << endl;

else

cout << "The number (" << arr[result] << ") was found at index (" <<

result << ")." << endl;

return 0;
}

C. Check Palindrome: Create a recursive function to

check if

a string is a palindrome. Test your function with both

palindromic and non-palindromic strings. Example :

level : Palindrome

madam: Palindrome

cat: not palindrome

interesting : not palindrome.

Palindrome : not palindrome

#include <iostream>

#include <string>
using namespace std;

// Recursive function to check if a string is a palindrome

bool isPalindrome(string str, int start, int end) {

// Base case: If the start index is greater or equal to end, it's a

palindrome

if (start >= end)

return true;

// If characters at start and end don't match, it's not a palindrome

if (str[start] != str[end])

return false;

// Recursive case: Move inward

return isPalindrome(str, start + 1, end - 1);


}

int main() {

string str;

cout << "Enter a string: ";

cin >> str;

// Check if the string is a palindrome

if (isPalindrome(str, 0, str.length() - 1))

cout << str << " : Palindrome" << endl;

else

cout << str << " : Not Palindrome" << endl;

return 0;

}
Write a program to solve Hanoii tower

problem for n plates

void Hanoii(char x , char y , char z , int n)

​ if(n > 1)​ ​ ​ Hanoii(x,z,y,n-1);

​ cout << x << " ----> " << z << "\n";

​ if(n > 1)​ ​ ​ Hanoii(y,x,z,n-1);

void main(void)

{
​ int n ;

​ cout << " n = ";

​ cin >> n ;

​ Hanoii('A','B','C',n);

​ getch();

}
Pointer
A) Write a program to read ten numbers from a

user and store them

in array called (a) then call a function to

calculate the square of

each number.

● By calling function 10 times.

● By calling function only one time using

global variable.

● By calling function only one time using

pointer.

3- #include <iostream>
using namespace std;

void square (int arr[])

int i;

int *ptr;

ptr=arr;

for (i=0;i<=9;i++)

*(ptr+i)= *(ptr+i) * *(ptr+i);

int main ()

int arr[10];
int i;

for (i=0;i<=9; i++)

cin >> arr[i];

for (i=0;i<=9; i++)

cout<< arr[i];

square(arr);

for (i=0;i<=9; i++)

{
cout<< arr[i];

2-

#include<iostream>

using namespace std;

void square(int *p)

for(int i=0;i<10;i++)

*(p+i)=*(p+i) * *(p+i);

}
}

int main()

int a[10];

cout<<"enter 10 number";

for(int i=0;i<10;i++)

cin>>a[i];

square(a);

for(int i=0;i<10;i++)

cout<<a[i]<<endl;

}
return 0;

3-

#include<iostream>

using namespace std;

int square(int n)

int res=n*n;

return res;

int main()

int a[10],i;

cout<<"enter 10 number";
for(i=0;i<10;i++)

cin>>a[i];

for(i=0;i<10;i++)

cout<<square(a[i])<<endl;

return 0;

4-

int a[10];

void square()
{

for(int i=0;i<10;i++)

a[i]=a[i]*a[i];

int main()

cout<<"enter 10 number";

for(int i=0;i<10;i++)

cin>>a[i];

square();

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

cout<<a[i]<<endl;

B) Develop a program that utilizes pointers to

manage three arrays—a,

b, and c—each containing 10 elements. Implement

three separate

functions within this program:

read: This function should accept an array and

use pointers to fill it with

user-inputted values.

add: This function should calculate the sum of

every pair of these


arrays, producing three new arrays: a+b, b+c,

and a+c.

print: This function should display the

contents of the resultant arrays.

The program should ensure that each function

appropriately handles

pointers to perform its operations.

#include<iostream>

using namespace std;

void read(int *p, int n)

for(int i=0;i<n;i++)

cin>>*(p+i);
}

void add(int *p1, int *p2,int *p3,int n)

for(int i=0;i<n;i++)

*(p3+i)=*(p1+i) + *(p2+i);

void print(int *p, int n)

for(int i=0;i<n;i++)

cout<<*(p+i)<<endl;
}

int main()

{int a[10],b[10],c[10],

res1[10],res2[10],res3[10];

read(a,10);

read(b,10);

read(c,10);

add(a,b,res1,10);

add(b,c,res2,10);

add(a,c,res3,10);

cout<<"a+b"<<endl;

print(res1,10);
cout<<"b+c"<<endl;

print(res2,10);

cout<<"a+c"<<endl;

print(res3,10);

return 0;

C) Write a program to call a function that

prints the reverse order of

n numbers in an array using pointer.

using namespace std;

void reverse(int *p,int size)

for(int i=size;i>=0;i--)
{

cout<<*(p+i)<<endl;

int main (){

int * array;

int n;

cout<<"please enter number of numbers";

cin>>n;

array= new int[n];

cout<<"Enter the array numbers";

for(int i=0;i<n;i++)

{
cin>>*(array+i);

reverse(array,n);

Sorting
Merge sort
#include <iostream>
using namespace std;

// Function to merge two halves


void merge(int A[], int low, int mid, int high) {
int i = low, j = mid + 1, k = 0;
int temp[high - low + 1];

while (i <= mid && j <= high) {


if (A[i] < A[j]) {
temp[k++] = A[i++];
} else {
temp[k++] = A[j++];
}
}

while (i <= mid) {


temp[k++] = A[i++];
}

while (j <= high) {


temp[k++] = A[j++];
}

for (i = low, k = 0; i <= high; i++, k++) {


A[i] = temp[k];
}
}

// Recursive Merge Sort function


void mergeSort(int A[], int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
mergeSort(A, low, mid);
mergeSort(A, mid + 1, high);
merge(A, low, mid, high);
}
}

int main() {
int arraySize = 7;
int A[7] = {38, 27, 43, 3, 9, 82, 10};

int low = 0;
int high = arraySize - 1;

mergeSort(A, low, high);

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


cout << A[i] << " ";
}

return 0;
}
Quick sort
#include <iostream>
using namespace std;

// Partition function divides the array and returns the pivot index
int Partition(int A[], int low, int high) {
int pivot = A[low]; // Choose the first element as the pivot
int leftwall = low; // The "wall" separates elements smaller than
pivot

// Loop through the rest of the array


for (int i = low + 1; i <= high; i++) {
if (A[i] < pivot) {
leftwall++; // Move the wall one step to the right
swap(A[i], A[leftwall]); // Put the smaller element on the left side
}
}

// Put the pivot in its correct position (middle of the smaller and larger
elements)
swap(A[low], A[leftwall]);

// Return the final position of the pivot


return leftwall;
}

// The Quicksort function recursively sorts the array


void Quicksort(int A[], int low, int high) {
// Base condition: only proceed if there are at least 2 elements
if (low < high) {
// Partition the array and get the index of the pivot
int pivot_location = Partition(A, low, high);

// Recursively sort the left part (before pivot)


Quicksort(A, low, pivot_location - 1);

// Recursively sort the right part (after pivot)


Quicksort(A, pivot_location + 1, high);
}
}

// Main function to test the quicksort


int main() {
// Example array to sort
int A[] = {33, 10, 55, 71, 29, 3, 17};
int size = sizeof(A) / sizeof(A[0]); // Get number of elements in the
array

// Print array before sorting


cout << "Before Sorting: ";
for (int i = 0; i < size; i++)
cout << A[i] << " ";
cout << endl;

// Call quicksort on the whole array


Quicksort(A, 0, size - 1);

// Print array after sorting


cout << "After Sorting: ";
for (int i = 0; i < size; i++)
cout << A[i] << " ";
cout << endl;

return 0;
}

Bubble Sort
#include <iostream>
using namespace std;

void bubbleSort(int arr[], int n) {


int k, r, temp;
for (k = 0; k < n - 1; k++) {
for (r = k + 1; r < n; r++) {
if (arr[k] > arr[r]) {
temp = arr[k];
arr[k] = arr[r];
arr[r] = temp;
}
}
}
}

int main() {
int a[10];
int k;

cout << "Enter 10 elements:\n";


for (k = 0; k < 10; k++) {
cin >> a[k];
}

int n = sizeof(a) / sizeof(a[0]);

bubbleSort(a, n);

cout << "Sorted array:\n";


for (k = 0; k < 10; k++) {
cout << a[k] << " ";
}

return 0;
}

Insertion Sort

#include <iostream>
using namespace std;

void insertionSort(int A[], int n) {


for (int i = 1; i < n; i++) {
int key = A[i]; // The current element to be inserted
int j = i - 1;

// Shift elements of A[0..i-1] that are greater than key to the right
while (j >= 0 && A[j] > key) {
A[j + 1] = A[j]; // Move element one step to the right
j = j - 1;
}

A[j + 1] = key; // Insert the key in the right position


}
}

int main() {
int A[] = {8, 3, 5, 2};
int n = sizeof(A) / sizeof(A[0]);

insertionSort(A, n);

cout << "Sorted array: ";


for (int i = 0; i < n; i++) {
cout << A[i] << " ";
}
return 0;
}

SelectionSort

#include <iostream>
using namespace std;

void selectionSort(int A[], int n) {


for (int i = 0; i < n - 1; i++) {
int minIndex = i; // Assume the current index has the minimum

// Search for the smallest element in the rest of the array


for (int j = i + 1; j < n; j++) {
if (A[j] < A[minIndex]) {
minIndex = j; // Update index of the minimum
}
}

// Swap if a smaller element was found


if (minIndex != i) {
int temp = A[i];
A[i] = A[minIndex];
A[minIndex] = temp;
}
}
}

int main() {
int A[] = {8, 3, 5, 2};
int n = sizeof(A) / sizeof(A[0]);

selectionSort(A, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << A[i] << " ";
}

return 0;
}

Files
//Write a program to store squares of numbers
from 1 to 10
//in a file

void main(void)
{
​ int k;
​ ofstream ofp;
​ ofp.open("mosalah.txt");
​ for(k = 1 ; k <= 10 ; k++)
​ ​ ofp << k << "\t" << k*k << "\n";
​ ofp.close();
}

Write a program to read a file mydata


//then, print the data inside it

void main(void)
{
​ ifstream​ ifp;
​ ifp.open("mydata.txt");
​ if(ifp.is_open() == true)​ ​ ​ cout << "Input file is opened \n";
​ else​ ​ ​ ​ ​ { cout << "Error, input file could not be
opened \n"; return; }
​ int a , b;
​ while(ifp >> a)
​ {
​ ​ ifp >> b;
​ ​ cout << a << "\t" << b << "\n";
​ }
​ getch();
}

Write a program to store squares of even


numbers from 6 to 40
//in a file called salah
//Then, reopen the file and print its contents

void main(void)
{
​ int k;
​ ofstream toto;
​ toto.open("salah.txt");
​ for(int k = 6 ; k <= 40 ; k=k+2)
​ ​ toto << k << "\t" << k*k << "\n";
​ toto.close();
}
*/
/*
void main(void)
{
​ ifstream ifp;
​ ifp.open("salah.txt");
​ if(ifp.is_open() == true)​ ​ ​ cout << "Input file is opened \n";
​ else​ { cout << "Error, input file could not be opened \n"; getch();​ ​
return; }
​ int a , b;
​ while(ifp >> a)
​ {
​ ​ ifp >> b;
​ ​ cout << a << "\t" << b << "\n";
​ }
​ getch();
}

// Write a program to print contents of the


previous
//file squares.txt
/*
void main(void)
{
​ FILE *pf2;
​ pf2 = fopen("salah.txt","r");
​ if(pf2 == NULL)
​ {
​ ​ cout << "ERROR; File can not be opened\n";
​ ​ return;
​ }

​ int k , n , m;
​ for(k = 1 ; k <= 9 ; k++)
​ {
​ ​ fscanf(pf2,"%d %d ",&n,&m);
​ ​ printf("%d \t %d \n",n,m);
​ }
​ fclose(pf2);
}
*/

//Write a program to generate random


unrepeated numbers with values less
//than 100. Store the generated numbers in a
file called
//"random_numbers.txt". If the generated
number is equals
//to zero, stop the program.
/*
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
srand(time(NULL));

int nums[99];

// 1. 99 ‫ إلى‬1 ‫نمأل المصفوفة من‬


for (int i = 0; i < 99; i++) {
nums[i] = i + 1;
}

// 2. ‫ نعمل‬shuffle (‫)تبديل عشوائي‬


for (int i = 0; i < 99; i++) {
int j = rand() % 99;
// ‫تبادل العناصر‬
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}

// 3. ‫نكتب األرقام في الملف‬


ofstream outFile("random_numbers.txt");
for (int i = 0; i < 99; i++) {
outFile << nums[i] << "\n";
cout << nums[i] << "\t";
}
outFile.close();

return 0;
}

If repeated
void main(void)
{
​ srand(time(NULL));
//​ srand(3);
​ ofstream ofp;
​ ofp.open("random_numbers.txt");

​ int num ;
​ do{
​ ​ num = rand() % 100;
​ ​ cout << num << "\t";
​ ​ ofp << num << "\n";
​ }while(num != 0);
​ ofp.close();
​ getch();
}

//Write a program to read integer numbers from


a file called
//"random_numbers.txt" store odd numbers in
a file called
//"odd_numbers.txt" and even numbers in
//another file called "even_numbers.txt".
/*
void main(void)
{
​ ofstream oddp , evenp;
​ ifstream ifp;
​ ifp.open("random_numbers.txt");
​ oddp.open("odd_numbers.txt");
​ evenp.open("even_numbers.txt");
​ int num;
​ while(ifp)
​ {
​ ​ ifp >> num ;
​ ​ if(num % 2 == 0)​ ​ evenp << num << "\n";
​ ​ else​ ​ ​ ​ ​ ​ ​ oddp << num << "\n";
​ ​ cout << num << "\t";
​ }
​ ifp.close();
​ oddp.close();
​ evenp.close();
​ getch();
}
//Write a program to copy a file calld
"random_numbers.txt"
//into another file called "mydata.txt"
/*
void main(void)
{
​ FILE *pf1 , *pf2;
​ char ch;
​ pf1 = fopen("random_numbers.txt","r");
​ if(pf1 == NULL)
​ {
​ ​ printf( "ERROR; random_numbers.txt file can not be opened\n");
​ ​ return;
​ }
​ pf2 = fopen("mydata.txt","w");
​ if(pf2 == NULL)
​ {
​ ​ printf("ERROR; mydata.txt file can not be opened\n");
​ ​ return;
​ }

​ while((ch = getc(pf1)) != EOF )


​ {
//​ ​ ch = getc(pf1);
//​ ​ if(ch == EOF)​ ​ break;
//​ ​ ch++;
​ ​ putc(ch,pf2);
​ ​ cout << ch;
​ }

​ fclose(pf1);
​ fclose(pf2);
}
*/

//Write a program to read a key number.


//Count the number of times this key
//number exists in a file called
"odd_numbers.txt"
/*
void main(void)
{
​ ifstream ifp("odd_numbers.txt");
​ int key , n , counter = 0 ;
​ if(!ifp)
​ {
​ ​ printf( "ERROR; random_numbers.txt file can not be opened\n");
​ ​ return;
​ }
​ cout << "Enter key number: ";
​ cin >> key;
​ while(ifp)
​ {
​ ​ ifp >> n;
​ ​ if(n == key)​ counter++;
​ ​ cout << n << " ";
​ }
​ cout << "\n The number " << key << " is found " << counter << " times \n";
​ ifp.close();
​ getch();
}

//Write a program to read numbers from a file


called
//"random_numbers.txt"
//sort these numbers, store the numbers after
sorting in a
//file called sorted_random_numbers.txt
/*
void main(void)
{
​ int a , b , size , *arr , temp;
​ ifstream​ ifp;
​ ofstream​ ofp;
​ ifp.open("random_numbers.txt");
​ if(ifp.is_open() == true)​ ​ ​ cout << "Input file is opened \n";
​ else​ { cout << "Error, input file could not be opened \n"; return; }
​ size = 0;
​ while(ifp >> a)​ { cout << a << "\t" ;​ size++; }
​ ifp.close();
​ arr = new int[size];
​ ifp.open("random_numbers.txt");
​ for(a = 0 ; ifp >> arr[a] ; a++)​ ​ ​ continue;
//​ for(a = 0 ; a < size ; a++)​ ​ ​ ifp >> arr[a];
​ ifp.close();

​ for(a = 0 ; a <= size -2 ; a++)


​ ​ for(b = a+1 ; b <= size-1 ; b++)
​ ​ ​ if(arr[a] > arr[b])
​ ​ ​ { temp = arr[a] ; arr[a] = arr[b] ; arr[b] = temp ; }

​ cout << "\n\n";


​ ofp.open("sorted_random_numbers.txt");
​ for(a = 0 ; a < size ; a++)
​ {​ ​
​ ​ ofp << arr[a] << "\n";
​ ​ cout << arr[a] << "\t";
​ }
​ ofp.close();
}
*/

//Write a program to read numbers from a file


called
//"random_numbers.txt"
//delete repeated numbers, store the numbers
after deleting in a
//file called unrepeated_data.txt
#include <iostream>
#include <fstream>

using namespace std;

int main() {
ifstream inputFile("random_numbers.txt");
ofstream outputFile("unrepeated_random_numbers.txt");

if (!inputFile.is_open()) {
cout << "Error opening input file.\n";
return 1;
}

int temp;
int arr[1000]; // Assuming max 1000 numbers
int count = 0;
bool isRepeated;

// Read numbers one by one


while (inputFile >> temp) {
isRepeated = false;

// Check for duplicates


for (int i = 0; i < count; i++) {
if (arr[i] == temp) {
isRepeated = true;
break;
}
}

// If not a duplicate, add it to the array


if (!isRepeated) {
arr[count] = temp;
count++;
}
}

inputFile.close();

// Write unrepeated numbers to output file


for (int i = 0; i < count; i++) {
outputFile << arr[i] << endl;
cout << arr[i] << "\t"; // Optional: print to screen
}

outputFile.close();
return 0;
}
Stackusing ARRAY
class stack_using_array
{
private:
​ int top , size , *arr ;
public:
​ stack_using_array(void)
​ {
​ ​ arr = new int[10];
​ ​ size = 10;
​ ​ top = 0;
​ }
​ stack_using_array(int ss)
​ {
​ ​ arr = new int[ss];
​ ​ size = ss;
​ ​ top = 0;
​ }
​ void push(int value)
​ {
​ ​ if(top >= size)
​ ​ {
​ ​ ​ cout << "Stack is full, so size will be double\n";
​ ​ ​ double_size();
​ ​ }
​ ​ arr[top] = value ;
​ ​ top++;
​ }
​ int pop(void)
​ {
​ ​ if(top == 0)
​ ​ {
​ ​ ​ cout << "Stack is empty\n";
​ ​ ​ return -1;
​ ​ }
​ ​ top--;
​ ​ return arr[top];
​ }
​ int read_top_data(void)
​ {
​ ​ if(top == 0)​ ​ return -1;
​ ​ else​ ​ ​ ​ ​ return arr[top-1];
​ }
​ bool is_full(void)
​ {
​ ​ return top == size;
​ }
​ bool is_empty(void)
​ {
​ ​ return top == 0 ;
​ }
​ int get_max_size(void)
​ {
​ ​ return size ;
​ }
​ int get_nuumber_of_item(void)
​ {
​ ​ return top;
​ }
​ void double_size(void)
​ {
​ ​ int *temparr;
​ ​ temparr = new int[size*2];
​ ​ for(int k = 0 ; k < top ; k++)
​ ​ ​ temparr[k] = arr[k];
​ ​ delete arr;
​ ​ size = size * 2;
​ ​ arr = temparr;
​ }
​ void delete_stack_data()
​ {
​ ​ top = 0;
​ }
​ ~stack_using_array(void)
​ {
​ ​ delete arr;
​ }
};

Queue Using ARRAY


#include <iostream>
using namespace std;

// ‫تعريف كالس الطابور باستخدام مصفوفة‬


class queue_using_array
{
private:
int *arr; // ‫مصفوفة لتخزين عناصر الطابور‬
int front; // ‫)مؤشر العنصر األول (لإلخراج‬
int rear; // ‫)مؤشر نهاية الطابور (إلدخال عنصر جديد‬
int size; // ‫الحجم الكلي للطابور‬
int counter; // ‫عدد العناصر الحالية في الطابور‬

public:
// Constructor ‫لتحديد الحجم‬
queue_using_array(int ss)
{
size = ss;
arr = new int[size];
front = rear = counter = 0;
}

// Constructor 10 ‫افتراضي بحجم‬


queue_using_array()
{
size = 10;
arr = new int[size];
front = rear = counter = 0;
}

// ‫إدخال عنصر في نهاية الطابور‬


void enqueue(int n)
{
if (isfull())
{
cout << "Queue is full. Doubling size...\n";
‫نكبر الحجم إذا امتأل ‪double_size(); //‬‬
‫}‬
‫;‪arr[rear] = n‬‬ ‫ضع العنصر في المكان الصحيح ‪//‬‬
‫;‪rear = (rear + 1) % size‬‬ ‫تحرك للخلف بطريقة دائرية ‪//‬‬
‫;‪counter++‬‬ ‫زيد عدد العناصر ‪//‬‬
‫}‬

‫إخراج عنصر من بداية الطابور ‪//‬‬


‫)(‪int dequeue‬‬
‫{‬
‫))(‪if (isempty‬‬
‫{‬
‫;"‪cout << "Queue is empty!\n‬‬
‫;‪return -1‬‬
‫}‬
‫;‪int temp = front‬‬ ‫احفظ مكان العنصر الخارج ‪//‬‬
‫;‪front = (front + 1) % size‬‬ ‫تحرك لألمام بشكل دائري ‪//‬‬
‫;‪counter--‬‬ ‫نقص عدد العناصر ‪//‬‬
‫;]‪return arr[temp‬‬ ‫أرجع العنصر ‪//‬‬
‫}‬

‫التحقق هل الطابور فارغ ‪//‬‬


‫)(‪bool isempty‬‬
‫{‬
‫;)‪return (counter == 0‬‬
‫}‬

‫التحقق هل الطابور ممتليء ‪//‬‬


‫)(‪bool isfull‬‬
‫{‬
‫;‪return counter == size‬‬
‫}‬

‫إرجاع عدد العناصر الموجودة ‪//‬‬


‫)(‪int get_number_of_elements‬‬
‫{‬
‫;‪return counter‬‬
}

// ‫إرجاع الحجم األقصى للطابور‬


int get_max_size()
{
return size;
}

// ‫إرجاع أول عنصر في الطابور‬


int get_front()
{
if (!isempty())
return arr[front];
else
{
cout << "Queue is empty!\n";
return -1;
}
}

// ‫مضاعفة حجم الطابور‬


void double_size()
{
int *temp = new int[size * 2]; // ‫مصفوفة جديدة بحجم مضاعف‬
for (int k = 0; k < counter; k++)
temp[k] = arr[(k + front) % size]; // ‫نسخ العناصر بشكل دائري‬

delete[] arr; // ‫حذف القديمة‬


arr = temp;
front = 0;
rear = counter;
size *= 2; // ‫تحديث الحجم الجديد‬
}
};

// ‫البرنامج الرئيسي لتجربة الطابور‬


int main()
{
queue_using_array q(3); // 3 ‫إنشاء طابور بحجم‬

// ‫إدخال عناصر‬
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);

// ‫)تجربة إدخال عنصر بعد االمتالء (سيقوم بمضاعفة الحجم‬


q.enqueue(40);

// ‫إخراج عنصر‬
cout << "Dequeued: " << q.dequeue() << endl;

// ‫عرض أول عنصر حالي‬


cout << "Front element: " << q.get_front() << endl;

// ‫إدخال عنصر جديد‬


q.enqueue(50);

// ‫عرض جميع العناصر المتبقية‬


cout << "Queue elements:\n";
while (!q.isempty())
{
cout << q.dequeue() << " ";
}

cout << "\nFinal size of queue: " << q.get_max_size() << endl;
return 0;
}

Stack using LL
//Stack by linked list

struct stackNode
{
​ int data;
​ stackNode *next;
};

class LinkedListStack
{
private:
​ stackNode *top;
public:
​ LinkedListStack()
​ {
​ ​ top = NULL;
​ }
​ bool isEmpty(void)
​ {
​ ​ return top == NULL;
​ }
​ void push(int dd)
​ {
​ ​ stackNode *temp;
​ ​ temp = new stackNode ;
​ ​ temp->data = dd;
​ ​ temp->next = top;
​ ​ top = temp;
​ }
​ int pop(void)
​ {
​ ​ stackNode *temp;
​ ​ int dd;
​ ​ dd = top->data;
​ ​ temp = top;
​ ​ top = top->next ;
​ ​ delete temp;
​ ​ return dd;
​ }
​ int getNumberOfElements(void)
​ {
​ ​ int counter;
​ ​ stackNode *temp;
​ ​ counter = 0;
​ ​ for(temp = top ; temp != NULL ; temp = temp->next)​ ​
​ ​ ​ counter++;
​ ​ return counter;
​ }
​ void printStack(void)
​ {
​ ​ stackNode *temp;
​ ​ cout << "Data in stack: ";
​ ​ for(temp = top ; temp != NULL ; temp = temp->next)​ ​
​ ​ ​ cout << temp->data << "\t";
​ ​ cout << "\n";
​ }
​ void deleteStack(void)
​ {
​ ​ stackNode *temp;
​ ​ while( top != NULL )​​
​ ​ {
​ ​ ​ temp = top;
​ ​ ​ top = top->next;
​ ​ ​ delete temp;
​ ​ }
​ }
};

queue using linked


list
struct queueNode
{
​ int data;
​ queueNode *next;
};

class LinkedListQueue
{
private:
​ queueNode *front, *rear;
public:
​ LinkedListQueue()
​ {
​ ​ front = rear = NULL;
​ }
​ void enqueue(int dd)
​ {
​ ​ queueNode *temp;
​ ​ temp = new queueNode;
​ ​ temp->data = dd;
​ ​ temp->next = NULL;
​ ​ if(rear == NULL)​ ​ front = rear = temp;
​ ​ else
​ ​ ​ {
​ ​ ​ ​ rear->next = temp;
​ ​ ​ ​ rear = temp;
​ ​ }
​ }
​ int dequeue(void)
​ {
​ ​ queueNode *temp;
​ ​ int dd;
​ ​ dd = front->data;
​ ​ temp = front;
​ ​ front = front->next;
​ ​ delete temp;
​ ​ if(front == NULL)​ ​ rear = NULL;
​ ​ return dd;
​ }
​ bool isEmpty(void)
​ {
​ ​ return front == NULL;
​ }
​ void printQueue(void)
​ {
​ ​ queueNode *temp;
​ ​ cout << "All data in queue : ";
​ ​ for(temp = front ; temp != NULL ; temp = temp->next)
​ ​ ​ cout << temp->data << "\t";
​ ​ cout << "\n";
​ }
​ int getNumberOfElements(void)
​ {
​ ​ int counter;
​ ​ queueNode *temp;
​ ​ counter = 0;
​ ​ for(temp = front ; temp != NULL ; temp = temp->next)​ ​
​ ​ ​ counter++;
​ ​ return counter;
​ }
};
‫رر‬

You might also like