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

C Programs

Uploaded by

neeraj kapoor
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)
39 views

C Programs

Uploaded by

neeraj kapoor
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/ 23

1. Write C Program to find largest of three integers.

#include <stdio.h>

int main()
{
int a, b, c, largest;

printf("Enter three numbers: ");


if (scanf("%d %d %d", &a, &b, &c) != 3)
{
printf("Invalid input. Please enter three integers.\n");
return 1;
// Return a non-zero value to indicate error
}

largest = a;

if (b > largest)
{
largest = b;
}
if (c > largest)
{
largest = c;
}

printf("Largest number is: %d\n", largest);

return 0;
}

Output:

Enter three numbers: 25

63

56

Largest number is: 63


2. Write C program to check whether the given string is palindrome or not.

#include <stdio.h>
#include <string.h>
// Implementing the logic in a function

void isPalindrome(char str[])


{

// Initializing indexes

int l = 0;
int h = strlen(str) - 1;

// Step 4 to keep checking the characters until they are same


while (h > l)
{
if (str[l++] != str[h--])
{
printf("%s is not a palindrome string\n", str);
return;

}
}

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

// Driver program

int main()
{

isPalindrome("level");

isPalindrome("radar");

isPalindrome("Simplilearn");

return 0;

Output:

level is a palindrome string


radar is a palindrome string
Simplilearn is not a palindrome string
3. Write C program to find whether the given integer is
(i) A prime numer

#include <stdio.h>
int main()

int i, num, temp = 0;


// read input from user.
printf("Enter any numb to Check for Prime: ");
scanf("%d", &num);
// iterate up to n/2.
for (i = 2; i <= num / 2; i++)
{ // check if num is divisible by any number.

if (num % i == 0)
{
temp++;
break;

}
} // check for the value of temp and num.

if (temp == 0 && num != 1)


{
printf("%d is a Prime number", num);

}
else
{

printf("%d is not a Prime number", num);


}

return 0;
}

Output:

Enter any numb to Check for Prime: 12


12 is not a Prime number
(ii) An Armstrong

#include <stdio.h>
int main()
{
int num, originalNum, remainder, result = 0;
printf("Enter a three-digit integer: ");
scanf("%d", &num);
originalNum = num;

while (originalNum != 0)
{
// remainder contains the last digit
remainder = originalNum % 10;

result += remainder * remainder * remainder;

// removing last digit from the orignal number


originalNum /= 10;
}

if (result == num)
printf("%d is an Armstrong number.", num);
else
printf("%d is not an Armstrong number.", num);

return 0;
}

Output:

Enter a three-digit integer: 123


123 is not an Armstrong number.
4. Write C program for Pascal triangle.

// C program to print Pascal’s Triangle


// using combinations in O(n^2) time
// and O(1) extra space function
#include <stdio.h>
void printPascal(int n)
{
for (int line = 1; line <= n; line++) {
for (int space = 1; space <= n - line; space++)
printf(" ");
// used to represent C(line, i)
int coef = 1;
for (int i = 1; i <= line; i++) {
// The first value in a line
// is always 1
printf("%4d", coef);
coef = coef * (line - i) / i;
}
printf("\n");
}
}

// Driver code
int main()
{
int n = 5;
printPascal(n);
return 0;
}

Output:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
5. Write C program to find sum and average of n integer using linear array.

#include<stdio.h>

int main()
{
float a[100], sum=0, avg;
int i, n;

printf("Enter n: ");
scanf("%d", &n);

/* Reading array */
printf("Enter numbers:\n");
for(i=0; i< n; i++)
{
printf("a[%d] = ", i);
scanf("%f", &a[i]);
}
/* Finding sum */
for(i=0; i< n; i++)
{
sum = sum + a[i];
}
/* Calculating average */
avg = sum/n;
/* Displaying Result */
printf("Sum is %f\n", sum);
printf("Average is %f", avg);
return 0;
}

Output:

Enter n: 4
Enter numbers:
a[0] = 25
a[1] = 42
a[2] = 12
a[3] = 12
Sum is 91.000000
Average is 22.750000
6. Write C program to perform addition , multiplication, transpose on matrices.

#include<stdio.h>
#include<stdlib.h>

// function to add two 3x3 matrix


void add(int m[3][3], int n[3][3], int sum[3][3])
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
sum[i][j] = m[i][j] + n[i][j];
}

// function to subtract two 3x3 matrix


