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

cp 3 to 9

Uploaded by

Parv Agrawal
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)
25 views

cp 3 to 9

Uploaded by

Parv Agrawal
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/ 66

Assignment 3 – 9

Submitted By
NAME OF THE STUDENT ENROLLMENT NO.
PARV AGRAWAL BTCS24O1090
3rd assignment
 Write a C program for printing prime factors of a number using functions.

ANSWER –

#include <stdio.h>
void primeFactors(int n)
{
while (n % 2 == 0) {
printf("%d ", 2);
n = n / 2;
}
for (int i = 3; i * i <= n; i = i + 2) {
while (n % i == 0) {
printf("%d ", i);
n = n / i;
}
}
if (n > 2)
printf("%d ", n);
}

int main()
{
int n;
printf(" enter the number for which you want to find prime factors n : ");
scanf("%d",&n);
primeFactors(n);
return 0;
}
OUTPUT
enter the number for which you want to find prime factors n : 225
3355

 Write a C program for printing prime numbers between a interval.

ANSWER –

#include <stdio.h>

int main()
{
int a, b, i, j, flag;
printf("Enter lower bound of the interval: ");
scanf("%d", &a);
printf("Enter upper bound of the interval: ");
scanf("%d", &b);
printf("Prime numbers between %d and %d are: ", a, b);
for (i = a; i <= b; i++)
{
if (i == 1 || i == 0)
continue;
flag = 1;
for (j = 2; j <= i / 2; ++j)
{
if (i % j == 0)
{
flag = 0;
break;
}
}
if (flag == 1)
printf("%d ", i);
}
return 0;
}

OUTPUT

Enter lower bound of the interval: 5

Enter upper bound of the interval: 125

Prime numbers between 5 and 125 are: 5 7 11 13 17 19 23 29 31 37 41 43


47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113

 Write a C program to convert decimal to binary numbers & vice versa.

ANSWER

1) DECIMAL TO BINARY NUMBER

#include <stdio.h>

int decToBinary(int n)
{
int binaryNum[32];
int i = 0;
while (n > 0) {
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
for (int j = i - 1; j >= 0; j--)
printf("%d", binaryNum[j]);
return binaryNum;
}
int main()
{
int n ;
decToBinary(n);
printf("enter the number which yo want to covert binary : ");
scanf("%d",&n);
printf(" %d " , decToBinary(n));
return 0;
}

OUTPUT

enter the number which yo want to covert binary : 8

1000

2) BINARY NUMBER TO DECIMAL

#include <stdio.h>

#include <math.h>

int binaryToDecimal(int n) {

int decimal = 0, i = 0, remainder;

while (n != 0) {

remainder = n % 10;
decimal += remainder * pow(2, i);

n = n / 10;

i++;

return decimal;

int main() {

int binary, decimal;

printf("Enter a binary number: ");

scanf("%d", &binary);

decimal = binaryToDecimal(binary);

printf("Decimal equivalent: %d\n", decimal);

return 0;

OUTPUT

enter the number which yo want to covert decimal number : 10000

16.
 Write a C program to convert octal to binary & vice versa.
ANSWER
1) OCTAL TO BINARY

#include <stdio.h>

#include <stdio.h>
void octalToBinary(int octal) {
int binary[32];
int i = 0;
if (octal == 0) {
printf("Binary: 000\n");
return;
}
while (octal != 0) {
int octal_digit = octal % 10;
switch(octal_digit) {
case 0: printf("000"); break;
case 1: printf("001"); break;
case 2: printf("010"); break;
case 3: printf("011"); break;
case 4: printf("100"); break;
case 5: printf("101"); break;
case 6: printf("110"); break;
case 7: printf("111"); break;
}
octal = octal / 10;
}
printf("\n");
}

int main() {
int octal;
printf("Enter an octal number: ");
scanf("%d", &octal);

printf("Binary equivalent: ");


octalToBinary(octal);
return 0;
}

OUTPUT
Enter an octal number: 125467
Binary equivalent: 2101502239

2) CONVERT BINARY TO OCTAL

#include <stdio.h>
int main()
{
long int binary_number, octal_number = 0, j = 1, remainder;

printf("Enter the value for binary number: ");


scanf("%ld", &binary_number);
while (binary_number != 0)
{
remainder = binary_number % 10;
octal_number = octal_number + remainder * j;
j = j * 2;
binary_number = binary_number / 10;
}
printf("Equivalent octal value: %lo", octal_number);
return 0;
}
OUTPUT

Enter the value for binary number: 10001010

Equivalent octal value: 212

 Write a C program to find mean, median, mode.


ANSWER

#include <stdio.h>
void findMeanMedianMode(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
float mean = (float)sum / n;
int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
float median;
if (n % 2 == 0) {
median = (arr[n / 2 - 1] + arr[n / 2]) / 2.0;
} else {
median = arr[n / 2];
}
int mode = arr[0];
int count = 1;
int maxCount = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) {
count++;
} else {
if (count > maxCount) {
maxCount = count;
mode = arr[i - 1];
}
count = 1;
}
}
printf("Mean: %.2f\n", mean);
printf("Median: %.2f\n", median);
printf("Mode: %d\n", mode);
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
findMeanMedianMode(arr, n);
return 0;
}

