All C programs

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

1) Write a program to print transpose of a given Matrix.

(Take element
form the user from console).
→#include <stdio.h>
void main() {
int matrix[100][100], transpose[100][100];
int row, col, i, j;
printf("Enter the number of rows and columns of the matrix: ");
scanf("%d %d", &row, &col);
printf("Enter elements of the matrix:\n");
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
for(i = 0; i < row; i++) {
for(j = 0; j < col; j++) {
transpose[j][i] = matrix[i][j];
}
}
printf("Transpose of the matrix:\n");
for(i = 0; i < col; i++) {
for(j = 0; j < row; j++) {
printf("%d\t", transpose[i][j]);
}
printf("\n");
}
}

1
2. Write a program to sum up all the elements of diagonal of 4x4 Matrix.
→ #include <stdio.h>

void main() {
// Declare variables
int matrix[4][4];
int i, j, sum = 0;

// Input matrix elements


printf("Enter elements of the 4x4 matrix:\n");
for(i = 0; i < 4; i++) {
for(j = 0; j < 4; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}

// Summing up the diagonal elements


for(i = 0; i < 4; i++) {
sum += matrix[i][i];
}

// Printing the sum


printf("Sum of diagonal elements: %d\n", sum);
}

3. Write a program Matrix Multiplication. Check if Multiplication is


Possible
→ #include <stdio.h>

void main() {
// Declare variables
int matrix1[10][10], matrix2[10][10], result[10][10];
int row1, col1, row2, col2, i, j, k;

// Input dimensions of first matrix


printf("Enter the number of rows and columns of the first matrix: ");
scanf("%d %d", &row1, &col1);

// Input elements of first matrix


printf("Enter elements of the first matrix:\n");
for(i = 0; i < row1; i++) {

2
for(j = 0; j < col1; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}

// Input dimensions of second matrix


printf("Enter the number of rows and columns of the second matrix: ");
scanf("%d %d", &row2, &col2);

// Input elements of second matrix


printf("Enter elements of the second matrix:\n");
for(i = 0; i < row2; i++) {
for(j = 0; j < col2; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
// Check if multiplication is possible
if(col1 != row2) {
printf("Matrix multiplication is not possible.\n");
return;
}

// Perform matrix multiplication


for(i = 0; i < row1; i++) {
for(j = 0; j < col2; j++) {
result[i][j] = 0;
for(k = 0; k < col1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Output the result matrix


printf("Result of matrix multiplication:\n");
for(i = 0; i < row1; i++) {
for(j = 0; j < col2; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}
}

3
4. WAP to find greatest among three numbers.
→ #include <stdio.h>
void main() {
// Declare variables
int num1, num2, num3, greatest;

// Input three numbers


printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);

// Assume the first number is the greatest


greatest = num1;

// Compare with the second number


if (num2 > greatest) {
greatest = num2;
}

// Compare with the third number


if (num3 > greatest) {
greatest = num3;
}

// Output the greatest number


printf("The greatest number is: %d\n", greatest);
}

4
5. WAP to count the number of vowels in the given String.
→ #include <stdio.h>
#include <string.h>
void main() {
// Declare variables
char str[100];
int i, vowels = 0;

// Input the string


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Loop through each character in the string


for(i = 0; str[i] != '\0'; i++) {
// Check if the character is a vowel (both uppercase and lowercase)
if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {
vowels++;
}
}

// Output the number of vowels


printf("Number of vowels in the string: %d\n", vowels);
}

5
6. WAP to find if given number is Armstrong.
→ #include <stdio.h>
#include <math.h>

void main() {
// Declare variables
int num, originalNum, remainder, result = 0, n = 0;

// Input the number


printf("Enter a number: ");
scanf("%d", &num);

// Store the original number in another variable


originalNum = num;

// Count the number of digits


while (originalNum != 0) {
originalNum /= 10;
n++;
}

// Restore the original number


originalNum = num;

// Calculate the result


while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}

// Check if the number is Armstrong


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

6
7. WAP to prepare the pay slip of an employee Structure. Input the
employee’s name, employee number and basic pay. Calculate the DA,
HRA, PF, PT, Gross Pay and Net Pay as follows:
If Basic < 40000, DA = 50% of Basic, HRA = 12% of Basic, PF = 12% of
Gross Pay, PT = 250.Otherwise DA = 40% of Basic, HRA = 10% of
Basic, PF = 13% of Gross, PT= 300. Gross Pay = Basic + DA + HRA
and Net Pay = Gross Pay – PF – PT.

→ #include <stdio.h>

// Define structure for employee


struct Employee {
char name[50];
int empNumber;
float basicPay;
float DA;
float HRA;
float PF;
float PT;
float grossPay;
float netPay;
};

// Function to calculate pay slip


void calculatePaySlip(struct Employee *emp) {
if (emp->basicPay < 40000) {
emp->DA = 0.5 * emp->basicPay;
emp->HRA = 0.12 * emp->basicPay;
emp->PF = 0.12 * (emp->basicPay + emp->DA + emp->HRA);
emp->PT = 250;
} else {
emp->DA = 0.4 * emp->basicPay;
emp->HRA = 0.1 * emp->basicPay;
emp->PF = 0.13 * (emp->basicPay + emp->DA + emp->HRA);
emp->PT = 300;
}
emp->grossPay = emp->basicPay + emp->DA + emp->HRA;
emp->netPay = emp->grossPay - emp->PF - emp->PT;
}

void main() {
// Declare structure variable
struct Employee emp;

7
// Input employee details
printf("Enter employee name: ");
scanf("%s", emp.name);

printf("Enter employee number: ");


scanf("%d", &emp.empNumber);

printf("Enter basic pay: ");


scanf("%f", &emp.basicPay);

// Calculate pay slip


calculatePaySlip(&emp);

// Output pay slip


printf("\nPay Slip for Employee %s (Employee Number: %d)\n",
emp.name, emp.empNumber);
printf("Basic Pay: %.2f\n", emp.basicPay);
printf("Dearness Allowance (DA): %.2f\n", emp.DA);
printf("House Rent Allowance (HRA): %.2f\n", emp.HRA);
printf("Provident Fund (PF): %.2f\n", emp.PF);
printf("Professional Tax (PT): %.2f\n", emp.PT);
printf("Gross Pay: %.2f\n", emp.grossPay);
printf("Net Pay: %.2f\n", emp.netPay);
}

8
8. WAP to enter the information of student (name, roll number, marks in
six subjects) in student structure array and Compute and print the result.
For passing, student should get at least 35 in each subject, otherwise
result is “FAIL”. If the student passes and if percentage >= 70, result is
DISTINCTION; If percentage is < 70 and >= 60, result is FIRST CLASS;
if percentage is < 60 and >=50, result is SECOND CLASS; otherwise,
result is PASS CLASS. Get the output of all students in a tabular form
with proper column headings.
→ #include <stdio.h>
struct Student {
char name[50];
int rollNumber;
int marks[6];
float percentage;
char result[20];
};

void computeResult(struct Student *student) {


int totalMarks = 0;
for (int i = 0; i < 6; i++) {
totalMarks += student->marks[i];
if (student->marks[i] < 35) {
strcpy(student->result, "FAIL");
student->percentage = 0;
return;
}
}
student->percentage = (float)totalMarks / 6;
if (student->percentage >= 70) {
strcpy(student->result, "DISTINCTION");
} else if (student->percentage >= 60) {
strcpy(student->result, "FIRST CLASS");
} else if (student->percentage >= 50) {
strcpy(student->result, "SECOND CLASS");
} else {
strcpy(student->result, "PASS CLASS");
}
}

void main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);

9
struct Student students[n];

// Input student information


for (int i = 0; i < n; i++) {
printf("\nEnter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Roll Number: ");
scanf("%d", &students[i].rollNumber);
printf("Marks in six subjects: ");
for (int j = 0; j < 6; j++) {
scanf("%d", &students[i].marks[j]);
}
computeResult(&students[i]);
}

// Output student information in tabular form


printf("\n\n%-15s%-15s%-15s%-15s%-15s%-15s%-15s\n", "Name",
"Roll Number", "Subject 1", "Subject 2", "Subject 3", "Subject 4",
"Subject 5", "Subject 6", "Percentage", "Result");
for (int i = 0; i < n; i++) {
printf("%-15s%-15d", students[i].name, students[i].rollNumber);
for (int j = 0; j < 6; j++) {
printf("%-15d", students[i].marks[j]);
}
printf("%-15.2f%-15s\n", students[i].percentage, students[i].result);
}
}

10
9.WAP to read a string and to find the number of alphabets, digits,
spaces and special characters. (without using character functions)

#include <stdio.h>
void main() {
char str[100];
int alphabets = 0, digits = 0, spaces = 0, specialChars = 0;
int i = 0;

// Input the string


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Count characters in the string


while (str[i] != '\0') {
// Check for alphabets
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
alphabets++;
}
// Check for digits
else if (str[i] >= '0' && str[i] <= '9') {
digits++;
}
// Check for spaces
else if (str[i] == ' ') {
spaces++;
}
// Count special characters
else {
specialChars++;
}
i++;
}

// Output the counts


printf("Number of alphabets: %d\n", alphabets);
printf("Number of digits: %d\n", digits);
printf("Number of spaces: %d\n", spaces);
printf("Number of special characters: %d\n", specialChars);
}

11
10. WAP to accept String from the user and print the string in reverse
without using function.
→ #include <stdio.h>
void main() {
char str[100];
int length = 0;

// Input the string


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Calculate the length of the string


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

// Print the string in reverse


printf("Reversed string: ");
for (int i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");
}

12
11. WAP to read a string and to find the number of alphabets, digits,
spaces and special characters. (use character functions)
→ #include <stdio.h>
#include <ctype.h>
void main() {
char str[100];
int alphabets = 0, digits = 0, spaces = 0, specialChars = 0;
int i = 0;

// Input the string


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Count characters in the string


while (str[i] != '\0') {
// Check for alphabets
if (isalpha(str[i])) {
alphabets++;
}
// Check for digits
else if (isdigit(str[i])) {
digits++;
}
// Check for spaces
else if (isspace(str[i])) {
spaces++;
}
// Count special characters
else {
specialChars++;
}
i++;
}

// Output the counts


printf("Number of alphabets: %d\n", alphabets);
printf("Number of digits: %d\n", digits);
printf("Number of spaces: %d\n", spaces);
printf("Number of special characters: %d\n", specialChars);
}

13
12. WAP to accept String from the user and check if it is palindrome.
→ #include <stdio.h>
#include <string.h>

void main() {
char str[100];
int i, j;
int isPalindrome = 1; // Assume string is a palindrome by default

// Input the string


printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Remove newline character from input


str[strcspn(str, "\n")] = '\0';

// Check if the string is a palindrome


for (i = 0, j = strlen(str) - 1; i < j; i++, j--) {
if (str[i] != str[j]) {
isPalindrome = 0; // Not a palindrome
break;
}
}
// Output the result
if (isPalindrome) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
}

14
13. WAP to accept a number and check whether it is a palindrome
number.
→ #include <stdio.h>
void main() {
int num, reversedNum = 0, originalNum;

// Input the number


printf("Enter a number: ");
scanf("%d", &num);

// Store the original number


originalNum = num;

// Reverse the number


while (num != 0) {
int digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
}

// Check if the original number is equal to the reversed number


if (originalNum == reversedNum) {
printf("%d is a palindrome number.\n", originalNum);
} else {
printf("%d is not a palindrome number.\n", originalNum);
}
}

15
14. Write ‘C’ program to accept a number and check whether it is an
Armstrong number.
→ #include <stdio.h>
#include <math.h>
void main() {
int num, originalNum, remainder, result = 0, n = 0;

// Input the number


printf("Enter a number: ");
scanf("%d", &num);

// Store the original number in another variable


originalNum = num;

// Count the number of digits


while (originalNum != 0) {
originalNum /= 10;
n++;
}

// Restore the original number


originalNum = num;

// Calculate the result


while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}

// Check if the number is Armstrong


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

16
15. Write a Program to find the Area and circumference of the Circle.
→ #include <stdio.h>
#define PI 3.14159 // Define the value of PI
void main() {
float radius, area, circumference;

// Input the radius of the circle


printf("Enter the radius of the circle: ");
scanf("%f", &radius);

// Calculate the area of the circle


area = PI * radius * radius;

// Calculate the circumference of the circle


circumference = 2 * PI * radius;

// Output the results


printf("Area of the circle: %.2f square units\n", area);
printf("Circumference of the circle: %.2f units\n", circumference);
}

17
16. Write a program to check if the given number is prime number. (Use
ternary operator)
→ #include <stdio.h>
void main() {
int num, i;
int isPrime;

// Input the number


printf("Enter a number: ");
scanf("%d", &num);

// Check if the number is prime


isPrime = (num <= 1) ? 0 : 1; // Assume the number is prime by
default

for (i = 2; i <= num / 2; i++) {


if (num % i == 0) {
isPrime = 0; // Not a prime number
break;
}
}

// Output the result


(isPrime == 1) ? printf("%d is a prime number.\n", num) : printf("%d is
not a prime number.\n", num);
}

18
17. Write a Program to convert centimetres to meter and vice versa.
(Ask User an option to choose)
→ #include <stdio.h>
void main() {
int option;
float length, convertedLength;

// Display options to the user


printf("Choose an option:\n");
printf("1. Convert centimeters to meters\n");
printf("2. Convert meters to centimeters\n");
printf("Enter your option (1 or 2): ");
scanf("%d", &option);

// Perform conversion based on user input


switch (option) {
case 1:
// Convert centimeters to meters
printf("Enter length in centimeters: ");
scanf("%f", &length);
convertedLength = length / 100;
printf("%.2f centimeters = %.2f meters\n", length,
convertedLength);
break;
case 2:
// Convert meters to centimeters
printf("Enter length in meters: ");
scanf("%f", &length);
convertedLength = length * 100;
printf("%.2f meters = %.2f centimeters\n", length,
convertedLength);
break;
default:
printf("Invalid option selected.\n");
}
}

19
18. WAP to print follow pattern
*****
* *
* *
* *
*****

→ #include <stdio.h>
void main() {
int rows, cols, i, j;

// Input number of rows and columns


rows = 5;
cols = 5;

// Iterate through each row


for (i = 1; i <= rows; i++) {
// Iterate through each column
for (j = 1; j <= cols; j++) {
// Print '*' for the first and last row, and for the first and last
column of each row
if (i == 1 || i == rows || j == 1 || j == cols) {
printf("* ");
} else {
// Otherwise, print a space
printf(" ");
}
}
// Move to the next line after printing each row
printf("\n");
}
}

20
19. WAP to print follow pattern
a
aba
abcba
abcdcba
abcdedcba

→ #include <stdio.h>
void main() {
int rows, i, j, k;
char ch;

// Input number of rows


rows = 5;
ch = 'a';

// Iterate through each row


for (i = 1; i <= rows; i++) {
// Print spaces for the first part of each row
for (j = i; j < rows; j++) {
printf(" ");
}

// Print characters for the first half of the row


for (k = 1; k <= i; k++) {
printf("%c", ch++);
}

// Decrement ch to print the second half of the row


ch--;

// Print characters for the second half of the row


for (k = 1; k < i; k++) {
printf("%c", --ch);
}

// Move to the next line after printing each row


printf("\n");

// Reset ch for the next row


ch = 'a';
}
}

21
20. Write a program to make the following pattern
$
$ $
$ $ $
$ $ $ $

→ #include <stdio.h>
void main() {
int rows, i, j;

// Input number of rows


rows = 4;

// Iterate through each row


for (i = 1; i <= rows; i++) {
// Print spaces for the first part of each row
for (j = i; j < rows; j++) {
printf(" ");
}

// Print '$' characters for each part of the row


for (j = 1; j <= i; j++) {
printf("$ ");
}

// Move to the next line after printing each row


printf("\n");
}
}

22
21. WAP to print the following pattern
1
22
333
55555
7777777
999999999

→ #include <stdio.h>
void main() {
int rows, i, j, num;

// Input number of rows


rows = 5;

// Initialize the starting number


num = 1;

// Iterate through each row


for (i = 1; i <= rows; i++) {
// Print the repeating number in each row
for (j = 1; j <= i; j++) {
printf("%d", num);
}

// Increment the number for the next row


num += 2;

// Move to the next line after printing each row


printf("\n");
}
}

23
22. WAP to accept number(n) and find the sum of the series
11+22+33+44……..+nn
→ #include <stdio.h>

void main() {
int n, i;
int sum = 0;

// Input the value of n


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

// Calculate the sum of the series


for (i = 1; i <= n; i++) {
sum += i * 11;
}

// Output the result


printf("Sum of the series: %d\n", sum);
}

23. WAP to accept number(n) and find the sum of the series 1! + 3! + 5!
…… + n!
→ #include <stdio.h>
// Function to calculate the factorial of a number
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

void main() {
int n, i;
int sum = 0;

// Input the value of n


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

24
// Calculate the sum of the series
for (i = 1; i <= n; i += 2) {
sum += factorial(i);
}

// Output the result


printf("Sum of the series: %d\n", sum);
}

24. WAP to accept number(n) and find the sum of the series
1!+2!+3!+4!....+n!.
→ #include <stdio.h>
// Function to calculate the factorial of a number
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

void main() {
int n, i;
int sum = 0;

// Input the value of n


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

// Calculate the sum of the series


for (i = 1; i <= n; i++) {
sum += factorial(i);
}

// Output the result


printf("Sum of the series: %d\n", sum);
}

25
25.WAP to print n number of Fibonacci series.
→ #include <stdio.h>
void main() {
int n, i;
int fib1 = 0, fib2 = 1, nextTerm;

// Input the value of n


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

printf("Fibonacci Series: ");

// Print the first two terms of the series


printf("%d %d ", fib1, fib2);

// Generate the Fibonacci series


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

printf("\n");
}

26
26. WAP to accept n number and find the sum of the series
1!/1+2!/2+3!/3…..+n!/n

#include <stdio.h>
// Function to calculate the factorial of a number
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

void main() {
int n, i;
float sum = 0;

// Input the value of n


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

// Calculate the sum of the series


for (i = 1; i <= n; i++) {
sum += (float)factorial(i) / i;
}

// Output the result


printf("Sum of the series: %.2f\n", sum);
}

27
27. WAP to copy the content of one file into another file.
→ #include <stdio.h>
void main() {
FILE *sourceFile, *destinationFile;
char ch;

// Open the source file in read mode


sourceFile = fopen("source.txt", "r");
// Check if the source file exists and can be opened
if (sourceFile == NULL) {
printf("Unable to open source file.\n");
return;
}

// Open the destination file in write mode


destinationFile = fopen("destination.txt", "w");
// Check if the destination file exists and can be opened
if (destinationFile == NULL) {
printf("Unable to create destination file.\n");
fclose(sourceFile);
return;
}

// Copy the contents of the source file to the destination file


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

// Close both files


fclose(sourceFile);
fclose(destinationFile);

printf("File copied successfully.\n");


}

28
28. WAP to find number of vowels in the given file.
→ #include <stdio.h>
#include <ctype.h>
void main() {
FILE *file;
char ch;
int vowelCount = 0;

// Open the file in read mode


file = fopen("input.txt", "r");

// Check if the file exists and can be opened


if (file == NULL) {
printf("Unable to open the file.\n");
return;
}

// Read characters from the file and count vowels


while ((ch = fgetc(file)) != EOF) {
// Convert character to lowercase
ch = tolower(ch);
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
}

// Close the file


fclose(file);

// Output the result


printf("Number of vowels in the file: %d\n", vowelCount);
}

29
29. WAP to find the number of digit and character (Excluding special
character) in the given file
→ #include <stdio.h>
#include <ctype.h>
void main() {
FILE *file;
char ch;
int digitCount = 0, charCount = 0;

// Open the file in read mode


file = fopen("input.txt", "r");

// Check if the file exists and can be opened


if (file == NULL) {
printf("Unable to open the file.\n");
return;
}

// Read characters from the file and count digits and characters
(excluding special characters)
while ((ch = fgetc(file)) != EOF) {
// Check if the character is a digit
if (isdigit(ch)) {
digitCount++;
}
// Check if the character is an alphabet
else if (isalpha(ch)) {
charCount++;
}
}

// Close the file


fclose(file);

// Output the result


printf("Number of digits in the file: %d\n", digitCount);
printf("Number of characters (excluding special characters) in the file:
%d\n", charCount);
}

30

You might also like