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

Intermediate Level C Programming

The document provides code snippets and explanations for 9 problems involving arrays: 1) Finding the maximum difference between elements in an array 2) Finding the longest increasing subarray 3) Finding common elements between two arrays 4) Finding an element that appears more than n/2 times in an array 5) Rearranging an array so negative elements come before positive 6) Finding the majority element (appears more than n/2 times) if it exists 7) Finding the subarray with the largest sum 8) Rotating an array k positions to the right 9) Rearranging an array so even elements come before odd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Intermediate Level C Programming

The document provides code snippets and explanations for 9 problems involving arrays: 1) Finding the maximum difference between elements in an array 2) Finding the longest increasing subarray 3) Finding common elements between two arrays 4) Finding an element that appears more than n/2 times in an array 5) Rearranging an array so negative elements come before positive 6) Finding the majority element (appears more than n/2 times) if it exists 7) Finding the subarray with the largest sum 8) Rotating an array k positions to the right 9) Rearranging an array so even elements come before odd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 74

Problem Solving

Intermediate Level
Topics Covered: Array, Pinter, Recursion, Structure

1. Given an array of integers, find the maximum difference between any two
elements in the array.
#include<stdio.h>

/* The function assumes that there are at least two


elements in array.
2. The function returns a negative value if the
array is
3. sorted in decreasing order.
4. Returns 0 if elements are equal */
5. int maxDiff(int arr[], int arr_size)
6. {
7. int max_diff = arr[1] - arr[0];
int i, j;
for (i = 0; i < arr_size; i++)
{
8. for (j = i+1; j < arr_size; j++)
9. {
10. if (arr[j] - arr[i] > max_diff)
11. max_diff = arr[j] - arr[i];
12. }
13. }
14. return max_diff;
15. }
16.
17. /* Driver program to test above function
*/
18. int main()
19. {
20. int arr[] = {1, 2, 90, 10, 110};
21. printf("Maximum difference is %d",
maxDiff(arr, 5));
22. getchar();
23. return 0;
24. }

Output:
Maximum difference is 109
2. Given an array of integers, find the longest increasing subarray.

// C implementation of the approach

#include <stdio.h>

// Find maximum between two numbers.

int max(int num1, int num2)

return (num1 > num2) ? num1 : num2;

// Function to return the maximum length


of strictly

// increasing subarray after removing


atmost one element

int maxIncSubarr(int a[], int n)

// Create two arrays pre and pos

int pre[n];

int pos[n];

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

pre[i] = 0;

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

pos[i] = 0;

pre[0] = 1;

pos[n - 1] = 1;

int l = 0;
// Find out the contribution of the
current element in

// array[0, i] and update pre[i]