OUTPUT

Enter the number of elements: 10

Enter 10 elements:

10

20

30

40

45

50

60
78

110

Mean: 45.20

Median: 42.50

Mode: 9

4th assignment
 Write a program in C to make such a pattern like a right angle triangle
with a number, which will repeat a number in a row.

ANSWER

#include <stdio.h>

int main() {
int i, j, rows;

printf("Input number of rows : ");


scanf("%d", &rows);

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


for (j = 1; j <= i; j++)
printf("%d", i);
printf("\n");
}return 0;
}

OUTPUT

Input number of rows : 10

22

333

4444

55555

666666

7777777

88888888

999999999

10101010101010101010

 Write a program in C to make a pyramid pattern with numbers increased


by 1.

ANSWER

include <stdio.h>

int main() {
int rows;

// Take number of rows as input from the user


printf("Enter the number of rows: ");
scanf("%d", &rows);

int number = 1; // To control the number to be printed in the pyramid

// Outer loop for each row


for (int i = 1; i <= rows; i++) {
// Inner loop for spaces
for (int j = 1; j <= rows - i; j++) {
printf(" "); // Printing spaces
}

// Inner loop for printing numbers in each row


for (int k = 1; k <= i; k++) {
printf("%d ", number); // Printing the number
number++; // Increment the number
}

// Move to the next line after each row


printf("\n");
}

return 0;
}

OUTPUT
1

23

456

7 8 9 10

11 12 13 14 15

16 17 18 19 20 21

22 23 24 25 26 27 28

 Write a program in C to print Floyd's Triangle.


ANSWER

#include <stdio.h>

int main() {
int rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {

if ((i + j) % 2 == 0) {
printf("1");
} else {
printf("0");
}
}
printf("\n");
}
return 0;
}

OUTPUT
Input number of rows : 7
1
01
101
0101
10101
010101
1010101

 Write a program in C to display a pattern like a diamond.

ANSWER

#include <stdio.h>