void subtract(int m[3][3], int n[3][3], int result[3][3])
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
result[i][j] = m[i][j] - n[i][j];
}

// function to multiply two 3x3 matrix


void multiply(int m[3][3], int n[3][3], int result[3][3])
{
for(int i=0; i < 3; i++)
{
for(int j=0; j < 3; j++)
{
result[i][j] = 0; // assign 0
// find product
for (int k = 0; k < 3; k++)
result[i][j] += m[i][k] * n[k][j];
}
}
} // function to find transpose of a 3x3 matrix
void transpose(int matrix[3][3], int trans[3][3])
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
trans[i][j] = matrix[j][i];
} // function to display 3x3 matrix
void display(int matrix[3][3])
{
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
printf("%d\t",matrix[i][j]);

printf("\n"); // new line


}
} // main function
int main()
{
// matrix
int a[][3] = { {5,6,7}, {8,9,10}, {3,1,2} };
int b[][3] = { {1,2,3}, {4,5,6}, {7,8,9} };
int c[3][3]; // print both matrix
printf("First Matrix:\n");
display(a);
printf("Second Matrix:\n");
display(b); // variable to take choice
int choice; // menu-driven
do
{
// menu to choose the operation
printf("\nChoose the matrix operation,\n");
printf("----------------------------\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Transpose\n");
printf("5. Exit\n");
printf("----------------------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
add(a, b, c);
printf("Sum of matrix: \n");
display(c);
break;
case 2:
subtract(a, b, c);
printf("Subtraction of matrix: \n");
display(c);
break;
case 3:
multiply(a, b, c);
printf("Multiplication of matrix: \n");
display(c);
break;
case 4:
printf("Transpose of the first matrix: \n");
transpose(a, c);
display(c);
printf("Transpose of the second matrix: \n");
transpose(b, c);
display(c);
break;
case 5:
printf("Thank You.\n");
exit(0);
default:
printf("Invalid input.\n");
printf("Please enter the correct input.\n");
}
}
while(1);

return 0;
}

Output:

First Matrix:
5 6 7
8 9 10
3 1 2
Second Matrix:
1 2 3
4 5 6
7 8 9

Choose the matrix operation,


----------------------------
1. Addition
2. Subtraction
3. Multiplication
4. Transpose
5. Exit
----------------------------
Enter your choice: 2.
Subtraction of matrix:
4 4 4
4 4 4
-4 -7 -7
7. Write C program to find Fibonacci series of iterative method using user-defined function.

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

int i, n;

// initialize first and second terms


int t1 = 0, t2 = 1;

// initialize the next term (3rd term)


int nextTerm = t1 + t2;

// get no. of terms from user


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

// print the first two terms t1 and t2


printf("Fibonacci Series: %d, %d, ", t1, t2);

// print 3rd to nth terms


for (i = 3; i <= n; ++i) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}

return 0;
}

Output:

Enter the number of terms: 5


Fibonacci Series: 0, 1, 1, 2, 3,
8. Write C program to find factorial of n by recursion using –defined function.

#include<stdio.h>
long int fact(int x);
int main()
{
int x;
printf("Enter A Number To Find Factorial: ");
scanf("%d",&x);
printf("The Factorial of %d = %ld", x, fact(x));
return 0;
}

long int fact(int x)


{
if (x>=1)
return x*fact(x-1);
else
return 1;
}

Output:

Enter A Number To Find Factorial: 5


The Factorial of 5 = 120
9. Write C program to perform following operations by using user defined functions:
(i) Concatenation

#include <stdio.h>
int main()
{
char s1[100] = "programming ", s2[] = "is awesome";
int length, j;

// store length of s1 in the length variable


length = 0;
while (s1[length] != '\0')
{
++length;
}

// concatenate s2 to s1
for (j = 0; s2[j] != '\0'; ++j, ++length)
{
s1[length] = s2[j];
}

// terminating the s1 string


s1[length] = '\0';

printf("After concatenation: ");


puts(s1);

return 0;
}

Output:
After concatenation: programming is awesome

(ii) Reverse

// C Program to Reverse a String using Two-Pointer Technique


#include <stdio.h>
#include <string.h>
void reverse(char* str)
{
// Initialize first and last pointers
int first = 0;
int last = strlen(str) - 1;
char temp;
// Swap characters till first and last meet
while (first < last)
{
// Swap characters
temp = str[first];
str[first] = str[last];
str[last] = temp;
// Move pointers towards each other
first++;
last--;
} }
int main()
{
char str[100] = "Hello World";

// Reversing str
reverse(str);

printf("%s\n", str);
return 0;
}