for (int i = 1; i < n; i++) {

if (a[i] > a[i - 1])

pre[i] = pre[i - 1] + 1;

else

pre[i] = 1;

// Find out the contribution of the


current element in

// array[N - 1, i] and update pos[i]

l = 1;

for (int i = n - 2; i >= 0; i--) {

if (a[i] < a[i + 1])

pos[i] = pos[i + 1] + 1;

else

pos[i] = 1;

// Calculate the maximum length of


the strictly

// increasing subarray without


removing any element

int ans = 0;

l = 1;

for (int i = 1; i < n; i++) {

if (a[i] > a[i - 1])


l++;

else

l = 1;

ans = max(ans, l);

// Calculate the maximum length of


the strictly

// increasing subarray after


removing the current

// element

for (int i = 1; i <= n - 2; i++)

if (a[i - 1] < a[i + 1])

ans = max(pre[i - 1] + pos[i


+ 1], ans);

return ans;

// Driver code

int main()

int arr[] = { 1, 2 };

int n = sizeof(arr) / sizeof(int);

printf("%d", maxIncSubarr(arr, n));

return 0;

// This code is contributed by Sania


Kumari Gupta
Output
2

3. Given two arrays of integers, find the common elements between them.

// C Program to demonstrate scrunity of

// 2 Common Array Elements Using Brute


force

#include <stdio.h>

int main()

int array1[] = { 8, 2, 3, 4, 5, 6,
7, 1 };

int array2[] = { 4, 5, 7, 11, 6,


1 };

int i, j, flag, x, k = 0;

int result[100];

printf("Common elements are: ");

// To traverse in array1.

for (i = 0; i < sizeof(array1) / 4;


i++) {

// To traverse in array2.

for (j = 0; j < sizeof(array2) /


4; j++) {

// To match elements of
array1 with elements of

// array2.

if (array1[i] == array2[j])
{
flag = 0;

// To traverse in result
array.

for (x = 0; x < k; x++)


{

// Check whether
found element is

// already present
in result array or

// not.

if (result[x] ==
array1[i]) {

flag++;

// If we found a new
element which is common

// in both arrays then


store it in result

// array and print it.

if (flag == 0) {

result[k] =
array1[i];

printf("%d ",
result[k]);

k++;

}
}

Output
Common elements are: 4 5 6 7 1

4. Given an array of integers, find the element that appears more than n/2 times
(where n is the size of the array).
#include<stdio.h>

Int main(){

Int n;
Scanf(“%d”,&n);

Int arr[n];
For(int i=0; i<n; i++)
Scanf(“%d”,&arr[i]);

Int k;
Scanf(“%d”,&k);

Int x = n/k;

For(int i=0; i<n; i++){

Int count = 1;
If(arr[i] != -1){
For(int j=i+1; j<n; j++){

If(arr[i]==arr[j]){
Count++;
Arr[j] = -1; //set that visited element to -1 to avoid repetition
}
}
}
If(count > x) printf(“%d “,arr[i]);
}

}
Input :
9
122666679
4

Output :
6

5. Given an array of integers, rearrange the elements in such a way that all the
negative elements come before the positive elements.
#include <stdio.h>
#include <stdlib.h>
void rearrange_alternate_positions(int arr[], int n)
{
int i,j;
j = 0;
for(i = 0; i < n; i++)
{
if(arr[i] < 0)
{
if(i != j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
j++;
}
}
}
int main()
{
int n,i;
printf("\nEnter the number of elements : ");
scanf("%d",&n);
int arr[n];
printf("\nInput the array elements : ");
for(i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
printf("\nOriginal array : ");
for(i = 0; i < n; i++)
{
printf("%d ",arr[i]);
}
printf("\n");
rearrange_alternate_positions(arr, n);
printf("\nRearranged array : ");
for(i = 0; i < n; i++)
{
printf("%d ",arr[i]);
}
printf("\n");
return 0;
}

OUTPUT
Input-
Enter the number of elements:6
Input the array elements:-1 1 -2 2 -3 3
Original array:-1 1 -2 2 -3 3
Output-
Rearranged array : -1 -2 -3 2 1 3

6. Given an array of integers, find the majority element (an element that appears
more than n/2 times, where n is the size of the array) if it exists.
#include <stdio.h>

Void findMajority(int arr[], int n)


{
Int maxCount = 0;
Int index = -1; // sentinels
For (int I = 0; I < n; i++) {
Int count = 0;
For (int j = 0; j < n; j++) {
If (arr[i] == arr[j])
Count++;
}

If (count > maxCount) {


maxCount = count;
index = I;
}
}

If (maxCount > n / 2)
Printf(“%d\n”, arr[index]);

Else
Printf(“No Majority Element\n”);
}

Int main()
{
Int arr[] = { 1, 1, 2, 1, 3, 5, 1 };
Int n = sizeof(arr) / sizeof(arr[0]);
findMajority(arr, n);

return 0;
}
Output:
1

7. Given an array of integers, find the subarray with the largest sum.
#include <stdio.h>
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
Int maxSubArraySum(int arr[], int n)
{
Int I =0;
Int max_so_far = 0;
Int max_ending_here = 0;
For ( I = 0; I < n; i++)
{

Max_ending_here = max_ending_here + arr[i];


If (max_ending_here < 0)
{
Max_ending_here = 0;
}

If (max_so_far < max_ending_here)


{
Max_so_far = max_ending_here;
}
}
Return max_so_far;
}
Int main()
{
Int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };

Int arr_size = ARRAY_SIZE(arr);


Const int maxSum = maxSubArraySum(arr, arr_size);
Printf(“%d “, maxSum);
Return 0;
}
Output:
Maximum subarraysum=6

8. Given an array of integers, rotate the array by k positions to the right.

// C program to rotate right an array


by K times

#include <stdio.h>

// using namespace std;

int main()

int arr[] = { 1, 3, 5, 7, 9, 11 };

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

int k = 3; //No. of rotations

k = k % n;

int i, j;

// Reverse last k numbers

for (i = n - k, j = n - 1; i < j; i+
+, j--) {
int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

// Reverse the first n-k terms

for (i = 0, j = n - k - 1; i < j; i+
+, j--) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

// Reverse the entire array

for (i = 0, j = n - 1; i < j; i++,


j--) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

// Print the rotated array

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

printf("%d ", arr[i]);

return 0;

Output
7 9 11 1 3 5
9. Given an array of integers, rearrange the array in such a way that all the even
elements come before the odd elements.

#include<stdio.h>

#define N 10

int main()
{
int a[N], i, j = N, temp;

printf("Enter %d integer numbers\n", N);


for(i = 0; i < N; i++)
scanf("%d", &a[i]);

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


{
if(a[i] % 2 != 0)
{
while(j > i)
{
j--;
if(a[j] % 2 == 0)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
break;
}
}
}
}

printf("\nAfter re-arranging even and odd elements ...\n");


for(i = 0; i < N; i++)
printf("%d\n", a[i]);

return 0;
}
Output:
Enter 10 integer numbers
1
2
3
4
5
6
7
8
9
10

After re-arranging even and odd elements …


10
2
8
4
6
5
7
3
9
1
10. Given an array of integers, find the longest subarray with equal number of 0s
and 1s.
// A simple program to find the largest subarray
// with equal number of 0s and 1s

#include <stdio.h>

// This function Prints the starting and ending


// indexes of the largest subarray with equal
// number of 0s and 1s. Also returns the size
// of such subarray.

int findSubArray(int arr[], int n)


{
int sum = 0;
int maxsize = -1, startindex;

// Pick a starting point as i

for (int i = 0; i < n - 1; i++) {


sum = (arr[i] == 0) ? -1 : 1;

// Consider all subarrays starting from i


for (int j = i + 1; j < n; j++) {
(arr[j] == 0) ? (sum += -1) : (sum += 1);

// If this is a 0 sum subarray, then


// compare it with maximum size subarray
// calculated so far

if (sum == 0 && maxsize < j - i + 1) {


maxsize = j - i + 1;
startindex = i;
}
}
}
if (maxsize == -1)
printf("No such subarray");
else
printf("%d to %d", startindex, startindex + maxsize - 1);

return maxsize;
}

/* Driver program to test above functions*/

int main()
{
int arr[] = { 1, 0, 0, 1, 0, 1, 1 };
int size = sizeof(arr) / sizeof(arr[0]);

findSubArray(arr, size);
return 0;
}
Output:

0 to 5

11. Given an array of integers, find the smallest missing positive integer.

#include <stdio.h>

// Function to find the smallest missing positive number from


an unsorted array
int findSmallestMissing(int nums[], int n)
{
// create an auxiliary array of size `n+1` to mark all positive
elements
int aux[n + 1];
for (int i = 0; i < n + 1; i++) {
aux[i] = 0;
}

// iterate over the array and mark all positive elements in


range `[1, n]`
for (int i = 0; i < n; i++)
{
// ignore all non-positive elements and elements greater
than `n`
if (nums[i] > 0 && nums[i] <= n) {
aux[nums[i]] = 1;
}
}

// check for the smallest missing number between 1 and `n`


for (int i = 1; i <= n; i++)
{
if (!aux[i]) {
return i;
}
}

// If numbers from 1 to `n` are present in the array,


// then the missing number is `n+1`
return n + 1;
}

int main()
{
int nums[] = { 1, 4, 2, -1, 6, 5 };
int n = sizeof(nums) / sizeof(nums[0]);

printf("The smallest positive missing number is %d",


findSmallestMissing(nums, n));

return 0;
}

Output:

The smallest missing positive number from the array is 3

12. Given an array of integers, find the two elements that have the maximum
product.

#include <stdio.h>
#include <limits.h>

// A naïve solution to finding the maximum product of two integers


// in an array
Void findMaximumProduct(int arr[], int n)
{
// base case
If (n < 2) {
Return;
}

Int max_product = INT_MIN;


Int max_i, max_j;
// consider every pair of elements
For (int I = 0; I < n – 1; i++)
{
For (int j = I + 1; j < n; j++)
{
// update the maximum product if required
If (max_product < arr[i] * arr[j])
{
Max_product = arr[i] * arr[j];
Max_i = I, max_j = j;
}
}
}

Printf(“Pair is (%d, %d)”, arr[max_i], arr[max_j]);


}

Int main()
{
Int arr[] = { -10, -3, 5, 6, -2 };
Int n = sizeof(arr) / sizeof(arr[0]);

findMaximumProduct(arr, n);

return 0;
}

Output:

Pair is (-10, -3)

13. Given an array of integers, find the subarray with the maximum product.
14. #include<stdio.h>
15.
16. int main(){
17. int arr[] = { 10, -20, -30, 0, 70, -80, -20 };
18. int n=sizeof(arr)/sizeof(arr[0]);
19. int result = arr[0];
20.
21. for (int i = 0; i < n; i++)
22. {
23. int mul = arr[i];
24. // traversing in current subarray
25. for (int j = i + 1; j < n; j++) { // updating result every time // to keep an eye over the // maximum product
if(mul>result)
26. result = mul;
27. mul *= arr[j];
28. }
29. if(mul>result)
30. result = mul;
31. }
32.
33. printf("Maximum Product of sub-array is %d", result);
34. }
Output
Maximum Product of sub-array is 1600

14. Given an array of integers, find the longest subarray with the given sum.
15. #include <stdio.h>
16.
17. int maxSum(int a[],int n)
18. {
19. int i,j,k;
20. int sum,maxSum = 0;
21. for(i=0; i<n; i++)
22. {
23. for(j=i; j<n; j++)
24. {
25. sum = 0;
26. for(k=i ; k<=j; k++)
27. {
28. sum = sum + a[k];
29. }
30. if(sum>maxSum)
31. maxSum = sum;
32. }
33. }
34. return maxSum;
35. }
36. int main()
37. {
38. int i;
39. int arr1[] = {8, 3, 8, -5, 4, 3, -4, 3, 5};
40. int ctr = sizeof(arr1)/sizeof(arr1[0]);
41. printf("The given array is : ");
42. for(i = 0; i < ctr; i++)
43. {
44. printf("%d ", arr1[i]);
45. }
46. printf("\n");
47. printf("The largest sum of contiguous subarray is : %d \n", maxSum(arr1, ctr));
48. return 0;
49. }
50.
51. Copy
52. Sample Output:
53. The given array is : 8 3 8 -5 4 3 -4 3 5
54. The largest sum of contiguous subarray is : 25

15. Given a matrix (2D array) of integers, find the saddle point(s) (an element that is the
minimum in its row and maximum in its column)

// C program to illustrate Saddle point

#include <stdio.h>

#include <stdbool.h>

#define MAX 100

// Function to find saddle point

bool findSaddlePoint(int mat[MAX][MAX],


int n)

// Process all rows one by one

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

// Find the minimum element of


row i.

// Also find column index of the


minimum element

int min_row = mat[i][0], col_ind


= 0;

for (int j = 1; j < n; j++)

if (min_row > mat[i][j])

min_row = mat[i][j];

col_ind = j;

// Check if the minimum element


of row is also

// the maximum element of column


or not

int k;

for (k = 0; k < n; k++)

// Note that col_ind is


fixed

if (min_row < mat[k]


[col_ind])
break;

// If saddle point is present in


this row then

// print it

if (k == n)

printf("Value of Saddle Point


%d",min_row);

return true;

// If Saddle Point not found

return false;

// Driver code

int main()

int mat[MAX][MAX] = {{1, 2, 3},

{4, 5, 6},

{7, 8, 9}};

int n = 3;

if (findSaddlePoint(mat, n) ==
false)

printf("No Saddle Point ");

return 0;

}
// This code is contributed by
kothavvsaakash.

Output
Value of Saddle Point 7

16. Write a program to swap the values of two variables using pointers.
17. #include <stdio.h>
18.
19. int main()
20. {
21. int x, y, *a, *b, temp;
22.
23. printf("Enter the value of x and y\n");
24. scanf("%d%d", &x, &y);
25.
26. printf("Before Swapping\nx = %d\ny = %d\n", x, y);
27.
28. a = &x;
29. b = &y;
30.
31. temp = *b;
32. *b = *a;
33. *a = temp;
34.
35. printf("After Swapping\nx = %d\ny = %d\n", x, y);
36.
37. return 0;
38. }
Output:
Before swapping
X=3,y=2;
After swapping
x=2,y=3

17. Write a program to find the length of a string using pointers.

1 #include<stdio.h>
2 #include<conio.h>
3
4 int string_ln(char*);
5
6 void main() {
7 char str[20];
8 int length;
9 clrscr();
10
printf("\nEnter any string : ");
11
gets(str);
12
13
length = string_ln(str);
14
printf("The length of the given string
15
%s is : %d", str, length);
16
getch();
17
}
18
19
int string_ln(char*p) /* p=&str[0] */
20
{
21
int count = 0;
22
while (*p != '\0') {
23
count++;
24
p++;
25
}
26
return count;
27
}

Output :
1 Enter the String : pritesh

2 Length of the given string pritesh is : 7

18. Write a program to reverse a string using pointers.

#include <stdio.h>

#include <string.h>
// Function to reverse the string

// using pointers

void reverseString(char* str)

int l, i;

char *begin_ptr, *end_ptr, ch;

// Get the length of the string

l = strlen(str);

// Setting the begin_ptr

// to start of string

begin_ptr = str;

//Setting the end_ptr the end of

//the string

end_ptr = str + l - 1;

// Swap the char from start and end

// index using begin_ptr and end_ptr

for (i = 0; i < (l - 1) / 2; i++) {

// swap character

ch = *end_ptr;

*end_ptr = *begin_ptr;

*begin_ptr = ch;
// update pointers positions

begin_ptr++;

end_ptr--;

// Driver code

int main()

// Get the string

char str[100] = "GeeksForGeeks";

printf("Enter a string: %s\n", str);

// Reverse the string

reverseString(str);

// Print the result

printf("Reverse of the string: %s\


n", str);

return 0;

Output:
Enter a string: GeeksForGeeks
Reverse of the string: skeeGroFskeeG

19. Write a program to count the number of occurrences of a character in a string


using pointers.
20. #include <stdio.h>
21. #include <string.h>
22.
23. int main()
24. {
25. char s[1000],c;
26. int i,count=0;
27.
28. printf("Enter the string : ");
29. gets(s);
30. printf("Enter character to be searched: ");
31. c=getchar();
32.
33. for(i=0;s[i];i++)
34. {
35. if(s[i]==c)
36. {
37. count++;
38. }
39. }
40.
41. printf("character '%c' occurs %d times \n ",c,count);
42.
43.
44.
45. return 0;
46. }

20. Write a program to find the maximum and minimum values in an array using
pointers.
#include <stdio.h>

#include <conio.h>

int main()

int i,j,temp,tempmin, max,min;


max = temp = tempmin = 0;

int arr[10];

min = arr[0];

printf("Enter up to 10 numbers:\n");

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

scanf("%d",&arr[i]);

int *ptr1, *ptr2;

ptr1 = arr;

ptr2 = arr;

for(i=1;i<=10;i++)
{

if(max <= *ptr1)


{

temp = max;

max = *ptr1;
*ptr1 = temp;

ptr1++;

printf("MAX=%d\n",max);

// finding minimum

for(j=1;j<=10;j++) {

if(min >= *ptr2)


{

tempmin = *ptr2;

*ptr2 = min;

min = tempmin;

ptr2++;

printf("MIN=%d\n",min);
system("PAUSE");

return 0;

}
Enter up to 10 numbers:

23

66

87

34

65

32

21

25

85

45

MAX=87

MIN=5

21. Write a program to sort an array of integers in ascending order using pointers.
#include <stdio.h>

Void swap(int* xp, int* yp)


{
Int temp = *xp;
*xp = *yp;
*yp = temp;
}

// Function to perform Selection Sort


Void selectionSort(int arr[], int n)
{
Int I, j, min_idx;

// One by one move boundary of


// unsorted subarray
For (I = 0; I < n – 1; i++) {
// Find the minimum element in
// unsorted array
Min_idx = I;
For (j = I + 1; j < n; j++)
If (arr[j] < arr[min_idx])
Min_idx = j;

// Swap the found minimum element


// with the first element
Swap(&arr[min_idx], &arr[i]);
}
}

// Function to print an array


Void printArray(int arr[], int size)
{
Int I;
For (I = 0; I < size; i++)
Printf(“%d “, arr[i]);
Printf(“\n”);
}

// Driver code
Int main()
{
Int arr[] = { 0, 23, 14, 12, 9 };
Int n = sizeof(arr) / sizeof(arr[0]);
Printf(“Original array: \n”);
printArray(arr, n);

selectionSort(arr, n);
printf(“\nSorted array in Ascending order: \n”);
printArray(arr, n);

return 0;
}
Output:
Original array:
0 23 14 12 9

Sorted array in Ascending order:


0 9 12 14 23

22. Write a program to find factorial of a number using pointers.


#include<stdio.h>

Void findFactorial(int,int *); //function


Int main(){
Int I,factorial,n;

Printf(“Enter a number: “);


Scanf(“%d”,&n);

findFactorial(n,&factorial);
printf(“Factorial of %d is: %d”,n,*factorial);

return 0;
}

Void findFactorial(int n,int *factorial){


Int I;

*factorial =1;

For(i=1;i<=n;i++)
*factorial=*factorial*I;
}
Output:
Enter a number: 5
Factorial of 5 is 120

23. Write a program to check if a given number is prime using pointers.


#include <stdio.h>
Void writePrime(int arr[], int n) {
Int *q = arr, *qq = arr, I, prime;
While (q < arr + n) {
While (qq < arr + n) {
I = 1;
If (*qq % I != 0)
Continue;
Else
Prime = 1;
I++;
Qq++;
}
If (prime == 1)
Printf(“%d “, *q);
Q++;
}
}
Int main() {
Int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 92, 93, 94, 95, 96};
Int n = sizeof(arr) / sizeof(*arr);
writePrime(arr, n);
return 0;
}
Output:
Enter a number:3
3 is a prime number
24. Write a program to concatenate two strings using pointers.
#include <stdio.h>

#define MAX_SIZE 100 // Maximum string size

Int main()
{

Char str1[MAX_SIZE], str2[MAX_SIZE];

Char * s1 = str1;

Char * s2 = str2;

// Inputting 2 strings from user

Printf(“Enter 1st string: “);

Gets(str1);

Printf(“Enter 2nd string: “);

Gets(str2);

// Moving till the end of str1

While(*(++s1));
// Coping str2 to str1

While(*(s1++) = *(s2++));

Printf(“Concatenated string: %s”, str1);

Return 0;

}
Output:
Enter first string:Hello
Enter second string: world
Concatenate string:Hello world

25. Write a program to find the sum of elements in an array using pointers.
#include <stdio.h>
Int main() {
Int arr[100], size;
Int *ptr, sum = 0;
Printf(“Enter the size of the array: “);
Scanf(“%d”, &size);
Printf(“Enter array elements: “);
For (int I = 0; I < size; i++) {
Scanf(“%d”, &arr[i]);
}
// Set address of first array element to *ptr
Ptr = arr;
For (int I = 0; I < size; i++) {
Sum = sum + *ptr;
Ptr++; // Increment pointer by one to get next element
}
Printf(“The sum of array elements is: %d”, sum);
Return 0;
}
Output:
Enter the size of array:5
Enter the array elements:
23451
Sum of array elements is 15
26. Write a program to delete an element from an array using pointers.
#include<stdio.h>
#include<stdlib.h>
Void delete(int n,int *a,int pos);
Int main(){
Int *a,n,I,pos;
Printf(“enter the size of array:”);
Scanf(“%d”,&n);
A=(int*)malloc(sizeof(int)*n);
Printf(“enter the elements:
“);
For(i=0;i<n;i++){
Scanf(“%d”,(a+i));
}
Printf(“enter the position of element to be deleted:”);
Scanf(“%d”,&pos);
Delete(n,a,pos);
Return 0;
}
Void delete(int n,int *a,int pos){
Int I,j;
If(pos<=n){
For(i=pos-1;i<n;i++){
J=i+1;
*(a+i)=*(a+j);
}
Printf(“after deletion the array elements is:
“);
For(i=0;i<n-1;i++){
Printf(“%d
“,(*(a+i)));
}
}
Else{
Printf(“Invalid Input”);
}
}
Output:
Enter the size of array:5
Enter the elements: 1 2 3 4 5
Enter the position of element to be deleted:4
After deletion the array elements is:1 2 3 5

27. Write a program to reverse an array using pointers.

#include <stdio.h>

// Function to swap two memory contents


Void swap(int* a, int* b)
{
Int temp = *a;
*a = *b;
*b = temp;
}

// Function to reverse the array through pointers


Void reverse(int array[], int array_size)
{
// pointer1 pointing at the beginning of the array
Int *pointer1 = array,

// pointer2 pointing at end of the array


*pointer2 = array + array_size – 1;
While (pointer1 < pointer2) {
Swap(pointer1, pointer2);
Pointer1++;
Pointer2--;
}
}

// Function to print the array


Void print(int* array, int array_size)
{
// Length pointing at end of the array
Int *length = array + array_size,

// Position pointing to the beginning of the array


*position = array;
Printf(“Array = “);
For (position = array; position < length; position++)
Printf(“%d “, *position);
}

// Driver function
Int main()
{
// Array to hold the values
Int array[] = { 2, 4, -6, 5, 8, -1 };

Printf(“Original “);
Print(array, 6);

Printf(“Reverse “);
Reverse(array, 6);
Print(array, 6);
Return 0;
}
Output:
{-1,8,5,-6,4,2}
28. Write a program to find the largest and smallest elements in an array using
pointers.
# include < stdio.h >
Int main( )
{
Int a[20],n,I,sml ;
Int *ptr ;
Printf(“ How many Numner you want to enter: “) ;
Scanf(“%d “,& n) ;
Printf(“\n Enter the number : \n”) ;

For (I = 0; I < n ; i++ )


{
Scanf(“%d “,& a[i]) ;
Ptr++ ;
}
Ptr = & a[0] ;
Printf(“ \n Number you enter :\n “) ;
For (I = 0; I < n ; i++ )
{
Printf(“\t %d “,( *ptr )) ;
}
Ptr = & a[0] ;
Sml = a[0] ;
For (I = 0; I < n ; i++ )
{
If ( sml > ( *ptr ))
Sml = *ptr ;
Ptr++ ;
}
Printf(“\n Smallaest element is : %d”,sml) ;
Return ( 0 );
}

Output of Program:
Enter how many numbers u want:5
12345
Smallest number is 1
#include <stdio.h>
#include <stdlib.h>

// Function to find the largest element


// using dynamic memory allocation
Void findLargest(int* arr, int N)
{
Int I;

// Traverse the array arr[]


For (I = 1; I < N; i++) {
// Update the largest element
If (*arr < *(arr + i)) {
*arr = *(arr + i);
}
}

// Print the largest number


Printf(“%d “, *arr);
}

// Driver Code
Int main()
{
Int I, N = 4;

Int* arr;

// Memory allocation to arr


Arr = (int*)calloc(N, sizeof(int));

// Condition for no memory


// allocation
If (arr == NULL) {
Printf(“No memory allocated”);
Exit(0);
}

// Store the elements


*(arr + 0) = 14;
*(arr + 1) = 12;
*(arr + 2) = 19;
*(arr + 3) = 20;
// Function Call
findLargest(arr, N);
return 0;
}

29. Write a program to copy the contents of one array to another using pointers.
#include <stdio.h>

#define MAX_SIZE 100 // Maximum array size

/* Function declaration to print array */


Void printArray(int arr[], int size);

Int main()
{
Int source_arr[MAX_SIZE], dest_arr[MAX_SIZE];
Int size, I;

Int *source_ptr = source_arr; // Pointer to source_arr


Int *dest_ptr = dest_arr; // Pointer to dest_arr

Int *end_ptr;
/*
* Input size and elements in source array
*/
Printf(“Enter size of array: “);
Scanf(“%d”, &size);
Printf(“Enter elements in array: “);
For (I = 0; I < size; i++)
{
Scanf(“%d”, (source_ptr + i));
}

// Pointer to last element of source_arr


End_ptr = &source_arr[size – 1];

/* Print source and destination array before copying */


Printf(“\nSource array before copying: “);
printArray(source_arr, size);

printf(“\nDestination array before copying: “);


printArray(dest_arr, size);

/*
* Run loop till source_ptr exists in source_arr
* memory range.
*/
While(source_ptr <= end_ptr)
{
*dest_ptr = *source_ptr;

// Increment source_ptr and dest_ptr


Source_ptr++;
Dest_ptr++;
}

/* Print source and destination array after copying */


Printf(“\n\nSource array after copying: “);
printArray(source_arr, size);

printf(“\nDestination array after copying: “);


printArray(dest_arr, size);

return 0;
}

/**
* Function to print array elements.
*
* @arr Integer array to print.
* @size Size of array.
*/
Void printArray(int *arr, int size)
{
Int I;

For (I = 0; I < size; i++)


{
Printf(“%d, “, *(arr + i));
}
}
Output:
Enter size of array: 10
Enter elements in array: 10 -1 100 90 87 0 15 10 20 30

Source array before copying: 10, -1, 100, 90, 87, 0, 15, 10, 20, 30,
Destination array before copying: 0, 0, 127, 127, 0, 1, 0, 16777472, 0, 0,

Source array after copying: 10, -1, 100, 90, 87, 0, 15, 10, 20, 30,
Destination array after copying: 10, -1, 100
30. Write a program to find the intersection of two arrays using pointers.
#include <stdio.h>

Int intersection(int arr1[], int arr2[], int arr3[])


{

Int I = 0;
Int j = 0;
Int k = 0;
While ((I < 5) && (j < 5)) {
If (arr1[i] < arr2[j]) {
I++;
}
Else if (arr1[i] > arr2[j]) {
J++;
}
Else {
Arr3[k] = arr1[i];
I++;
J++;
K++;
}
}

Return k;
}

Int main()
{
Int arr1[5] = { 1, 2, 3, 4, 5 };
Int arr2[5] = { 2, 3, 5, 7, 8 };
Int arr3[5] = { 0 };

Int len = 0;
Int cnt = 0;
Len = intersection(arr1, arr2, arr3);

Printf(“Intersection is: “);


For (cnt = 0; cnt < len; cnt++)
Printf(“%d “, arr3[cnt]);

Printf(“\n”);

Return 0;
}
Output:
Intersection is: 2 3 5
31. Write a recursive program to calculate the factorial of a given number.
#include<stdio.h>
Long int multiplyNumbers(int n);
Int main() {
Int n;
Printf(“Enter a positive integer: “);
Scanf(“%d”,&n);
Printf(“Factorial of %d = %ld”, n, multiplyNumbers(n));
Return 0;
}

Long int multiplyNumbers(int n) {


If (n>=1)
Return n*multiplyNumbers(n-1);
Else
Return 1;
}
Output:
Enter a positive number:6
Factorial of 6 is 720
32. Implement a recursive program to find the nth Fibonacci number.
#include <stdio.h>
Int fib(int n)
{
Int a = 0, b = 1, c, I;
If (n == 0)
Return a;
For (I = 2; I <= n; i++) {
C = a + b;
A = b;
B = c;
}
Return b;
}

Int main()
{
Int n = 9;
Printf(“%d”, fib(n));
Getchar();
Return 0;
}
Output:
34
33. Write a program to recursively calculate the sum of digits in a given number.
#include <stdio.h>

// Function to check sum of digit using recursion


Int sum_of_digit(int n)
{
If (n == 0)
Return 0;
Return (n % 10 + sum_of_digit(n / 10));
}

// Driven Program to check above


Int main()
{
Int num = 12345;
Int result = sum_of_digit(num);
Printf(“Sum of digits in %d is %d\n”, num, result);
Return 0;
}
Output:
Sum of digits in 12345 is 15
34. Implement a recursive program to calculate the power of a number.
#include <stdio.h>
Int power(int n1, int n2);
Int main() {
Int base, a, result;
Printf(“Enter base number: “);
Scanf(“%d”, &base);
Printf(“Enter power number(positive integer): “);
Scanf(“%d”, &a);
Result = power(base, a);
Printf(“%d^%d = %d”, base, a, result);
Return 0;
}

Int power(int base, int a) {


If (a != 0)
Return (base * power(base, a – 1));
Else
Return 1;
}
Output:
Enter base number: 3
Enter power number(positive integer): 4
3^4 = 81
35. Write a program to recursively calculate the GCD (Greatest Common Divisor) of
two numbers.
#include <stdio.h>
Int hcf(int n1, int n2);
Int main() {
Int n1, n2;
Printf(“Enter two positive integers: “);
Scanf(“%d %d”, &n1, &n2);
Printf(“G.C.D of %d and %d is %d.”, n1, n2, hcf(n1, n2));
Return 0;
}
Int hcf(int n1, int n2) {
If (n2 != 0)
Return hcf(n2, n1 % n2);
Else
Return n1;
}
Output:
Enter two positive integers: 366
60
G.C.D of 366 and 60 is 6.
36. Implement a recursive program to find the sum of elements in an array.
#include <stdio.h>
//Calculate array size
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
// Return sum of elements in A[0..N-1]
// using recursion.
Int sumArrayElements(int arr[], const int N)
{
If (N <= 0)
{
Return 0;
}
Return (sumArrayElements(arr, N – 1) + arr[N – 1]);
}
Int main()
{
Int arr[] = { 1, 2, 3, 4, 5 };
//calculate array size
Const int N = ARRAY_SIZE(arr);
Printf(“%d\n”, sumArrayElements(arr, N));
Return 0;
}
Output:
Sum is 15

37. Write a program to recursively check if a given string is a palindrome.


#include <stdio.h>
#include <string.h>
#include <stdbool.h>

// A recursive function that


// check a str[s..e] is
// palindrome or not.
Bool isPalRec(char str[],
Int s, int e)
{
// If there is only one character
If (s == e)
Return true;

// If first and last


// characters do not match
If (str[s] != str[e])
Return false;
// If there are more than
// two characters, check if
// middle substring is also
// palindrome or not.
If (s < e + 1)
Return isPalRec(str, s + 1, e – 1);

Return true;
}

Bool isPalindrome(char str[])


{
Int n = strlen(str);

// An empty string is
// considered as palindrome
If (n == 0)
Return true;

Return isPalRec(str, 0, n – 1);


}

// Driver Code
Int main()
{
Char str[] = “geeg”;

If (isPalindrome(str))
Printf(“Yes”);
Else
Printf(“No”);

Return 0;
}
Output:
Geeg is a palindrome
38. Implement a recursive program to reverse a string.
#include <stdio.h>
Void reverseString();
Int main() {
Printf(“Enter a string: “);
reverseString();
return 0;
}

Void reverseString() {
Char c;
Scanf(“%c”, &c);
If (c != ‘\n’) {
reverseString();
printf(“%c”, c);
}
}
Output:
Enter a string: margorp emosewa
Awesome program
39. Write a program to recursively solve the Tower of Hanoi problem for n disks.
#include <stdio.h>

// C recursive function to solve tower of hanoi puzzle


Void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
If (n == 1)
{
Printf(“\n Move disk 1 from rod %c to rod %c”, from_rod, to_rod);
Return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf(“\n Move disk %d from rod %c to rod %c”, n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}

Int main()
{
Int n = 4; // Number of disks
towerOfHanoi(n, ‘A’, ‘C’, ‘B’); // A, B and C are names of rods
return 0;
}
Output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C

40. Implement a recursive program to generate all possible permutations of a given


string.
#include <stdio.h>
#include <string.h>

/* Function to swap values at two pointers */


Void swap(char* x, char* y)
{
Char temp;
Temp = *x;
*x = *y;
*y = temp;
}

/* Function to print permutations of string


This function takes three parameters:
1. String
2. Starting index of the string
3. Ending index of the string. */
Void permute(char* a, int l, int r)
{
Int I;
If (l == r)
Printf(“%s\n”, a);
Else {
For (I = l; I <= r; i++) {
Swap((a + l), (a + i));
Permute(a, l + 1, r);
Swap((a + l), (a + i)); // backtrack
}
}
}

/* Driver code */
Int main()
{
Char str[] = “ABC”;
Int n = strlen(str);
Permute(str, 0, n – 1);
Return 0;
}
Output:
ABC
ACB
BAC
BCA
CBA
CAB

41. Write a program to recursively calculate the sum of all even numbers in a given
range.
#include<stdio.h>
Int SumEven(int num1, int num2)
{
If(num1>num2)
Return 0;
Return num1+SumEven(num1+2,num2);
}
Int main()
{
Int num1=2,num2;
Printf(“Enter your Limit:”);
Scanf(“%d”,&num2);
Printf(“Sum of all Even numbers in the given range is: %d”,SumEven(num1,num2));
}
Output:
Enter your Limit:12
Sum of all Even numbers in the given range is: 42

42. Implement a recursive program to find the binary representation of a decimal


number.
#include <stdio.h>
// Decimal to binary conversion
// using recursion
Int find(int decimal_number)
{
If (decimal_number == 0)
Return 0;
Else
Return (decimal_number % 2 + 10 *
Find(decimal_number / 2));
}

// Driver code
Int main()
{
Int decimal_number = 10;
Printf(“%d”, find(decimal_number));
Return 0;
}
Output:
1010

43. Write a program to recursively calculate the sum of even Fibonacci numbers up
to a given limit.

#include <stdio.h>
#include <math.h>
Int main()
{
Int f1,f2,f3,n,i=2,s=1;
F1=0;
F2=1;
Printf(“How many terms do you \nwant in Fibonacci series? : “);
Scanf(“%d”,&n);
Printf(“\nFibonacci Series Upto %d Terms:\n\n”,n);
Printf(“%d, %d”,f1,f2);
While(i<n)
{
F3=f1+f2;
Printf(“, %d”,f3);
F1=f2;
F2=f3;
S=s+f3;
I++;
}
Printf(“\n\nSum of Fibonacci Series : %d”,s);
Return 0;
}
Output:
How many terms do you want in Fibonacci series? : 8
Fibonacci series upto 8 Terms :
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13
Sum of Fibonacci Series : 33

44. Implement a recursive program to solve the Sudoku puzzle.

#include <stdio.h>
#include <stdlib.h>
#define N 9

Void print(int arr[N][N])


{
For (int I = 0; I < N; i++)
{
For (int j = 0; j < N; j++)
Printf(“%d “,arr[i][j]);
Printf(“\n”);
}
}

Int isSafe(int grid[N][N], int row,


Int col, int num)
{

For (int x = 0; x <= 8; x++)


If (grid[row][x] == num)
Return 0;

For (int x = 0; x <= 8; x++)


If (grid[x][col] == num)
Return 0;
Int startRow = row – row % 3,
startCol = col – col % 3;

for (int I = 0; I < 3; i++)


for (int j = 0; j < 3; j++)
if (grid[I + startRow][j +
startCol] == num)
return 0;

return 1;
}

Int solveSudoku(int grid[N][N], int row, int col)


{

If (row == N – 1 && col == N)


Return 1;

If (col == N)
{
Row++;
Col = 0;
}

If (grid[row][col] > 0)
Return solveSudoku(grid, row, col + 1);

For (int num = 1; num <= N; num++)


{

If (isSafe(grid, row, col, num)==1)


{
Current (row,col]×
Grid[row][col] = num;

// Checking for next possibility with next


// column
If (solveSudoku(grid, row, col + 1)==1)
Return 1;
}

Grid[row][col] = 0;
}
Return 0;
}

Int main()
{

Int grid[N][N] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 },
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 8, 7, 0, 0, 0, 0, 3, 1 },
{ 0, 0, 3, 0, 1, 0, 0, 8, 0 },
{ 9, 0, 0, 8, 6, 3, 0, 0, 5 },
{ 0, 5, 0, 0, 9, 0, 6, 0, 0 },
{ 1, 3, 0, 0, 0, 0, 2, 5, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 7, 4 },
{ 0, 0, 5, 2, 0, 6, 3, 0, 0 } };
If (solveSudoku(grid, 0, 0)==1)
Print(grid);
Else
Printf(“No solution exists”);

Return 0;
// This is code is contributed by Pradeep Mondal P
}
Output:
316578492
529134768
487629531
263415987
974863125
851792643
138947256
692351874
745286319

45. Write a program to recursively calculate the number of ways to reach a target
sum using a set of given numbers.

46. Create a structure named "Employee" to store employee details such as name,
employee ID, and salary. Write a program to initialize and display the details of
an employee using this structure.
#include <stdio.h>

/*structure declaration*/
Struct employee{
Char name[30];
Int empId;
Float salary;
};

Int main()
{
/*declare structure variable*/
Struct employee emp;

/*read employee details*/


Printf(“\nEnter details :\n”);
Printf(“Name ?:”); gets(emp.name);
Printf(“ID ?:”); scanf(“%d”,&emp.empId);
Printf(“Salary ?:”); scanf(“%f”,&emp.salary);

/*print employee details*/


Printf(“\nEntered detail is:”);
Printf(“Name: %s” ,emp.name);
Printf(“Id: %d” ,emp.empId);
Printf(“Salary: %f\n”,emp.salary);
Return 0;
}
Output:
Enter details :
Name ?:Mike
ID ?:1120
Salary ?:76543

Entered detail is:


Name: Mike
Id: 1120
Salary: 76543.000000

47. Define a structure named "Point" to represent a point in a 2D coordinate system.


Write a program to calculate the distance between two points using this
structure.
#include <stdio.h>
#include<math.h>

Int main()
{
Int x1, x2, y1, y2, dtn;

Printf(“Enter the First Point Coordinates = “);


Scanf(“%d %d”,&x1, &y1);

Printf(“Enter the Second Point Coordinates = “);


Scanf(“%d %d”,&x2, &y2);

Int x = pow((x2- x1), 2);


Int y = pow((y2- y1), 2);

Dtn = sqrt(x + y);

Printf(“\nThe Distance Between Two Points = %d\n”, dtn);


}
Output:
Enter the First Coordinates = 2 3
Enter the Second Coordinates = 9 11

The Distance = 10

48. Create a structure named "Book" to store book details such as title, author, and
price. Write a program to initialize an array of books using this structure and
display their details.
#include<stdio.h>

#include<string.h>

#define SIZE 20

Struct bookdetail

Char name[20];

Char author[20];
Int pages;

Float price;

};

Void output(struct bookdetail v[],int n);

Void main()

Struct bookdetail b[SIZE];

Int num,I;

Printf(“Enter the Numbers of Books:”);

Scanf(“%d”,&num);

Printf(“\n”);

For(i=0;i<num;i++)

Printf(“\t=:Book %d Detail:=\n”,i+1);

Printf(“\nEnter the Book Name:\n”);


Scanf(“%s”,b[i].name);

Printf(“Enter the Author of Book:\n”);

Scanf(“%s”,b[i].author);

Printf(“Enter the Pages of Book:\n”);

Scanf(“%d”,&b[i].pages);

Printf(“Enter the Price of Book:\n”);

Scanf(“%f”,&b[i].price);

Output(b,num);

Void output(struct bookdetail v[],int n)

{
Int I,t=1;

For(i=0;i<n;i++,t++)

Printf(“\n”);

Printf(“Book No.%d\n”,t);

Printf(“\t\tBook %d Name is=%s \n”,t,v[i].name);

Printf(“\t\tBook %d Author is=%s \n”,t,v[i].author);

Printf(“\t\tBook %d Pages is=%d \n”,t,v[i].pages);

Printf(“\t\tBook %d Price is=%f \n”,t,v[i].price);

Printf(“\n”);

}
}

49. Define a structure named "Date" to represent a date (day, month, and year).
Write a program to compare two dates using this structure and display which
date comes first.
#include<stdio.h>
Struct date {
Int dd, mm, yy;
};
Int date_cmp(struct date d1, struct date d2);
Void date_print(struct date d);
Int main() {
Struct date d1 = {7, 3, 2005};
Struct date d2 = {24, 10, 2005};
Date_print(d1);
Int cmp = date_cmp(d1, d2);
If(cmp == 0)
Printf(“ is equal to”);
Else if (cmp > 0)
Printf(“ is greater i.e. later than “);
Else
Printf(“ is smaller i.e. earlier than”);
Date_print(d2);
Return 0;
}
/* compare given dates d1 and d2 */
Int date_cmp(struct date d1, struct date d2) {
If (d1.dd == d2.dd && d1.mm == d2.mm && d1.yy ==d2.yy)
Return 0;
Else if (d1.yy > d2.yy || d1.yy == d2.yy && d1.mm > d2.mm ||
D1.yy == d2.yy && d1.mm == d2.mm && d1.dd > d2.dd)
Return 1;
Else return -1;
}
/* print a given date */
Void date_print(struct date d) {
Printf(“%d/%d/%d”, d.dd, d.mm, d.yy);
}
Output:
7/3/2005 is smaller i.e. earlier than 24/10/2005

50. Create a structure named "Student" to store student details such as name, roll
number, and marks in three subjects. Write a program to calculate the average
marks of a student using this structure.
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int rollno;
char name[20];
int m1,m2,m3;
float percent;
};
struct student s[20],t;
int i,j,n;
clrscr();
printf("\n enter the limit");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n enter the roll no\n");
scanf("%d",&s[i].rollno);
printf("\n enter the name \n");
scanf("%s",s[i].name);
printf("\n enter the mark=");
scanf("%d",&s[i].m1);
printf("\n enter the mark=");
scanf("%d",&s[i].m2);
printf("\n enter the mark=");
scanf("%d",&s[i].m3);
s[i].percent=(s[i].m1+s[i].m2+s[i].m3)/3;
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i].percent<s[j].percent)
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
}
}
printf("\n display in desending order\n");
for(i=0;i<n;i++)
{
printf("\n rollno=%d",s[i].rollno);
printf("\n name=%s",s[i].name);
printf("\n mark1=%d",s[i].m1);
printf("\n mark2=%d",s[i].m2);
printf("\n mark3=%d",s[i].m3);
printf("\n percent=%f",s[i].percent);
}
getch();
}

You might also like