int main() {
int n;
printf("Enter the number of rows: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n - i; j++) {
printf(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
printf("*");
}
printf("\n");
}
for (int i = n - 1; i >= 1; i--) {
for (int j = 1; j <= n - i; j++) {
printf(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
printf("*");
}
printf("\n");
}

return 0;
}

OUTPUT

Input number of rows (half of the diamond) :4


*
***
*****
*******
*****
***
*

 Write a C program to display Pascal's triangle.

ANSWER

#include <stdio.h>
int main() {

int n;

printf("Enter the number of rows: ");

scanf("%d", &n);

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

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

printf(" ");

int number = 1;

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

printf("%d ", number);

number = number * (i - j) / (j + 1);

printf("\n");

return 0;

OUTPUT

Input number of rows: 5


1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

5th assignment
 Write a program in C to check whether a number can be expressed as the
sum of two prime numbers.

ANSWER

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int check_primenumber(int n){
int i , prime = 1;
if (n==0 || n==1)
{
prime =0;}
else{
for ( i = 2; i < n/2; i++)
{
if (n%i==0)
{
prime=0;
break;
}
}
} return prime;
}
int main()
{
int n, flag= 0 ;
printf(" enter the number you want to express as sum of two prime numbers \
n");
scanf("%d",&n);
for ( int i = 2; i < n/2; i++)
{
if ((check_primenumber(i)==1))
{
if ((check_primenumber(n-i)==1))
{
printf("%d=%d+%d \n",n,i,n-i);
}
}
}
if (flag = 0){
printf("not a sum of two prime numbers");
}
return 0;
}
OUTPUT

enter the number you want to express as sum of two prime numbers

28

28=5+23

28=11+17

 Write a C program to check whether a number is a Strong Number or not.

ANSWER

#include <stdio.h>
void main()
{
int i, n, n1, s1 = 0, j;
long fact

printf("\n\nCheck whether a number is Strong Number or not:\n ");


printf("Input a number to check whether it is Strong number: ");
scanf("%d", &n);
n1 = n;
for (j = n; j > 0; j = j / 10)
{
fact = 1;
for (i = 1; i <= j % 10; i++)
{
fact = fact * i;
}
s1 = s1 + fact; .
}
if (s1 == n1)
{
printf("\n%d is Strong number.\n\n", n1);
}
else
{
printf("\n%d is not Strong number.\n\n", n1);
}
}

OUTPUT

Check whether a number is Strong Number or not:

Input a number to check whether it is Strong number: 145

145 is Strong number.

 Write C program to convert binary to hexadecimal & vice versa.

ANSWER

1) BINARY TO HEXADECIMAL

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

int main()
{
int hexConstant[] = {0, 1, 10, 11, 100, 101, 110, 111, 1000,
1001, 1010, 1011, 1100, 1101, 1110, 1111};

long long binary, tempBinary;


char hex[20];
int index, i, digit;

/* Input binary number from user */


printf("Enter binary number: ");
scanf("%lld", &binary);
tempBinary = binary;
index = 0;
while(tempBinary!=0)
{
digit = tempBinary % 10000;
for(i=0; i<16; i++)
{
if(hexConstant[i] == digit)
{
if(i<10)
{
hex[index] = (char)(i + 48);
}
else
{
hex[index] = (char)((i-10) + 65);
}
index++;
break;
}
}
tempBinary /= 10000;
}
hex[index] = '\0';
strrev(hex);
printf("Binary number = %lld\n", binary);
printf("Hexadecimal number = %s", hex);
return 0;
}

OUTPUT

Enter binary number: 10100001

Binary number = 10100001

Hexadecimal number = A1

2) HEXADECIMAL TO BINARY

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