Output:
dlroW olleH

(iii) String Matching

// C program to demonstrate the strcmp() function


#include <stdio.h>
#include <string.h>
int main()
{
// Define a string 'str1' and initialize it with "Geeks"
char str1[] = "Geeks";
// Define a string 'str2' and initialize it with "For"
char str2[] = "For";
// Define a string 'str3' and initialize it with "Geeks"
char str3[] = "Geeks";
// Compare 'str1' and 'str2' using strcmp() function and
// store the result in 'result1'
int result1 = strcmp(str1, str2);
// Compare 'str2' and 'str3' using strcmp() function and
// store the result in 'result2'
int result2 = strcmp(str2, str3);
// Compare 'str1' and 'str1' using strcmp() function and
// store the result in 'result3'
int result3 = strcmp(str1, str1);
// Print the result of the comparison between 'str1' and
// 'str2'
printf("Comparison of str1 and str2: %d\n", result1);
// Print the result of the comparison between 'str2' and
// 'str3'
printf("Comparison of str2 and str3: %d\n", result2);
// Print the result of the comparison between 'str1' and
// 'str1'
printf("Comparison of str1 and str1: %d\n", result3);

return 0;
}

Output:
Comparison of str1 and str2: 1
Comparison of str2 and str3: -1
Comparison of str1 and str1: 0

10. Write c program to find sum of n terms of series: n-n*2/2!+n*3/3!-n*4/4!+....

#include <stdio.h>
int fact(int);
void main()
{
int sum;
sum=fact(1)/1+fact(2)/2+fact(3)/3+fact(4)/4+fact(5)/5;
printf("\n\n Function : find the sum of 1!/1+2!/2+3!/3+4!/4+5!/5 :\n");
printf("----------------------------------------------------------\n");
printf("The sum of the series is : %d\n\n",sum);
}

int fact(int n)
{
int num=0,f=1;
while(num<=n-1)
{
f =f+f*num;
num++;
}
return f;
}

Output:

Function : find the sum of 1!/1+2!/2+3!/3+4!/4+5!/5 :


----------------------------------------------------------
The sum of the series is : 34
11. Write C program to interchange two values using
(i) Call by value.

#include <stdio.h>
void swap(int x, int y)
{
int temp = x;
x = y;
y = temp;
}

int main()
{
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(x,y);
printf("Values after swap: x = %d, y = %d", x,y);
}
Output:
Values before swap: x = 10, y = 11
Values after swap: x = 10, y = 11

(ii) Call by reference

#include <stdio.h>
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

int main()
{
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(&x,&y);
printf("Values after swap: x = %d, y = %d", x,y);
}

Output:

Values before swap: x = 10, y = 11


Values after swap: x = 11, y = 10
12. Write C program to sort the list of integers using dynamic memory allocation.

#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a,n,i,j,t;
printf("How many numbers you want to be sorted: ");
scanf("%d",&n);
a=(int *)malloc(n *sizeof(int));
printf("\nEnter %d Numbers: \n\n",n);
for(i=0;i<=n-1;i++)
{
scanf("%d", (a+i));
}
for(i=0;i<n;i++)
{
for(j=0;j<=i;j++)
{
if(*(a+i)<*(a+j))
{
t=*(a+i);
*(a+i)=*(a+j);
*(a+j)=t;
}
}
}
printf("\nAfter Sorting in Ascending Order: \n");
for(i=0;i<n;i++)
printf("\n%d",*(a+i));
return 0;
}

Output:

How many numbers you want to be sorted: 5

Enter 5 Numbers:

23
12
74
15
75
After Sorting in Ascending Order:

12
15
23
74
75

13. Write c program to display the marks sheet of a student using structure.

#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;

int main()
{
printf("Enter information:\n");
printf("Enter name: ");
fgets(s.name, sizeof(s.name), stdin);

printf("Enter roll number: ");


scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);

printf("Displaying Information:\n");
printf("Name: ");
printf("%s", s.name);
printf("Roll number: %d\n", s.roll);
printf("Marks: %.1f\n", s.marks);

return 0;
}

Output:

Enter information:
Enter name: veeru
Enter roll number: 678
Enter marks: 778
Displaying Information:
Name: veeru
Roll number: 678
Marks: 778.0
14. Write C program to perform following operations on the data files read from data file.

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

