Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Strucer Programming

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

Strucer Programming

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

Practice for Final

1. C Program To Check Prime Number By Creating a Function

// C Program to Check Prime Number using Simple Trial

// Division Approach

#include <stdio.h>

int isPrime(int N) {

// Check divisibility from 2 to N-1

for (int i = 2; i < N; i++) {

// If N is divisible by i, it is not a prime number

if (N % i == 0) {

return 0;

// If no divisors were found, N is a prime number

return 1;

int main() {

int N = 10;

printf("Is %d prime?\n", N);

// Check if the number is prime

if (isPrime(N)) {

printf("Yes\n");

}
else {

printf("No\n");

return 0;

2. C Program for Quadratic Equation Roots

// C program to find roots of

// a quadratic equation

#include <math.h>

#include <stdio.h>

#include <stdlib.h>

// Prints roots of quadratic

// equation ax*2 + bx + x

void findRoots(int a, int b, int c)

// If a is 0, then equation is

// not quadratic, but linear

if (a == 0) {

printf("Invalid");

return;

}
int d = b * b - 4 * a * c;

double sqrt_val = sqrt(abs(d));

if (d > 0) {

printf("Roots are real and different\n");

printf("%f\n%f", (double)(-b + sqrt_val) / (2 * a),

(double)(-b - sqrt_val) / (2 * a));

else if (d == 0) {

printf("Roots are real and same\n");

printf("%f", -(double)b / (2 * a));

else // d < 0

printf("Roots are complex\n");

printf("%f + i%f\n%f - i%f", -(double)b / (2 * a),

sqrt_val / (2 * a), -(double)b / (2 * a),

sqrt_val / (2 * a));

// Driver code

int main()

int a = 1, b = -7, c = 12;

// Function call

findRoots(a, b, c);
return 0;

3. C Program to Find Sum of Natural Numbers using Recursion

// C program to find the sum of n

// natural numbers using recursion

#include <stdio.h>

// Returns the sum of first n

// natural numbers

int recSum(int n)

// Base condition

if (n <= 1)

return n;

// Recursive call

return n + recSum(n - 1);

// Driver code

int main()

int n = 10;
printf("Sum = %d ", recSum(n));

return 0;

4. Find Factorial of a Number Using Recursion

// C program to find factorial of given number

// using recursion

#include <stdio.h>

unsigned int factorial(unsigned int n) {

// Base Case:

if (n == 1) {

return 1;

// Multiplying the current N with the previous product

// of Ns

return n * factorial(n - 1);

int main() {

int num = 5;
printf("Factorial of %d is %d", num, factorial(num));

return 0;

5. The series 0, 1, 1, 2, 3, 5, 8, 13, … is called the Fibonacci series. Here, termn=termn-1


+ termn 2, for n>1, term0 = 0, term1 = 1. Write a program that finds the sum of first
n terms of the series using recursion.

// C Program to print the Fibonacci series using recursion

#include <stdio.h>

// Recursive function to print the fibonacci series

void fib(int n, int prev1, int prev2) {

// Base Case: when n gets less than 3

if (n < 3) {

return;

int curr = prev1 + prev2;

prev2 = prev1;

prev1 = curr;

printf("%d ", curr);

return fib(n - 1, prev1, prev2);

// Function that handles the first two terms and calls the

// recursive function

void printFib(int n) {

// When the number of terms is less than 1

if (n < 1) {
printf("Invalid number of terms\n");

// When the number of terms is 1

else if (n == 1) {

printf("%d ", 0);

// When the number of terms is 2

else if (n == 2) {

printf("%d %d", 0, 1);

// When number of terms greater than 2

else {

printf("%d %d ", 0, 1);

fib(n, 0, 1);

return;

int main() {

int n = 9;

// Printing first 9 fibonacci series terms

printFib(n);

return 0;

6. C Program to Find GCD of Two Numbers Using Euclidean Algorithm

// C program to find GCD of two numbers


#include <stdio.h>

// Recursive function to return gcd of a and b

int gcd(int a, int b)

// Everything divides 0

if (a == 0)

return b;

if (b == 0)

return a;

// base case

if (a == b)

return a;

// a is greater

if (a > b)

return gcd(a - b, b);

return gcd(a, b - a);

// Driver program to test above function

int main()

int a = 98, b = 56;

printf("GCD of %d and %d is %d ", a, b, gcd(a, b));

return 0;

}
7. C Program to Find Largest Element in an Array

#include <stdio.h>

int findMax(int arr[], int n) {

// Assume the first element is the largest

int max = arr[0];

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

// Update max if arr[i] is greater

if (arr[i] > max) {

max = arr[i];

return max;

int main() {

int arr[] = {5, 2, 7, 6};

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

printf("%d\n", findMax(arr, n));

return 0;

8. Write a program in C to compute sin()


// C program to illustrate the sin() function

#include <math.h>

#include <stdio.h>

int main()

double angle1 = 3.1415926;

double angle2 = 10;

// printing the sine value of angle1 and angle2

printf("sin(3.14) = %.2lf\n", sin(angle1));

printf("sin(10) = %.2lf", sin(angle2));

return 0;

9. C Program to Sort the Elements of an Array in Descending Order

#include <stdio.h>

#include <stdlib.h>

// Comparator function to sort in descending order

int comp(const void *a, const void *b) {

return (*(int*)b - *(int*)a);

}
int main() {

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

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

// Sorting the array using qsort

qsort(arr, n, sizeof(int), comp);

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

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

return 0;

10. Write a program in C to sort an array in descending order using Bubble Sort

#include <stdio.h>

// Bubble sort implementation

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

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

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

if (arr[j] < arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

}
int main() {

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

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

// Perform bubble sort

sort(arr, n);

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

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

return 0;

11. C Program to Sort an Array in Ascending Order

#include <stdio.h>

#include <stdlib.h>

// Custom comparator

int comp(const void* a, const void* b) {

// If a is smaller, positive value will be returned

return (*(int*)a - *(int*)b);

int main() {

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

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

// Sort the array using qsort

qsort(arr, n, sizeof(int), comp);


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

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

return 0;

12. C Program to Sort an Array in Ascending Order using Bubble Sort

#include <stdio.h>

// Bubble sort implementation

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

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

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

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

int main() {

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

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

// Perform bubble sort

bubbleSort(arr,n);
for (int i = 0; i < n; i++)

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

return 0;

13. C Program to Find Determinant of a Matrix

// C program to find Determinant

// of a matrix

#include <stdio.h>

// Dimension of input square matrix

#define N 4

// Function to get cofactor of mat[p][q]

// in temp[][]. n is current dimension

// of mat[][]

void getCofactor(int mat[N][N], int temp[N][N],

int p, int q, int n)

int i = 0, j = 0;

// Looping for each element of the matrix

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

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

// Copying into temporary matrix


// only those element which are

// not in given row and column

if (row != p && col != q)

temp[i][j++] = mat[row][col];

// Row is filled, so increase row

// index and reset col index

if (j == n - 1)

j = 0;

i++;

/* Recursive function for finding the

determinant of matrix. n is current

dimension of mat[][]. */

int determinantOfMatrix(int mat[N][N], int n)

// Initialize result

int D = 0;

// Base case : if matrix contains

// single element
if (n == 1)

return mat[0][0];

// To store cofactors

int temp[N][N];

// To store sign multiplier

int sign = 1;

// Iterate for each element of

// first row

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

// Getting Cofactor of mat[0][f]

getCofactor(mat, temp, 0, f, n);

D += sign * mat[0][f]

* determinantOfMatrix(temp, n - 1);

// Terms are to be added with alternate sign

sign = -sign;

return D;

// Function for displaying the matrix

void display(int mat[N][N],

int row, int col)


{

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

for (int j = 0; j < col; j++)

printf(" %d", mat[i][j]);

printf("n");

// Driver code

int main()

int mat[N][N] = {{1, 0, 2, -1},

{3, 0, 0, 5},

{2, 1, 4, -3},

{1, 0, 5, 0}};

// Function call

printf("Determinant of the matrix is : %d",

determinantOfMatrix(mat, N));

return 0;

14. C Program to Add Two Square Matrices

// C program to implement

// the above approach

#include <stdio.h>

#define N 4
// This function adds A[][] and B[][],

// and stores the result in C[][]

void add(int A[][N], int B[][N], int C[][N])

int i, j;

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

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

C[i][j] = A[i][j] + B[i][j];

// This function prints the matrix

void printmatrix(int D[][N])

int i, j;

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

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

printf("%d ", D[i][j]);

printf("\n");

// Driver code

int main()

int A[N][N] = { { 1, 1, 1, 1 },

{ 2, 2, 2, 2 },

{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };

int B[N][N] = { { 1, 1, 1, 1 },

{ 2, 2, 2, 2 },

{ 3, 3, 3, 3 },

{ 4, 4, 4, 4 } };

// To store result

int C[N][N];

int i, j;

printf("Matrix A is \n");

printmatrix(A);

printf("Matrix B is \n");

printmatrix(B);

add(A, B, C);

printf("Result matrix is \n");

printmatrix(C);

return 0;

}
15. C Program to Add Two Rectangular Matrices

// C program to implement

// the above approach

#include <stdio.h>

#define M 4

#define N 3

// This function adds A[][] and B[][],

// and stores the result in C[][]

void add(int A[M][N], int B[M][N], int C[M][N])

int i, j;
for (i = 0; i < M; i++)

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

C[i][j] = A[i][j] + B[i][j];

// This function prints the matrix

void printmatrix(int D[M][N])

int i, j;

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

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

printf("%d ", D[i][j]);

printf("\n");

// Driver code

int main()

int A[M][N] = {

{ 1, 1, 1 }, { 2, 2, 2 }, { 3, 3, 3 }, { 4, 4, 4 }

};

int B[M][N] = {

{ 2, 1, 1 }, { 1, 2, 2 }, { 2, 3, 3 }, { 3, 4, 4 }

};

printf("Matrix A is \n");
printmatrix(A);

printf("Matrix B is \n");

printmatrix(B);

// To store result

int C[M][N];

int i, j;

add(A, B, C);

printf("Result matrix is \n");

printmatrix(C);

return 0;

}
16. C Program to Multiply Two Matrices

// C program to multiply two matrices

#include <stdio.h>

#include <stdlib.h>

// matrix dimensions so that we dont have to pass them as

// parametersmat1[R1][C1] and mat2[R2][C2]

#define R1 2 // number of rows in Matrix-1

#define C1 2 // number of columns in Matrix-1

#define R2 2 // number of rows in Matrix-2

#define C2 3 // number of columns in Matrix-2

void multiplyMatrix(int m1[][C1], int m2[][C2])


{

int result[R1][C2];

printf("Resultant Matrix is:\n");

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

for (int j = 0; j < C2; j++) {

result[i][j] = 0;

for (int k = 0; k < R2; k++) {

result[i][j] += m1[i][k] * m2[k][j];

printf("%d\t", result[i][j]);

printf("\n");

// Driver code

int main()

// R1 = 4, C1 = 4 and R2 = 4, C2 = 4 (Update these

// values in MACROs)

int m1[R1][C1] = { { 1, 1 }, { 2, 2 } };

int m2[R2][C2] = { { 1, 1, 1 }, { 2, 2, 2 } };
// if coloumn of m1 not equal to rows of m2

if (C1 != R2) {

printf("The number of columns in Matrix-1 must be "

"equal to the number of rows in "

"Matrix-2\n");

printf("Please update MACROs value according to "

"your array dimension in "

"#define section\n");

exit(EXIT_FAILURE);

// Function call

multiplyMatrix(m1, m2);

return 0;

17. C Program to Concatenate Two Strings Without Using strcat

#include <stdio.h>

void concat(char *s1, char *s2) {

int i = 0;
// Move to the end of str1

while (s1[i] != '\0')

i++;

// Copy characters from str2 to str1

int j = 0;

while (s2[j] != '\0') {

s1[i] = s2[j];

i++;

j++;

// Null-terminate the concatenated string

s1[i] = '\0';

int main() {

char s1[50] = "Hello ";

char s2[] = "Geeks";

concat(s1, s2);

printf("%s", s1);

return 0;

}
18. C Program to Concatenate Two Strings using Pointers

#include <stdio.h>

void concat(char *s1, char *s2) {

// Move the pointer to the end of str1

while (*s1)

s1++;

// Copy characters from s1 to s1 using

// pointer arithmetic

while (*s2) {

*s1 = *s2;

s1++;

s2++;

*s1 = '\0';

int main() {

char s1[50] = "Hello ";

char s2[] = "Geeks";

// Concat string s1 and s2

concat(s1, s2);

printf("%s", s1);
return 0;

19. Write a program in C to check if a string is Palindrome or not

#include <stdio.h>

#include <string.h>

int main() {

char string1[20];

int i, length;

int flag = 0;

// Prompt the user for input

printf("Enter a string: ");

scanf("%s", string1);

// Calculate the string length

length = strlen(string1);

// Compare characters from the start and end of the string

// and stop if a mismatch is found or the middle of the string is reached.

for (i = 0; i < length / 2; i++) {

if (string1[i] != string1[length - i - 1]) {

flag = 1;

break;

// Output the result


if (flag) {

printf("%s is not a palindrome\n", string1);

} else {

printf("%s is a palindrome\n", string1);

return 0;

20. Write a program to reverse an array

#include <stdio.h>

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

// Two pointers

int l = 0, r = n - 1;

while (l < r) {

// Swap the elements

int temp = arr[l];

arr[l] = arr[r];

arr[r] = temp;

// Move pointers towards middle

l++;

r--;

int main() {
int arr[] = {1, 2, 3, 4, 5};

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

// Reverse array arr

rev(arr, n);

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

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

return 0;

21. Write a program to reverse an array using Recursion

#include <stdio.h>

void rev(int arr[], int l, int r) {

if (l >= r) {

return;

// Swap the elements

int temp = arr[l];

arr[l] = arr[r];

arr[r] = temp;

// Recursively call function to reverse the

// remaining part

rev(arr, l + 1, r - 1);

}
int main() {

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

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

// Reverse the array arr

rev(arr, 0, n - 1);

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

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

return 0;

22. C Program to Find the Length of a String

#include <stdio.h>

#include <string.h>

int main() {

char s[] = "Geeks";

// Find length of string using strlen()

printf("%lu", strlen(s));

return 0;

23. C Program to Find Largest Element in an Array using Pointers

// C program for the above approach

#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;

24. C program to sort an array using pointers

#include <stdio.h>

// Function to sort the numbers using pointers


void sort(int n, int* ptr)

int i, j, t;

// Sort the numbers using pointers

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

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

if (*(ptr + j) < *(ptr + i)) {

t = *(ptr + i);

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

*(ptr + j) = t;

// print the numbers

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

printf("%d ", *(ptr + i));

// Driver code

int main()

int n = 5;

int arr[] = { 0, 23, 14, 12, 9 };


sort(n, arr);

return 0;

25. Check if a string is palindrome in C using pointers

// C program to check if a string is palindrome

// using pointers

#include <stdio.h>

// Function to check if the string is palindrome

// using pointers

void isPalindrome(char* string)

char *ptr, *rev;

ptr = string;

while (*ptr != '\0') {

++ptr;

--ptr;

for (rev = string; ptr >= rev;) {

if (*ptr == *rev) {

--ptr;

rev++;
}

else

break;

if (rev > ptr)

printf("String is Palindrome");

else

printf("String is not a Palindrome");

// Driver code

int main()

char str[1000] = "madam";

isPalindrome(str);

return 0;

26. C Program to Store Information of Students Using Structure

// C Program to Store Information of Students Using Structure

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// Create the student structure

struct Student {
char* name;

int roll_number;

int age;

double total_marks;

};

int main() {

// Create an array of student structure variable with

// 5 Student's records

struct Student students[5];

int n = sizeof(students)/sizeof(struct Student);

// Get the students data

students[0].roll_number = 1;

students[0].name = "Geeks1";

students[0].age = 12;

students[0].total_marks = 78.50;

students[1].roll_number = 5;

students[1].name = "Geeks5";

students[1].age = 10;

students[1].total_marks = 56.84;

students[2].roll_number = 2;

students[2].name = "Geeks2";

students[2].age = 11;

students[2].total_marks = 87.94;
students[3].roll_number = 4;

students[3].name = "Geeks4";

students[3].age = 12;

students[3].total_marks = 89.78;

students[4].roll_number = 3;

students[4].name = "Geeks3";

students[4].age = 13;

students[4].total_marks = 78.55;

// Print the Students information

printf("========================================\n");

printf(" Student Records \n");

printf("========================================\n");

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

printf("\nStudent %d:\n", i + 1);

printf(" Name : %s\n", students[i].name);

printf(" Roll Number : %d\n", students[i].roll_number);

printf(" Age : %d\n", students[i].age);

printf(" Total Marks : %.2f\n", students[i].total_marks);

printf("========================================\n");

return 0;

}
27. C program to store Student records as Structures and Sort them by Name

// C program to read Student records

// like id, name and age,

// and display them in sorted order by Name

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// struct person with 3 fields

struct Student {

char* name;

int id;

char age;

};

// setting up rules for comparison

// to sort the students based on names

int comparator(const void* p, const void* q)

return strcmp(((struct Student*)p)->name,

((struct Student*)q)->name);

// Driver program

int main()

int i = 0, n = 5;
struct Student arr[n];

// Get the students data

arr[0].id = 1;

arr[0].name = "bd";

arr[0].age = 12;

arr[1].id = 2;

arr[1].name = "ba";

arr[1].age = 10;

arr[2].id = 3;

arr[2].name = "bc";

arr[2].age = 8;

arr[3].id = 4;

arr[3].name = "aaz";

arr[3].age = 9;

arr[4].id = 5;

arr[4].name = "az";

arr[4].age = 10;

// Print the Unsorted Structure

printf("Unsorted Student Records:\n");

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

printf("Id = %d, Name = %s, Age = %d \n",


arr[i].id, arr[i].name, arr[i].age);

// Sort the structure

// based on the specified comparator

qsort(arr, n, sizeof(struct Student), comparator);

// Print the Sorted Structure

printf("\n\nStudent Records sorted by Name:\n");

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

printf("Id = %d, Name = %s, Age = %d \n",

arr[i].id, arr[i].name, arr[i].age);

return 0;

28. C program to store Student records as Structures and Sort them by Age or ID

// C program to read Student records

// like id, name and age,

// and display them in sorted order by Age

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// struct person with 3 fields

struct Student {

char* name;

int id;
char age;

};

// setting up rules for comparison

// to sort the students based on age

int comparator(const void* p, const void* q)

return (((struct Student*)p)->age - ((struct Student*)q)->age);

// Driver program

int main()

int i = 0, n = 5;

struct Student arr[n];

// Get the students data

arr[0].id = 1;

arr[0].name = "bd";

arr[0].age = 12;

arr[1].id = 2;

arr[1].name = "ba";

arr[1].age = 10;

arr[2].id = 3;

arr[2].name = "bc";
arr[2].age = 8;

arr[3].id = 4;

arr[3].name = "aaz";

arr[3].age = 9;

arr[4].id = 5;

arr[4].name = "az";

arr[4].age = 10;

// Print the Unsorted Structure

printf("Unsorted Student Records:\n");

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

printf("Id = %d, Name = %s, Age = %d \n",

arr[i].id, arr[i].name, arr[i].age);

// Sort the structure

// based on the specified comparator

qsort(arr, n, sizeof(struct Student), comparator);

// Print the Sorted Structure

printf("\n\nStudent Records sorted by Age:\n");

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

printf("Id = %d, Name = %s, Age = %d \n",

arr[i].id, arr[i].name, arr[i].age);

return 0;

You might also like