void hexToBinary(char hex[]) {


int length = strlen(hex);

printf("Binary equivalent: ");


for (int i = 0; i < length; i++) {
switch (hex[i]) {
case '0': printf("0000 "); break;
case '1': printf("0001 "); break;
case '2': printf("0010 "); break;
case '3': printf("0011 "); break;
case '4': printf("0100 "); break;
case '5': printf("0101 "); break;
case '6': printf("0110 "); break;
case '7': printf("0111 "); break;
case '8': printf("1000 "); break;
case '9': printf("1001 "); break;
case 'A': case 'a': printf("1010 "); break;
case 'B': case 'b': printf("1011 "); break;
case 'C': case 'c': printf("1100 "); break;
case 'D': case 'd': printf("1101 "); break;
case 'E': case 'e': printf("1110 "); break;
case 'F': case 'f': printf("1111 "); break;
default:
printf("\nInvalid hexadecimal digit '%c'.\n", hex[i]);
return;
OUTPUT

Enter any hexadecimal number: AA1

Hexademial number = AA1

Binary number = 101010100001

 Write a program in C to find the number and sum of all integers between
100 and 200 which are divisible by 9.
ANSWER

#include <stdio.h>
int main (){
int i , a= 0;
for ( i = 100 ; i < 201; i++)
{
if (i %9 == 0 )
{
a=a+i;
}
}
printf(" The sum of all divisible integers from 100 to 200 is = %d",a);
return 0;
}
OUTPUT

The sum of all divisible integers from 100 to 200 is = 1683

 Write a program to find out the second largest factor of a number.


ANSWER

#include <stdio.h>
int main(){
int n;
printf("enter a number for which you want to find second highest factor : ");
scanf("%d",&n);
for (int i = n/2; i >=1 ; i--)
{
if (n%i==0 && i<n){
printf("%d ",i);
break;
}
}

return 0;
}
OUTPUT

enter a number for which you want to find second highest factor : 145

29

6th assignment
 Write a C Program to Find the Maximum and Minimum in an Array.
ANSWER

#include <stdio.h>

int main() {
int n, i, max, min;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
max = arr[0];
min = arr[0];
for (i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
printf("Maximum element: %d\n", max);
printf("Minimum element: %d\n", min);

return 0;
}

OUTPUT

Input the number of elements to be stored in the array :10


Input 10 elements in the array :

element - 0 : 5

element - 1 : 10

element - 2 : 15

element - 3 : 20

element - 4 : 46

element - 5 : 13

element - 6 : 16

element - 7 : 4548

element - 8 : 16

element - 9 : 4

Maximum element is : 4548

Minimum element is : 4
 Write C Program to Find the Largest Element in an Array.
Answer

#include <stdio.h>
int main() {
int array[n];
int i,max, n;
printf("Input the number of elements to be stored in the array :");
scanf("%d", &n);
printf("Input %d elements in the array :\n", n);
for (i = 0; i < 10; i++) {
scanf("%d", &array[i]);
}
max = array[0];
for (i = 1; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
}
printf("The maximum value in the array is: %d\n", max);
return 0;
}

OUTPUT

Input the number of elements to be stored in the array :12

Input 12 elements in the array :

15
16

14

17

44

49

46

13

464

155

The maximum value in the array is : 464


 Write C Program to Search an Element in an Array

ANSWER

#include <stdio.h>

int main() {

int n, i, key, found = 0;

printf("Enter the number of elements in the array: ");

scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n);

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

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

printf("Enter the element to search: ");

scanf("%d", &key);

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

if (arr[i] == key) {

found = 1;

printf("Element %d found at index %d (position %d).\n", key, i, i + 1);

break;

}
if (!found) {

printf("Element %d not found in the array.\n", key);

return 0;

OUTPUT

Element Found at Position: 6

 Write a C Program to find all pairs in array of integers whose sum is


equal to given number.

Answer

#include <stdio.h>

Void findPairs(int arr[], int n, int target) {

Printf(“Pairs with sum %d are:\n”, target);

Int found = 0;

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

For (int j = I + 1; j < n; j++) {

If (arr[i] + arr[j] == target) {

Printf(“(%d, %d)\n”, arr[i], arr[j]);

Found = 1;

}
}

If (!found) {

Printf(“No pairs found.\n”);

Int main() {

Int arr[] = {1, 4, 6, 8, 10, 12};

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

Int target;

Printf(“Enter the target sum: “);

Scanf(“%d”, &target);

findPairs(arr, n, target);

return 0;

OUTPUT

Pairs with sum 16 are:

(6, 10)

(4, 12)

 Write a C program for calculating the factorial of a number.


Answer

#include <stdio.h>

Long long factorial(int n) {

If (n == 0 || n == 1)

Return 1; // Base case

Return n * factorial(n – 1);

Int main() {

Int num;

Printf(“Enter a number to calculate its factorial: “);

Scanf(“%d”, &num);

If (num < 0) {

Printf(“Factorial is not defined for negative numbers.\n”);

} else {

Printf(“The factorial of %d is %lld\n”, num, factorial(num));

Return 0;

Output
Enter a number to calculate its factorial: 5

The factorial of 5 is 120

7th assignment

 Write a C program to generate fibonacci numbers and to find out if a


given number is a fibonacci number or not.

Answer

#include <stdio.h>

#include <stdbool.h>

Void generateFibonacci(int n) {

Int a = 0, b = 1, next;

Printf(“Fibonacci series up to %d: “, n);

While (a <= n) {

Printf(“%d “, a);

Next = a + b;

A = b;

B = next;

Printf(“\n”);

}
Bool isFibonacci(int num) {

If (num < 0) return false;

Int a = 0, b = 1, next;

While (a < num) {

Next = a + b;

A = b;

B = next;

Return (a == num);

Int main() {

Int num, limit;

Printf(“Enter the limit for Fibonacci series: “);

Scanf(“%d”, &limit);

generateFibonacci(limit);

Printf(“Enter a number to check if it is a Fibonacci number: “);

Scanf(“%d”, &num);

If (isFibonacci(num)) {

Printf(“%d is a Fibonacci number.\n”, num);

} else {

Printf(“%d is not a Fibonacci number.\n”, num);

}
Return 0;

Output
Enter the limit to generate Fibonacci numbers: 100
Fibonacci numbers up to 100:
0 1 1 2 3 5 8 13 21 34 55 89

Enter a number to check if it’s a Fibonacci number: 13


13 is a Fibonacci number.

 Write C programs to check, if an integer is a power of 2 or not in a


single line.

Answer

#include <stdio.h>

Int main() {

Int num;
Printf(“Enter a number: “);

Scanf(“%d”, &num);

Printf(“%d is %s a power of 2\n”, num, (num > 0 && (num & (num – 1)) ==
0) ? “” : “not”);

Return 0;

Output

Enter a number: 8

8 is a power of 2

Enter a number: 10

10 is not a power of 2

 Write code to remove duplicates in a sorted array.


Answer
#include <stdio.h>
Int removeDuplicates(int arr[], int n) {
If (n == 0 || n == 1)
Return n;

Int j = 0;
For (int I = 0; I < n – 1; i++) {
If (arr[i] != arr[I + 1]) {
Arr[j++] = arr[i];
}
}
Arr[j++] = arr[n – 1];
Return j;
}

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

N = removeDuplicates(arr, n);

Printf(“Array after removing duplicates:\n”);


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

Return 0;
}

Output

Input array {1,2,2,3,3,3,4,4,4,5,5,6,6}


Array after removing duplicates:
123456
 Write C code to dynamically allocate one, two and three dimensional
arrays using malloc.
Answer
#include <stdio.h>
#include <stdlib.h>

Int main() {
Int I, j, k;
Int size1D, size2D_rows, size2D_cols, size3D_x, size3D_y, size3D_z;

// Dynamic allocation for 1D array


Printf(“Enter the size of 1D array: “);
Scanf(“%d”, &size1D);
Int* arr1D = (int*)malloc(size1D * sizeof(int));

If (arr1D == NULL) {
Printf(“Memory allocation failed for 1D array\n”);
Return -1;
}

// Initializing and printing 1D array


Printf(“Enter elements for 1D array:\n”);
For (I = 0; I < size1D; i++) {
Scanf(“%d”, &arr1D[i]);
}
Printf(“1D Array elements are:\n”);
For (I = 0; I < size1D; i++) {
Printf(“%d “, arr1D[i]);
}
Printf(“\n”);
// Dynamic allocation for 2D array
Printf(“Enter the number of rows and columns for 2D array: “);
Scanf(“%d %d”, &size2D_rows, &size2D_cols);
Int** arr2D = (int**)malloc(size2D_rows * sizeof(int*));

If (arr2D == NULL) {
Printf(“Memory allocation failed for 2D array\n”);
Free(arr1D); // Free previously allocated memory
Return -1;
}

For (I = 0; I < size2D_rows; i++) {


Arr2D[i] = (int*)malloc(size2D_cols * sizeof(int));
If (arr2D[i] == NULL) {
Printf(“Memory allocation failed for row %d of 2D array\n”, i);
Free(arr1D);
For (int k = 0; k < I; k++) {
Free(arr2D[k]);
}
Free(arr2D);
Return -1;
}
}

// Initializing and printing 2D array


Printf(“Enter elements for 2D array:\n”);
For (I = 0; I < size2D_rows; i++) {
For (j = 0; j < size2D_cols; j++) {
Scanf(“%d”, &arr2D[i][j]);
}
}
Printf(“2D Array elements are:\n”);
For (I = 0; I < size2D_rows; i++) {
For (j = 0; j < size2D_cols; j++) {
Printf(“%d “, arr2D[i][j]);
}
Printf(“\n”);
}

// Dynamic allocation for 3D array


Printf(“Enter the dimensions for 3D array (x y z): “);
Scanf(“%d %d %d”, &size3D_x, &size3D_y, &size3D_z);
Int*** arr3D = (int***)malloc(size3D_x * sizeof(int**));

If (arr3D == NULL) {
Printf(“Memory allocation failed for 3D array\n”);
Free(arr1D);
For (I = 0; I < size2D_rows; i++) {
Free(arr2D[i]);
}
Free(arr2D);
Return -1;
}

For (I = 0; I < size3D_x; i++) {


Arr3D[i] = (int**)malloc(size3D_y * sizeof(int*));
If (arr3D[i] == NULL) {
Printf(“Memory allocation failed for 2D slice %d of 3D array\n”, i);
Free(arr1D);
For (int k = 0; k < size2D_rows; k++) {
Free(arr2D[k]);
}
Free(arr2D);
For (int m = 0; m < I; m++) {
Free(arr3D[m]);
}
Free(arr3D);
Return -1;
}
For (j = 0; j < size3D_y; j++) {
Arr3D[i][j] = (int*)malloc(size3D_z * sizeof(int));
If (arr3D[i][j] == NULL) {
Printf(“Memory allocation failed for 3D slice[%d][%d]\n”, I, j);
Free(arr1D);
For (int k = 0; k < size2D_rows; k++) {
Free(arr2D[k]);
}
Free(arr2D);
For (int m = 0; m < I; m++) {
For (int n = 0; n < size3D_y; n++) {
Free(arr3D[m][n]);
}
Free(arr3D[m]);
}
Free(arr3D);
Return -1;
}
}
}

// Initializing and printing 3D array


Printf(“Enter elements for 3D array:\n”);
For (I = 0; I < size3D_x; i++) {
For (j = 0; j < size3D_y; j++) {
For (k = 0; k < size3D_z; k++) {
Scanf(“%d”, &arr3D[i][j][k]);
}
}
}
Printf(“3D Array elements are:\n”);
For (I = 0; I < size3D_x; i++) {
For (j = 0; j < size3D_y; j++) {
For (k = 0; k < size3D_z; k++) {
Printf(“%d “, arr3D[i][j][k]);
}
Printf(“\n”);
}
}

// Free dynamically allocated memory


Free(arr1D);
For (I = 0; I < size2D_rows; i++) {
Free(arr2D[i]);
}
Free(arr2D);
For (I = 0; I < size3D_x; i++) {
For (j = 0; j < size3D_y; j++) {
Free(arr3D[i][j]);
}
Free(arr3D[i]);
}
Free(arr3D);

Return 0;
}

Output
Enter the size of 1D array: 5
Enter elements for 1D array:
12345
1D Array elements are:
12345
Enter the number of rows and columns for 2D array: 2 3
Enter elements for 2D array:
123
456
2D Array elements are:
123
456

Enter the dimensions for 3D array (x y z): 2 2 2


Enter elements for 3D array:
12
34
56
78
3D Array elements are:
12
34
56
78

 Write C code to return a string from a function.

Answer

#include <stdio.h>

void getGreeting(char* buffer, int size) {

// Fill the buffer with the string, ensuring it doesn't overflow

snprintf(buffer, size, "Hello, World!");

}
int main() {

// Allocate a buffer (array) in the caller

char buffer[20]; // Ensure the buffer is large enough for the string and
null terminator

// Pass the buffer to the function

getGreeting(buffer, sizeof(buffer));

// Print the string from the buffer

printf("%s\n", buffer);

return 0;

Output

Hello, World!
8th assignment

 Write a C program which produces its own source code as its output.

Answer

#include <stdio.h>

int main() {

FILE *fp;

char ch;

// Open the current source file in read mode

fp = fopen(__FILE__, "r");

if (fp == NULL) {

printf("Error: Could not open file.\n");

return 1;

// Read and print each character until EOF

do {

ch = getc(fp);

if (ch != EOF) {
putchar(ch);

} while (ch != EOF);

// Close the file

fclose(fp);

return 0;

Output

#include <stdio.h>

int main() {

FILE *fp;

char ch;

// Open the current source file in read mode

fp = fopen(__FILE__, "r");

if (fp == NULL) {

printf("Error: Could not open file.\n");

return 1;

}
// Read and print each character until EOF

do {

ch = getc(fp);

if (ch != EOF) {

putchar(ch);

} while (ch != EOF);

// Close the file

fclose(fp);

return 0;

 Write a C program to multiply two matrices.


Answer

#include <stdio.h>
Void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int
resultMatrix[][10], int row1, int col1, int row2, int col2) {
For (int I = 0; I < row1; ++i) {
For (int j = 0; j < col2; ++j) {
resultMatrix[i][j] = 0; // Initialize result matrix element to 0
for (int k = 0; k < col1; ++k) {
resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
}

Void displayMatrix(int matrix[][10], int row, int col) {


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

Int main() {
Int row1, col1, row2, col2;
Int firstMatrix[10][10], secondMatrix[10][10], resultMatrix[10][10];

Printf(“Enter rows and columns for the first matrix: “);


Scanf(“%d %d”, &row1, &col1);
Printf(“Enter rows and columns for the second matrix: “);
Scanf(“%d %d”, &row2, &col2);

If (col1 != row2) {
Printf(“Matrix multiplication is not possible.\n”);
Return 0;
}

Printf(“Enter elements of the first matrix:\n”);


For (int I = 0; I < row1; ++i) {
For (int j = 0; j < col1; ++j) {
Scanf(“%d”, &firstMatrix[i][j]);
}
}

Printf(“Enter elements of the second matrix:\n”);


For (int I = 0; I < row2; ++i) {
For (int j = 0; j < col2; ++j) {
Scanf(“%d”, &secondMatrix[i][j]);
}
}

multiplyMatrices(firstMatrix, secondMatrix, resultMatrix, row1, col1,


row2, col2);

Printf(“Resultant matrix:\n”);
displayMatrix(resultMatrix, row1, col2);

return 0;
}

Output
Enter rows and columns for the first matrix: 2 3
Enter rows and columns for the second matrix: 3 2
Enter elements of the first matrix:
123
456
Enter elements of the second matrix:
78
9 10
11 12
Resultant matrix:
58 64
139 154

 Write a C program to check for palindromes.

Answer

#include <stdio.h>

#include <string.h>

#include <ctype.h>

Int isPalindrome(char str[]) {

Int start = 0, end = strlen(str) – 1;

While (start < end) {

While (start < end && !isalnum(str[start])) {

Start++;

While (start < end && !isalnum(str[end])) {

End--;

If (tolower(str[start]) != tolower(str[end])) {

Return 0; // Not a palindrome

Start++;

End--;
}

Return 1; // Palindrome

Int main() {

Char str[100];

Printf(“Enter a string: “);

Fgets(str, sizeof(str), stdin);

Str[strcspn(str, “\n”)] = ‘\0’; // Remove newline character

If (isPalindrome(str)) {

Printf(“The string is a palindrome.\n”);

} else {

Printf(“The string is not a palindrome.\n”);

Return 0;

Output

Enter a string: Madam

The string is a palindrome

2nd time

Enter a string: Hello


The string is not a palindrome.

 Write a C program to convert a decimal number into a binary numb

Answer

#include <stdio.h>

Void decimalToBinary(int n) {

Int binary[32]; // Array to store binary digits

Int I = 0;

If (n == 0) {

Printf(“0”);

Return;

// Convert decimal to binary

While (n > 0) {

Binary[i] = n % 2;

N = n / 2;

I++;

For (int j = I – 1; j >= 0; j--) {


Printf(“%d”, binary[j]);

Int main() {

Int decimalNumber;

Printf(“Enter a decimal number: “);

Scanf(“%d”, &decimalNumber);

Printf(“Binary representation: “);

decimalToBinary(decimalNumber);

return 0;

Ouput

Enter a decimal number: 42

Binary representation: 101010

 Write a program to check, if a given year is a leap year or not.

Answer

#include <stdio.h>

Int main() {

Int year;
// Input the year

Printf(“Enter a year: “);

Scanf(“%d”, &year);

// Check if it’s a leap year

If ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {

Printf(“%d is a leap year.\n”, year);

} else {

Printf(“%d is not a leap year.\n”, year);

Return 0;

Ouput

Ex-1

Enter a year: 2020

2020 is a leap year

Ex-2

Enter a year: 1900

1900 is not a leap year.


9th experiment
 Write your own sqrt function in C.

Answer

#include <stdio.h>

// Function to calculate the square root

Double customSqrt(double number) {

If (number < 0) {

Printf(“Error: Square root of a negative number is undefined.\n”);

Return -1;

If (number == 0 || number == 1) {

Return number; // Square root of 0 or 1 is the number itself

Double guess = number / 2.0; // Initial guess

Double epsilon = 0.00001; // Tolerance for accuracy

While ((guess * guess – number) > epsilon || (number – guess * guess) >
epsilon) {

Guess = (guess + number / guess) / 2.0; // Newton-Raphson formula

}
Return guess;

Int main() {

Double number;

Printf(“Enter a number to find its square root: “);

Scanf(“%lf”, &number);

Double result = customSqrt(number);

If (result != -1) { // Only print if no error

Printf(“Square root of %.5f is %.5f\n”, number, result);

Return 0;

Output
Enter a number to find its square root: 25
Square root of 25.00000 is 5.00000

Ex2
Enter a number to find its square root: 2
Square root of 2.00000 is 1.41421

Ex-3
Enter a number to find its square root: -4
Error: Square root of a negative number is undefined.

 How can we sum the digits of a given number in single statement

Answer

#include <stdio.h>

#include <string.h>

void splitString(char str[], int interval) {

int length = strlen(str);

if (interval <= 0) {

printf("Interval must be greater than 0.\n");

return;

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

printf("%c", str[i]);

if ((i + 1) % interval == 0) {

printf("\n"); // Break into a new line after every interval

}
}

// Handle leftover characters if the length is not a multiple of interval

if (length % interval != 0) {

printf("\n");

int main() {

char str[100];

int interval;

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

str[strcspn(str, "\n")] = '\0'; // Remove newline character

printf("Enter the interval: ");

scanf("%d", &interval);

printf("String split into intervals:\n");

splitString(str, interval);
return 0;

Output

Ex-1

Enter a string: HelloWorld

Enter the interval: 3

String split into intervals:

Hel

loW

orl

Ex-2

Enter a string: ProgrammingIsFun

Enter the interval: 4

String split into intervals:

Prog

Ramm

ingI

sFun

 Write a C program to print a square matrix helically.


Answer
#include <stdio.h>

Void printSpiral(int matrix[][10], int n) {


Int top = 0, bottom = n – 1, left = 0, right = n – 1;

While (top <= bottom && left <= right) {


// Print top row
For (int I = left; I <= right; i++) {
Printf(“%d “, matrix[top][i]);
}
Top++;

// Print right column


For (int I = top; I <= bottom; i++) {
Printf(“%d “, matrix[i][right]);
}
Right--;

// Print bottom row (if any rows remain)


If (top <= bottom) {
For (int I = right; I >= left; i--) {
Printf(“%d “, matrix[bottom][i]);
}
Bottom--;
}

// Print left column (if any columns remain)


If (left <= right) {
For (int I = bottom; I >= top; i--) {
Printf(“%d “, matrix[i][left]);
}
Left++;
}
}
}

Int main() {
Int n;
Int matrix[10][10];

// Input the size of the matrix


Printf(“Enter the size of the square matrix (n x n): “);
Scanf(“%d”, &n);

// Input matrix elements


Printf(“Enter the elements of the matrix:\n”);
For (int I = 0; I < n; i++) {
For (int j = 0; j < n; j++) {
Scanf(“%d”, &matrix[i][j]);
}
}

// Print the matrix helically


Printf(“The matrix in helical order is:\n”);
printSpiral(matrix, n);

return 0;
}

Ouput

Enter the size of the square matrix (n x n): 4


Enter the elements of the matrix:
1234
5678
9 10 11 12
13 14 15 16

The matrix in helical order is:


1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

 Write a C program generate permutations.


Answer

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

Void swap(char* x, char* y) {


Char temp = *x;
*x = *y;
*y = temp;
}

Void generatePermutations(char* str, int start, int end) {


If (start == end) {
Printf(“%s\n”, str);
Return;
}

For (int I = start; I <= end; i++) {


// Swap current index with the start index
Swap(&str[start], &str[i]);
// Recursively generate permutations for the rest of the string
generatePermutations(str, start + 1, end);
// Backtrack by swapping back
Swap(&str[start], &str[i]);
}
}
Int main() {
Char str[100];

Printf(“Enter a string: “);


Scanf(“%s”, str);

Int n = strlen(str);
Printf(“Permutations of the string are:\n”);
generatePermutations(str, 0, n – 1);

return 0;
}

Output

Enter a string: ABC


Permutations of the string are:
ABC
ACB
BAC
BCA
CBA
CAB

You might also like