Lab Programs
1. write a c program using for arithmetic, logical,bitwise and ternary operators
#include <stdio.h>
int main() {
int a = 10, b = 5;
int x = 1, y = 0;
int n1 = 5, n2 = 3;
// 1. Arithmetic Operators: Used for mathematical calculations
printf("--- Arithmetic Operators ---\n");
printf("Addition: %d + %d = %d\n", a, b, a + b);
printf("Subtraction: %d - %d = %d\n", a, b, a - b);
printf("Multiplication: %d * %d = %d\n", a, b, a * b);
printf("Division: %d / %d = %d\n", a, b, a / b);
printf("Modulus (Remainder): %d %% %d = %d\n\n", a, b, a % b);
// 2. Logical Operators: Used to combine or invert conditions
printf("--- Logical Operators ---\n");
printf("Logical AND (%d && %d): %d\n", x, y, x && y);
printf("Logical OR (%d || %d): %d\n", x, y, x || y);
printf("Logical NOT (!%d): %d\n\n", x, !x);
// 3. Bitwise Operators: Perform operations on binary bits
1
printf("--- Bitwise Operators ---\n");
printf("Bitwise AND (%d & %d): %d\n", n1, n2, n1 & n2); // 0101 & 0011 = 0001
(1)
printf("Bitwise OR (%d | %d): %d\n", n1, n2, n1 | n2); // 0101 | 0011 = 0111 (7)
printf("Bitwise XOR (%d ^ %d): %d\n", n1, n2, n1 ^ n2); // 0101 ^ 0011 = 0110 (6)
printf("Bitwise NOT (~%d): %d\n\n", n1, ~n1); // Inverts all bits
// 4. Ternary Operator: Shorthand for if-else statements
printf("--- Ternary Operator ---\n");
// Syntax: condition ? value_if_true : value_if_false
int max = (a > b) ? a : b;
printf("The maximum of %d and %d is: %d\n", a, b, max);
return 0;
}
Output:
--- Arithmetic Operators ---
Addition: 10 + 5 = 15
Subtraction: 10 - 5 = 5
Multiplication: 10 * 5 = 50
Division: 10 / 5 = 2
Modulus (Remainder): 10 % 5 = 0
--- Logical Operators ---
Logical AND (1 && 0): 0
Logical OR (1 || 0): 1
Logical NOT (!1): 0
--- Bitwise Operators ---
Bitwise AND (5 & 3): 1
Bitwise OR (5 | 3): 7
Bitwise XOR (5 ^ 3): 6
Bitwise NOT (~5): -6
--- Ternary Operator ---
The maximum of 10 and 5 is: 10
2. Write programs simple control statements:
a) Roots of quadratic equation
#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
2
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart,
realPart, imagPart);
}
return 0;
}
Output:
Enter coefficients a, b and c: 2.4
4
5.6
root1 = -0.83+1.28i and root2 = -0.83-1.28i
b) Print all digits of a given number/Extracting digits of integers
#include <stdio.h>
#define MAX 100
// Function to print the digit of
// number N
void printDigit(int N)
// To store the digit
3
// of the number N
int arr[MAX];
int i = 0;
int j, r;
// Till N becomes 0
while (N != 0) {
// Extract the last digit of N
r = N % 10;
// Put the digit in arr[]
arr[i] = r;
i++;
// Update N to N/10 to extract
// next last digit
N = N / 10;
// Print the digit of N by traversing
// arr[] reverse
for (j = i - 1; j > -1; j--) {
printf("%d ", arr[j]);
// Driver Code
int main()
int N = 3452897;
printDigit(N);
4
return 0;
Output:
3452897
c) Finding sum of digit using Iterative Approach
// C program to compute sum of digits in
// number.
# include<stdio.h>
/* Function to get sum of digits */
int getSum(int n)
{
int sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n/10;
}
return sum;
}
int main()
{
int n = 687;
printf(" %d ", getSum(n));
return 0;
}
Output:
21
d) Printing multiplication tables
#include <stdio.h>
int main() {
int num;
// Ask user for the number
printf("Enter an integer to print its table: ");
scanf("%d", &num);
printf("\nMultiplication Table for %d:\n", num);
// Loop from 1 to 10 to print the table
5
for (int i = 1; i <= 10; ++i) {
printf("%d x %d = %d\n", num, i, num * i);
}
return 0;
}
Output:
Enter an integer to print its table: 15
Multiplication Table for 15:
15 x 1 = 15
15 x 2 = 30
15 x 3 = 45
15 x 4 = 60
15 x 5 = 75
15 x 6 = 90
15 x 7 = 105
15 x 8 = 120
15 x 9 = 135
15 x 10 = 150
e) Armstrong numbers of Three digits
#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:
6
Enter a three-digit integer: 153
153 is an Armstrong number.
NOTE: All Armstrong number between 1 and 1000 are:
1 2 3 4 5 6 7 8 9 153 370 371 407
f) Checking for Prime Number
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
// 0 and 1 are not prime numbers
// change flag to 1 for non-prime number
if (n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; ++i) {
// if n is divisible by i, then n is not prime
// change flag to 1 for non-prime number
if (n % i == 0) {
flag = 1;
break;
}
}
// flag is 0 for prime numbers
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0;
}
Output:
Enter a positive integer: 29
29 is a prime number.
g) Magic Number
// C program to check
// Whether the number is Magic or not.
#include <stdio.h>
int main() {
// Accepting sample input
int x = 1234;
// Condition to check Magic number
if(x%9==1)
7
printf("Magic Number");
else
printf("Not a Magic Number");
return 0;
}
Output:
Magic Number
3. Sin X and cos X values using series expansions
#include <stdio.h>
int main() {
double degree, x, sin_x, cos_x, term_sin, term_cos;
int terms = 10;
printf("Enter angle in degrees: ");
scanf("%lf", °ree);
// Convert degrees to radians (Pi is approx 3.14159265)
x = degree * (3.14159265 / 180.0);
// Initial values for the first terms
sin_x = x;
term_sin = x;
cos_x = 1.0;
term_cos = 1.0;
// Loop to add remaining terms
for (int i = 1; i < terms; i++) {
// Calculate next Sin term
term_sin = -term_sin * x * x / ((2 * i) * (2 * i + 1));
sin_x += term_sin;
// Calculate next Cos term
term_cos = -term_cos * x * x / ((2 * i - 1) * (2 * i));
cos_x += term_cos;
8
printf("\nResults:\n");
printf("Sin(%.2f) = %.6f\n", degree, sin_x);
printf("Cos(%.2f) = %.6f\n", degree, cos_x);
return 0;
Output:
Enter angle in degrees: 10
Results:
Sin(10.00) = 0.173648
Cos(10.00) = 0.984808
4. Conversion of binary to decimal,octal,hexa and vice versa
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
// Function Prototypes for conversions
long long binToDec(long long n);
long long decToBin(int n);
long long octToDec(int n);
long long hexToDec(char hex[]);
int main() {
int choice, dec, oct;
long long bin;
char hex[20];
printf("[Link] to Dec [Link] to Bin [Link] to Oct [Link] to Dec [Link] to Hex [Link] to
Dec\nEnter: ");
scanf("%d", &choice);
switch(choice) {
case 1: printf("Binary: "); scanf("%lld", &bin); printf("Dec: %lld\n",
binToDec(bin)); break;
case 2: printf("Decimal: "); scanf("%d", &dec); printf("Bin: %lld\n",
decToBin(dec)); break;
case 3: printf("Decimal: "); scanf("%d", &dec); printf("Octal: %o\n", dec);
break; // Using %o
case 4: printf("Octal: "); scanf("%d", &oct); printf("Dec: %lld\n",
octToDec(oct)); break;
9
case 5: printf("Decimal: "); scanf("%d", &dec); printf("Hex: %X\n", dec); break;
// Using %X
case 6: printf("Hex: "); scanf("%s", hex); printf("Dec: %ld\n", strtol(hex, NULL,
16)); break; // Using strtol
}
return 0;
}
// Logic: Binary to Decimal (Position power)
long long binToDec(long long n) {
int dec = 0, i = 0;
while (n != 0) { dec += (n % 10) * pow(2, i++); n /= 10; }
return dec;
}
// Logic: Decimal to Binary (Successive division)
long long decToBin(int n) {
long long bin = 0; int i = 1;
while (n != 0) { bin += (n % 2) * i; n /= 2; i *= 10; }
return bin;
}
// Logic: Octal/Hex to Decimal (Position power)
long long octToDec(int n) {
int dec = 0, i = 0;
while (n != 0) { dec += (n % 10) * pow(8, i++); n /= 10; }
return dec;
}
Output:
[Link] to Dec [Link] to Bin [Link] to Oct [Link] to Dec [Link] to Hex [Link] to Dec
Enter: 3
Decimal: 10
Octal: 12
5. Generating a Pascal Triangle and Pyramid of numbers
a) Pascal,Triangle
#include <stdio.h>
int main() {
int rows, coef = 1, space, i, j;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
for (space = 1; space <= rows - i; space++)
printf(" ");
10
for (j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
b) Pyramid of numbers
#include <stdio.h>
int main() {
int n = 5;
// Outer loop to print all rows
for (int i = 0; i < n; i++) {
// First inner loop to print leading white spaces
for (int j = 0; j < 2 * (n - i - 1); j++)
printf(" ");
// Second inner loop to print star * character
for (int k = 0; k < 2 * i + 1; k++)
printf("%d ", k + 1);
printf("\n");
}
return 0;
}
Output:
6. Recursion: Factorial,Fibonacci,GCD
a) Factorial
11
#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 integer: 6
Factorial of 6 = 720
b) Fibonacci Series
#include <stdio.h>
// Function to find the nth Fibonacci number
int fibonacci(int n) {
// Base Case: if n is 0 or 1, return n
if (n <= 1) {
return n;
}
// Recursive Step: F(n) = F(n-1) + F(n-2)
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
return 0;
}
Output:
Enter the number of terms: 5
Fibonacci Series: 0 1 1 2 3
c) GCD
12
#include <stdio.h>
// Function to find GCD using recursion
int findGCD(int a, int b) {
if (b == 0) return a; // Base case
return findGCD(b, a % b); // Recursive step
}
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("GCD = %d\n", findGCD(n1, n2));
return 0;
}
Output:
Enter two positive integers: 36 60
GCD = 12
7. Finding the Maximum,Minimum,Average and Standard derviation of given set of
numbers using Arrays
#include <stdio.h>
#include <math.h>
int main() {
int n, i;
float sum = 0, average, std_dev = 0, variance = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
float arr[n];
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%f", &arr[i]);
sum += arr[i];
// Finding Maximum and Minimum
float max = arr[0];
float min = arr[0];
13
for (i = 1; i < n; i++) {
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
// Calculating Average
average = sum / n;
// Calculating Standard Deviation
for (i = 0; i < n; i++) {
variance += pow(arr[i] - average, 2);
std_dev = sqrt(variance / n);
printf("\nResults:\n");
printf("Maximum: %.2f\n", max);
printf("Minimum: %.2f\n", min);
printf("Average: %.2f\n", average);
printf("Standard Deviation: %.2f\n", std_dev);
return 0;
Output:
Enter the number of elements: 4
Enter 4 elements: 10 20 30 40
Results:
Maximum: 40.00
Minimum: 10.00
Average: 25.00
Standard Deviation: 11.18
8. Reversing an array, removal of duplicates from array
14
#include <stdio.h>
// Reverses the array by swapping start and end elements
void reverseArray(int arr[], int size) {
int start = 0, end = size - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
// Removes duplicates from a sorted array and returns the new size
int removeDuplicates(int arr[], int n) {
if (n == 0 || n == 1) return n;
int j = 0; // index of next unique element
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, 4, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
// 1. Remove duplicates (requires sorted array)
int newSize = removeDuplicates(arr, n);
// 2. Reverse the unique array
reverseArray(arr, newSize);
printf("Processed Array: ");
for (int i = 0; i < newSize; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output:
Processed Array: 5 4 3 2 1
9. Matrix Addition, Multiplication and Transpose of a square matrix using functions
#include <stdio.h>
#define MAX 10
// Function prototypes
void inputMatrix(int mat[MAX][MAX], int size);
15
void displayMatrix(int mat[MAX][MAX], int size);
void addMatrices(int a[MAX][MAX], int b[MAX][MAX], int res[MAX][MAX], int
size);
void multiplyMatrices(int a[MAX][MAX], int b[MAX][MAX], int res[MAX][MAX],
int size);
void transposeMatrix(int mat[MAX][MAX], int res[MAX][MAX], int size);
int main() {
int m1[MAX][MAX], m2[MAX][MAX], res[MAX][MAX], size;
printf("Enter size (max %d): ", MAX);
scanf("%d", &size);
printf("Matrix A:\n"); inputMatrix(m1, size);
printf("Matrix B:\n"); inputMatrix(m2, size);
printf("\nAddition:\n");
addMatrices(m1, m2, res, size); displayMatrix(res, size);
printf("\nMultiplication:\n");
multiplyMatrices(m1, m2, res, size); displayMatrix(res, size);
printf("\nTranspose of A:\n");
transposeMatrix(m1, res, size); displayMatrix(res, size);
return 0;
}
// Implementations for input, output, add, multiply, and transpose
void inputMatrix(int m[MAX][MAX], int s) {
for(int i=0; i<s; i++) for(int j=0; j<s; j++) scanf("%d", &m[i][j]);
}
void displayMatrix(int m[MAX][MAX], int s) {
for(int i=0; i<s; i++) {
for(int j=0; j<s; j++) printf("%d ", m[i][j]);
printf("\n");
}
}
void addMatrices(int a[MAX][MAX], int b[MAX][MAX], int r[MAX][MAX], int s)
{
for(int i=0; i<s; i++) for(int j=0; j<s; j++) r[i][j] = a[i][j] + b[i][j];
}
void multiplyMatrices(int a[MAX][MAX], int b[MAX][MAX], int r[MAX][MAX],
int s) {
for(int i=0; i<s; i++) for(int j=0; j<s; j++) {
r[i][j] = 0;
16
for(int k=0; k<s; k++) r[i][j] += a[i][k] * b[k][j];
}
}
void transposeMatrix(int m[MAX][MAX], int r[MAX][MAX], int s) {
for(int i=0; i<s; i++) for(int j=0; j<s; j++) r[j][i] = m[i][j];
}
Output:
Enter size (max 10): 2
Matrix A:
22
22
Matrix B:
22
22
Addition:
44
44
Multiplication:
88
88
Transpose of A:
22
22
10. Functions of string maniputation inputting and outputting string,using string funtions
such as strlen(),strcat(),strcpy()…etc
#include <string.h>
int main() {
char str1[100], str2[100], str3[100];
// 1. Inputting strings using fgets() for safety
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = 0; // Removing newline character
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);
str2[strcspn(str2, "\n")] = 0;
// 2. strlen() - Get string length
printf("\nLength of '%s': %zu", str1, strlen(str1));
17
// 3. strcpy() - Copy str1 into str3
strcpy(str3, str1);
printf("\nCopied str1 to str3: %s", str3);
// 4. strcmp() - Compare strings
if (strcmp(str1, str2) == 0) {
printf("\nStrings are equal.");
} else {
printf("\nStrings are different.");
}
// 5. strcat() - Concatenate str2 to the end of str1
strcat(str1, str2);
printf("\nConcatenated result (str1 + str2): %s\n", str1);
return 0;
}
Output:
Enter first string: Hello
Enter second string: Students
Length of 'Hello': 5
Copied str1 to str3: Hello
Strings are different.
Concatenated result (str1 + str2): HelloStudents
11. Writing Simple programs for Strings without using String functions.
#include <stdio.h>
// 1. Finding length (Manual strlen)
int getLength(char str[]) {
int count = 0;
while (str[count] != '\0') {
count++;
return count;
18
// 2. Copying a string (Manual strcpy)
void copyString(char target[], char source[]) {
int i = 0;
while (source[i] != '\0') {
target[i] = source[i];
i++;
target[i] = '\0'; // Crucial: Add the null terminator
// 3. Reversing a string (Manual strrev)
void reverseString(char str[]) {
int len = getLength(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
int main() {
char str[100], copyStr[100];
printf("Enter a string: ");
scanf("%s", str);
// Demonstration
printf("Length: %d\n", getLength(str));
copyString(copyStr, str);
printf("Copied String: %s\n", copyStr);
19
reverseString(str);
printf("Reversed String: %s\n", str);
return 0;
Output:
Enter a string: Welcome
Length: 7
Copied String: Welcome
Reversed String: emocleW
12. Finding the No. of characters, words and lines of given text file.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
FILE *file;
char path[100];
int ch;
int characters = 0, words = 0, lines = 0;
int in_word = 0;
// Prompt user for the file location [7, 10]
printf("Enter file path: ");
scanf("%s", path);
// Open file in read mode [2, 7]
file = fopen(path, "r");
// Check if file exists [7, 10]
if (file == NULL) {
printf("Unable to open file.\n");
20
return 1;
// Process file character by character until EOF [7, 9]
while ((ch = fgetc(file)) != EOF) {
characters++;
// Count lines based on newline characters [7, 13]
if (ch == '\n') {
lines++;
// Logic for counting words [7, 9]
if (isspace(ch)) {
in_word = 0;
} else if (in_word == 0) {
in_word = 1;
words++;
// Increment line count if the last line doesn't end with a newline [2, 7]
if (characters > 0 && ch != '\n') {
lines++;
// Output the results [1, 7]
printf("\nTotal characters = %d", characters);
printf("\nTotal words = %d", words);
printf("\nTotal lines = %d\n", lines);
// Close the file to free resources [2, 7]
fclose(file);
21
return 0;
Suppose if data\[Link] contains
I love programming.
Working with files in C programming is fun.
I am learning C programming at Codeforwin.
Output:
Enter file path:data\[Link]
Total characters = 106
Total words = 18
Total lines =3
13. File handling programs: Student memo printing
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fptr;
char name[50];
int roll, s1, s2, total;
// 1. Open file in write mode ("w")
fptr = fopen("student_memo.txt", "w");
if (fptr == NULL) {
printf("Error: Could not create file.\n");
exit(1);
}
// 2. Input student details from user
printf("Enter Student Name: ");
scanf("%[^\n]s", name); // Reads string with spaces
printf("Enter Roll Number: ");
scanf("%d", &roll);
printf("Enter marks in 2 subjects: ");
scanf("%d %d", &s1, &s2);
// 3. Write formatted data to the file
// fprintf works like printf but targets a file
22
fprintf(fptr, "%s\n%d\n%d %d", name, roll, s1, s2);
fclose(fptr);
// 4. Open file in read mode ("r") to print the memo
fptr = fopen("student_memo.txt", "r");
if (fptr == NULL) {
printf("Error: Could not open file for reading.\n");
exit(1);
}
// Read back data to calculate total for the memo
fscanf(fptr, " %[^\n]s", name);
fscanf(fptr, "%d", &roll);
fscanf(fptr, "%d %d", &s1, &s2);
total = s1 + s2;
// 5. Print the Student Memo
printf("\n---------- STUDENT MEMO ----------\n");
printf("Name: %s\n", name);
printf("Roll No: %d\n", roll);
printf("Subject 1: %d\n", s1);
printf("Subject 2: %d\n", s2);
printf("----------------------------------\n");
printf("Grand Total: %d\n", total);
printf("----------------------------------\n");
fclose(fptr);
return 0;
}
Output:
23
24