#define MAX_LINE_LENGTH 100

void readFile(const char *filename);


void writeFile(const char *filename, const char *data);
void appendFile(const char *filename, const char *data);
void searchFile(const char *filename, const char *query);

int main()
{
char filename[] = "data.txt";
char data[MAX_LINE_LENGTH];
char query[MAX_LINE_LENGTH];
int choice;

while (1)
{
printf("\nFile Operations Menu:\n");
printf("1. Read file\n");
printf("2. Write to file\n");
printf("3. Append to file\n");
printf("4. Search in file\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // Clear newline character from input buffer

switch (choice)
{
case 1:
readFile(filename);
break;
case 2:
printf("Enter data to write: ");
fgets(data, MAX_LINE_LENGTH, stdin);
data[strcspn(data, "\n")] = '\0'; // Remove newline character
writeFile(filename, data);
break;
case 3:
printf("Enter data to append: ");
fgets(data, MAX_LINE_LENGTH, stdin);
data[strcspn(data, "\n")] = '\0'; // Remove newline character
appendFile(filename, data);
break;
case 4:
printf("Enter data to search: ");
fgets(query, MAX_LINE_LENGTH, stdin);
query[strcspn(query, "\n")] = '\0'; // Remove newline character
searchFile(filename, query);
break;
case 5:
printf("Exiting program.\n");
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}
void readFile(const char *filename)
{
FILE *file = fopen(filename, "r");
if (file == NULL)
{
printf("Could not open file %s for reading.\n", filename);
return;
}
char line[MAX_LINE_LENGTH];
printf("Contents of %s:\n", filename);
while (fgets(line, sizeof(line), file) != NULL)
{
printf("%s", line);
}
fclose(file);
}
void writeFile(const char *filename, const char *data)
{
FILE *file = fopen(filename, "w");
if (file == NULL) {
printf("Could not open file %s for writing.\n", filename);
return;
}
fprintf(file, "%s\n", data);
fclose(file);
printf("Data written to %s successfully.\n", filename);
}
void appendFile(const char *filename, const char *data)
{
FILE *file = fopen(filename, "a");
if (file == NULL) {
printf("Could not open file %s for appending.\n", filename);
return;
}
fprintf(file, "%s\n", data);
fclose(file);
printf("Data appended to %s successfully.\n", filename);
}
void searchFile(const char *filename, const char *query)
{
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Could not open file %s for searching.\n", filename);
return;
}
char line[MAX_LINE_LENGTH];
int found = 0;

while (fgets(line, sizeof(line), file) != NULL)


{
if (strstr(line, query) != NULL)
{
printf("Found: %s", line);
found = 1;
}
}

if (!found)
{
printf("Query '%s' not found in file.\n", query);
}

fclose(file);
}

Output:

File Operations Menu:


1. Read file
2. Write to file
3. Append to file
4. Search in file
5. Exit
Enter your choice: 1.
Could not open file data.txt for reading.

File Operations Menu:


1. Read file
2. Write to file
3. Append to file
4. Search in file
5. Exit
Enter your choice: 2.
Enter data to write: Could not open file data.txt for writing.

File Operations Menu:


1. Read file
2. Write to file
3. Append to file
4. Search in file
5. Exit
Enter your choice:

15. Write C program to copy the content of one file to another file using command line argument.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])


{
// Check if the correct number of arguments is provided
if (argc != 3)
{
printf("Usage: %s <source_file> <destination_file>\n", argv[0]);
return 1;
}

// Open the source file in read mode


FILE *sourceFile = fopen(argv[1], "r");
if (sourceFile == NULL) {
printf("Error: Could not open source file %s.\n", argv[1]);
return 1;
}

// Open the destination file in write mode


FILE *destFile = fopen(argv[2], "w");
if (destFile == NULL) {
printf("Error: Could not open destination file %s.\n", argv[2]);
fclose(sourceFile); // Close the source file before exiting
return 1;
}

// Copy content from source to destination, character by character


char ch;
while ((ch = fgetc(sourceFile)) != EOF)
{
fputc(ch, destFile);
}

// Confirm the copy operation


printf("File copied successfully from %s to %s.\n", argv[1], argv[2]);

// Close both files


fclose(sourceFile);
fclose(destFile);

return 0;
}

Output:

Usage: /tmp/qQ8aJ17Al9.o <source_file> <destination_file>

You might also like