0% found this document useful (0 votes)
77 views69 pages

Cs Filnal Practical

The document contains code snippets for various C programming questions. The questions cover topics like calculating the average of 3 numbers, finding the area, volume and perimeter of a sphere, right and left bitwise shifting, finding the roots of a quadratic equation, bitwise operations, integer and number printing, digit sum, compound interest calculation, finding roots of equations, employee data entry and searching, number reversing, checking prime numbers in a range, finding HCF, Fabonacci series, trigonometric functions, array operations, string operations and more.

Uploaded by

test mail
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views69 pages

Cs Filnal Practical

The document contains code snippets for various C programming questions. The questions cover topics like calculating the average of 3 numbers, finding the area, volume and perimeter of a sphere, right and left bitwise shifting, finding the roots of a quadratic equation, bitwise operations, integer and number printing, digit sum, compound interest calculation, finding roots of equations, employee data entry and searching, number reversing, checking prime numbers in a range, finding HCF, Fabonacci series, trigonometric functions, array operations, string operations and more.

Uploaded by

test mail
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Submitted By: Submitted to:

Mr. M.M. Misgar


Name: Gouresh Chauhan
Roll No. 2022UCA1934
Ph. No. 7982286038
Email: [email protected]
Date: 29/02/2023
S. no NAME Page No.
1 Average of 3 numbers 4
2 Area volume and perimeter of 5
sphere
3 Right shift effectively 7
4 Root of quadratic 9
5 Bitwise operation 10
6 Interger printing #1 11
7 Sum of digits 13
8 Compound Interest 15
9 Root of equation 17
10 Employ data entry and searching 18
11 Reverse printing number 21
12 Prime numbers between a range 23
13 HCF 25
14 Fabonacci 28
15 Value of sine 30
16 Pattern printing #1 31
17 Merge 2 array in order 32
18 Count number of occurrences 33
19 Matrix functions 35
20 Counts vowels and consonants 36
21 Replace substring 38
22 Frequency of digits 40
23 Sum, mean, standard deviation 42
24 Pattern printing #2 43
25 Amount decoder 45
26 Reverse order elements using 47
pointer
27 Comparing string 48
28 Prime and fabonacci 50
29 Substring occurrence function 54
30 Stacking 56
31 Structure 57
32 Employ data and searching using 58
mobile number
33 Reading file and output in other 59
files
34 Matrix resultant 62
35 Prime number up to 2500 using 63
Eratosthenes
36 Python program 10 – 18 64
37 Percentage of 3 subjects 65
38 Employ data records keeper in 68
python
39 Copy input from file and print it in 69
other file
Question no 1
#include<stdio.h>

int main()

int num1, num2, num3; float average;


printf("Enter three numbers: "); scanf("%d%d%d", &num1,
&num2, &num3); average = (float)(num1 + num2 + num3)/3;
printf("Average of %d, %d and %d is: %.2f", num1, num2, num3,
average);
return 0;

Question no 2
#include<stdio.h>

int main()
{

float r, perimeter,
area, volume;
printf("Enter the
radius of the circle/sphere: "); scanf("%f", &r);
perimeter = 2 * PI * r;
area = 3.14 * r * r;
volume = (4.0/3.0) *
3.14 * r * r * r;
printf("Perimeter of
the circle: %.2f\n", perimeter);
printf("Area of the
circle: %.2f\n", area);
printf("Volume of the
sphere: %.2f\n", volume);
return 0;
}

Question no 3
#include<stdio.h>

int main()

{
int num, right_shift,
left_shift;
printf("Enter an
integer: "); scanf("%d", &num);
right_shift = num >> 1;
left_shift = num << 1;
printf("%d divided by 2
using right shift operator: %d\n", num, right_shift);
printf("%d multiplied
by 2 using left shift operator: %d\n", num, left_shift);
return 0;
}

Question no 4
#include <stdio.h>
#include <math.h>
int main()

double a, b, c,
discriminant, root1, root2;

printf("Enter the
coefficients of the quadratic equation (a, b, c): ");
scanf("%lf%lf%lf", &a, &b, &c);

discriminant = b*b -
4*a*c;

if (discriminant > 0) {
root1 = (-b +
sqrt(discriminant)) / (2*a); root2 = (-b - sqrt(discriminant)) /
(2*a);
printf("The roots
are %lf and %lf\n", root1, root2);
} else if (discriminant == 0)
{ root1 = root2 = -b /
(2*a);
printf("The root is
%lf%lf\n", root1,root2);
} else {
printf("The equation
has no real roots\n");
}

return 0;
}

Question no 5
#include <stdio.h>

unsigned int bitwise_and(unsigned int x, unsigned int y) {


return x & y;
}

unsigned int bitwise_or(unsigned int x, unsigned int y) {


return x | y;
}

unsigned int bitwise_xor(unsigned int x, unsigned int y) {


return x ^ y;
}

unsigned int bitwise_not(unsigned int x) {


return ~x;
}

int main() {
unsigned int x = 0b1010, y = 0b0110;

printf("x: %u\n", x);


printf("y: %u\n", y);

printf("bitwise_and(x, y): %u\n", bitwise_and(x, y));


printf("bitwise_or(x, y): %u\n", bitwise_or(x, y));

Question no 6
#include<stdio.h>
#include<math.h>

int main()
{
int num, digits = 0, temp;
printf("Enter an integer: ");
scanf("%d", &num);
temp = num;
while (temp != 0)
{
digits++;
temp /= 10;
}
temp = num;
for (int i = 1; i <= digits; i++)
{
int divisor = pow(10, digits - i);
int quotient = temp / divisor;
int remainder = temp % divisor;
printf("All digits except the last %d digits: %d\n", i,
remainder);
temp = quotient;
}
printf("The last digit: %d\n", temp % 10); return 0;
Question no 7
#include<stdio.h>

int main()
{
int num, sum = 0, remainder;
printf("Enter an integer: "); scanf("%d", &num);
while (num != 0)
{
remainder = num % 10;
sum += remainder;
num /= 10;
}
printf("Sum of the digits: %d\n", sum);
return 0;
}

Question no 8
#include<stdio.h>
#include<math.h>
int main()
{
float investment, interest_rate = 7.75, interest, total_amount;
int years = 10;
printf("Enter the investment amount: ");
scanf("%f", &investment);
interest = investment * interest_rate * years / 100;
total_amount = investment + interest;
printf("Fixed deposit cumulative return after %d years at an
interest rate of %.2f%%: %.2f\n", years, interest_rate,
total_amount);
return 0;
}

Question no 9
#include <stdio.h>
#include <math.h>

int main()
{
double a, b, c, discriminant, root1, root2, realPart,
imaginaryPart;
printf("Enter the coefficients a, b and c: ");
scanf("%lf%lf%lf", &a, &b, &c);

discriminant = b * b - 4 * a * c;

// Roots are real and different


if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}

// Roots are real and equal


else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}

// Roots are complex and different


else {
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf + %.2lfi and root2 = %.2lf - %.2lfi",
realPart, imaginaryPart, realPart, imaginaryPart);
}

return 0;
}

Question no 10
int main() {
char name[100];
int level, basic_pay;
int perks, tax, gross_salary, net_salary;

printf("Enter employee name: ");


scanf("%s", name);
printf("Enter employee level (1-4): ");
scanf("%d", &level);
printf("Enter basic pay: ");
scanf("%d", &basic_pay);
switch(level) {
case 1:
perks = 7000 + 3000;
if (basic_pay >= 40000 && basic_pay <= 60000) {
tax = (basic_pay + perks) * 0.1;
}
else {
printf("Invalid basic pay for level 1 employee.\n");
return 0;
}
break;
case 2:
perks = 6000 + 2000;
if (basic_pay >= 30000 && basic_pay <= 40000) {
tax = (basic_pay + perks) * 0.08;
}
else {
printf("Invalid basic pay for level 2 employee.\n"); return 0;
}
break;
case 3:
perks = 5000 + 1500;
if (basic_pay >= 20000 && basic_pay <= 30000) {
tax = (basic_pay + perks) * 0.05;
}
else {
printf("Invalid basic pay for level 3 employee.\n");
return 0;
}
break;
case 4:
perks = 5000 + 1500;
if (basic_pay >= 15000 && basic_pay <= 20000) {
tax = 0;
}
else {
printf("Invalid basic pay for level 4 employee.\n");
return 0;
}
break;
default:
printf("Invalid employee level.\n");
return 0;
}
gross_salary = basic_pay + perks + basic_pay * 0.25;
net_salary = gross_salary - tax;

printf("Employee name: %s\n", name);


printf("Gross salary: %d\n", gross_salary);
printf("Tax: %d\n", tax);
printf("Net salary: %d\n", net_salary);

return 0;
}

Question no 11
#include <stdio.h>

int main() {
int n, reversed = 0;

printf("Enter a number: ");


scanf("%d", &n);

while (n != 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
printf("Reversed number: %d", reversed);
return 0;
}

Question no 12
#include <stdio.h>
#include <math.h>

int is_prime(int n) {
int i;
if (n <= 1) return 0;
for (i = 2; i <= sqrt(n); i++) { if (n % i == 0) return 0;
}
return 1;
}

int main() {
int low, high, i;
printf("Enter low and high: ");
scanf("%d%d", &low, &high);

printf("Prime numbers between %d and %d are:", low, high);


for (i = low; i <= high; i++) {
if (is_prime(i)) printf("%d ", i);
}

return 0;
}

Question no 13
#include <stdio.h>

int hcf(int a, int b) {


if (b == 0) return a;
return hcf(b, a % b);
}

int main() {
int a, b, result;

printf("Enter two integers: ");


scanf("%d%d", &a, &b);

result = hcf(a, b);


printf("The HCF of %d and %d is %d", a, b, result);

return 0;
}

Question no 14
#include <stdio.h>

int main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("First %d terms of Fibonacci series:\n", n);
c = 0;
do {
if (c <= 1) {
next = c;
}
else {
next = first + second;
first = second;
second = next;
}
printf("%d\n", next);
c++;
} while (c < n);
return 0;
}

Question no 15
#include <stdio.h>
#include <math.h>

double sinx(double x) {
double sin = x, term = x, x_pow = x * x;
int i = 1;
while (fabs(term) >= 0.00001) {
sin += term;
i += 2;
term *= -x_pow / (i * (i - 1));
}
return sin;
}

int main(void) {
double x;
printf("Enter x in radians: ");
scanf("%lf", &x);
printf("sin(%.4lf) = %.4lf\n", x, sinx(x));
return 0;
}

Question no 16
#include <stdio.h>
int main()
{
int i, j, k, n = 4;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= i; j++)
{
printf("%d ", j);
}
for (k = i - 1; k >= 1; k--)
{
printf("%d ", k);
}
printf("\n");
}
return 0;
}

Question no 17
#include <stdio.h>

void merge(int a[], int b[], int c[], int n, int m)


{
int i = 0, j = 0, k = 0;
while (i < n && j < m)
{
if (a[i] < b[j])
{
c[k] = a[i];
i++;
}
else
{
c[k] = b[j];
j++;
}
k++;
}
while (i < n)
{
c[k] = a[i];
i++;
k++;
}
while (j < m)
{
c[k] = b[j];
j++;
k++;
}
}

int main()
{
int i, n = 5, m = 5;
int a[5] = {1, 3, 5, 7, 9};
int b[5] = {2, 4, 6, 8, 10};
int c[10];
merge(a, b, c, n, m);
printf("Sorted Array: ");
for (i = 0; i < n + m; i++)
{
printf("%d ", c[i]);
}
return 0;
}

Question no 18
#include <stdio.h>
#include <string.h>

int main() {
char text[100], c;
int count = 0;

printf("Enter a line of text: ");


fgets(text, 100, stdin);

printf("Enter the character to count: ");


scanf("%c", &c);

for (int i = 0; i < strlen(text); i++) {


if (text[i] == c) {
count++;
}
}
printf("The character '%c' appears %d times in the text.\n", c,
count);
return 0;
}
Question no 19 (a)
#include <stdio.h>

void add(int a[3][3], int b[3][3], int c[3][3])


{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}

int main()
{
int a[3][3], b[3][3], c[3][3];
printf("Enter elements of first matrix\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter elements of second matrix\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
scanf("%d", &b[i][j]);
}
}
add(a, b, c);
printf("Sum of two matrices is\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;

Question no 19(b)
#include <stdio.h>
int main() {
int a[3][3], b[3][3], c[3][3], i, j, k;

printf("Enter elements of first matrix:\n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}

printf("Enter elements of second matrix:\n");


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &b[i][j]);
}
}

// Initializing elements of result matrix to 0


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
c[i][j] = 0;
}
}

// Multiplying matrices a and b and storing result in c


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
for (k = 0; k < 3; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}

printf("Result matrix:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d\t", c[i][j]);
}
printf("\n");
}
return 0;
}

Question 19(C)
#include <stdio.h>

void transpose(int a[3][3]) {


int temp;
for (int i = 0; i < 3; i++) {
for (int j = i+1; j < 3; j++) {
temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
}
int main() {
int a[3][3], b[3][3];

printf("Enter elements for first matrix: \n");


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}

printf("Enter elements for second matrix: \n");


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &b[i][j]);
}
}

printf("Transpose of first matrix: \n");


transpose(a);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}

printf("Transpose of second matrix: \n");


transpose(b);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", b[i][j]);
}
printf("\n");
}

return 0;
}

Question no 20
#include<stdio.h>
#include<ctype.h>

int main(){
char line[100];
int vowels = 0, consonants = 0,
digits = 0, i;
printf("Enter a line of text: ");
fgets(line, 100, stdin);
for(i = 0; line[i] != '\0'; i++){
if(isalpha(line[i])){
if(line[i] == 'A' || line[i] == 'E' || line[i] == 'I' || line[i] == 'O'
|| line[i] == 'U' ||
line[i] == 'a' || line[i] == 'e' || line[i] == 'i' || line[i] == 'o' ||
line[i] == 'u'){
vowels++;
}
else{
consonants++;
}
}
else if(isdigit(line[i])){
digits++;
}
}
printf("Vowels: %d\nConsonants: %d\nDigits: %d\n", vowels,
consonants, digits);
return 0;
}

Question no 21
#include<stdio.h>
#include<string.h>

void replace_substring(char *str, char *old_sub, char


*new_sub){
char *p;
int len_old = strlen(old_sub);
int len_new = strlen(new_sub);
for(p = strstr(str, old_sub); p != NULL; p = strstr(p + len_new,
old_sub)){
memmove(p + len_new, p + len_old, strlen(p + len_old) + 1);
memcpy(p, new_sub, len_new);
}
}

int main(){
char line[100];
char old_sub[20], new_sub[20];
printf("Enter a line of text: ");
fgets(line, 100, stdin);
printf("Enter old substring: ");
scanf("%s", old_sub);
printf("Enter new substring: ");
scanf("%s", new_sub);
replace_substring(line, old_sub, new_sub);
printf("Modified line: %s\n", line);
return 0;
}

Question no 22
#include <stdio.h>
#include <ctype.h>

#define MAX_LENGTH 100


int main(void) {
char input[MAX_LENGTH];
int digit_counts[10] = {0};
int letter_counts[26] = {0};

printf("Enter a line of text: ");


fgets(input, MAX_LENGTH, stdin);

for (int i = 0; input[i]; i++) {


char c = tolower(input[i]);
if (isdigit(c)) {
digit_counts[c - '0']++;
} else if (isalpha(c)) {
letter_counts[c - 'a']++;
}
}

printf("Digit counts:\n");
for (int i = 0; i < 10; i++) {
printf("%d: %d\n", i, digit_counts[i]);
}

printf("Letter counts:\n");
for (int i = 0; i < 26; i++) {
printf("%c: %d\n", 'a' + i, letter_counts[i]);
}

return 0;
}

Question no 23
#include <stdio.h>
#include <math.h>
#define MAX_NUMBERS 100
int main()
{
int numbers[MAX_NUMBERS];
int count = 0;
int sum = 0;
float mean = 0.0;
float variance = 0.0;
float standard_deviation = 0.0;

// Input numbers
printf("Enter up to %d positive integers (0 to stop):\n",
MAX_NUMBERS);
while (count < MAX_NUMBERS) {
int n;
scanf("%d", &n);
if (n <= 0) break;
numbers[count++] = n;
sum += n;
}
// Calculate mean
mean = (float)sum / count;

// Calculate variance
for (int i = 0; i < count; i++) {
float diff = numbers[i] - mean;
variance += diff * diff;
}
variance /= count;

// Calculate standard deviation


standard_deviation = sqrt(variance);

// Output results
printf("Sum: %d\n", sum);
printf("Mean: %.2f\n", mean);

return 0;
}

Question no 24
#include <stdio.h>
int main()
{
char c = 'A';
int num = 1;

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


for (int j = 1; j <= i; j++) {
if (i % 2 == 1) {
printf("%d ", num++);
} else {
printf("%c ", c++);
}
}
printf("\n");
}

return 0;
}

Question no 25
#include <stdio.h>
#include <string.h>

char *less_than_twenty[] = {
"", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN",
"EIGHT", "NINE", "TEN",
"ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN",
"SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"
};

char *tens_multiple[] = {
"", "", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY",
"SEVENTY", "EIGHTY", "NINETY"
};

char *denom[] = {
"", "THOUSAND", "LAKH", "CRORE"
};

void print_word(int num, char *suffix) {


if (num == 0) {
printf("ZERO %s ", suffix);
return;
}
int x = 0;
int len = strlen(suffix);
int digits[20];
while (num > 0) {
digits[x++] = num % 10;
num /= 10;
}

int i = x;
while (i > 0) {
if (i == 4 || i == 7 || i == 10 || i == 13) {
printf("%s ", denom[x - i]);
}

if (i % 2 == 0) {
if (digits[i - 2] > 0) {
printf("%s ", tens_multiple[digits[i - 2]]);
}
if (digits[i - 1] > 0) {
printf("%s ", less_than_twenty[digits[i - 1]]);
}
}

i--;
}

if (len > 0) {
printf("%s ", suffix);
}
}

int main() {
float cost;
int rupees, paise;
printf("Enter the cost of an item in the form RRRR.PP: ");
scanf("%f", &cost);
rupees = (int) cost;
paise = (int) ((cost - rupees) * 100);
print_word(rupees, "RUPEES");
print_word(paise, "PAISE");
return 0;
}
Question no 26
#include <stdio.h>
#define N 10
int main() {
int a[N], *p;

printf("Enter %d numbers: ", N);


for (p = a; p < a + N; p++) {
scanf("%d", p);
}

printf("The numbers in reverse order are: ");


for (p = a + N - 1; p >= a; p--) {
printf("%d ", *p);
}
printf("\n");

return 0;
}
Question no 27
#include <stdio.h>
int compare_arrays(int *arr1, int *arr2, int size) {
for (int i = 0; i < size; i++) {
if (arr1[i] != arr2[i]) {
return 0;
}
}
return 1;
}

int main() {
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5] = {1, 2, 3, 4, 5};
int result = compare_arrays(arr1, arr2, 5);
printf("The arrays are %s\n", result ? "identical" : "not
identical");
return 0;
}

Question no 28
#include <stdio.h>
#include <math.h>

int isPrime(int num) {


int i;
if (num <= 1) {
return 0;
}
for (i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}

int isFibonicci(int num) {


int a = 0, b = 1, c = a + b;
while (c < num) {
a = b; b = c;
c = a + b;
}
return c == num;
}

void checkNumber(int num) {


if (isPrime(num) && isFibonicci(num)) {
printf("The number is both Prime and Fibonicci\n");
} else if (isPrime(num)) {
printf("The number is Prime\n");
} else if (isFibonicci(num)) {
printf("The number is Fibonicci\n");
} else {
printf("The number is neither Prime nor Fibonicci\n");
}
}

int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
checkNumber(num);
return 0;
}
Question no 29
#include <stdio.h>
#include <string.h>

int substring(const char s1[], const char s2[]){


const int lengthOfSubString = strlen(s1);

for (int i = 0; i < strlen(s2) - lengthOfSubString + 1; i++){


for (int j = 0; j < lengthOfSubString; j++){
if(s2[i + j] != s1[j])
break;
else if (j == lengthOfSubString - 1)
return i;
}
}
return -1;
}

void main()
{
char string[] = "thermometer";
char sub[] = "mom";
printf("%s occurs in %s at index no. %d\n", sub, string,
substring(sub, string));
}

Question no 30
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 10

struct Queue {
int front, rear;
int items[MAX_SIZE];
};

struct Queue* createQueue() {


struct Queue* q = (struct Queue*) malloc(sizeof(struct
Queue)); q->front = q->rear = -1;
return q;
}
int isEmpty(struct Queue* q) {
return q->rear == -1;
}
int isFull(struct Queue* q) {
return (q->rear + 1) % MAX_SIZE == q->front;
}

void enqueue(struct Queue* q, int item) {


if (isFull(q)) {
printf("Queue is full\n");
return;
}
q->rear = (q->rear + 1) % MAX_SIZE;
q->items[q->rear] = item;
if (q->front == -1) {
q->front = q->rear;
}
}

int dequeue(struct Queue* q) {


if (isEmpty(q)) {
printf("Queue is empty\n");
return -1;
}
int item = q->items[q->front];
if (q->front == q->rear) {
q->front = q->rear = -1;
} else {
q->front = (q->front + 1) % MAX_SIZE;
}
return item;
}

int main() {
struct Queue* q = createQueue();
enqueue(q, 1);
enqueue(q, 2);
enqueue(q, 3);
printf("Dequeued item: %d\n", dequeue(q));
printf("Dequeued item: %d\n", dequeue(q));
return 0;
}
Question no 31
#include <stdio.h>
struct time_struct { int hour;
int minute;
int second;
};

int main() {
struct time_struct time;

printf("Enter hour: ");


scanf("%d", &time.hour);
printf("Enter minute: ");
scanf("%d", &time.minute);
printf("Enter second: ");
scanf("%d", &time.second);

printf("The time is: %02d:%02d:%02d\n", time.hour,


time.minute, time.second);

return 0;
}

Question no 32
#include <stdio.h>

struct Address
{
int streetNumber;
char city[30], district[30], state[30];
};

struct Employee
{
char Emp_Name[30];
int Emp_Mobile; int Emp_Age;
char Emp_Degree[30];
float Emp_Exp;
struct Address Emp_Add;
};
void PrintEmployeeDetails(struct Employee employee){
printf("Name - %s, Mobile no. - %d, Age - %d, Degree - %s,
Experience
- %f\n", employee.Emp_Name, employee.Emp_Mobile,
employee.Emp_Age, employee.Emp_Degree,
employee.Emp_Exp);
printf("Address: %d, %s, %s, %s",
employee.Emp_Add.streetNumber, employee.Emp_Add.city,
employee.Emp_Add.district, employee.Emp_Add.state);
}

void main()
{
struct Employee employees[20];
int numberOfEmployees = 20, continueToEnter = 1;
for (int i = 0; i < 20; i++){
printf("Enter the employee name: ");
gets(employees[i].Emp_Name);

printf("Enter the mobile no.: ");


scanf("%d", &employees[i].Emp_Mobile);
printf("Enter the age.: ");
scanf("%d", &employees[i].Emp_Age); getchar();

printf("Enter the degree: ");


gets(employees[i].Emp_Degree);

printf("Enter the experience: ");


scanf("%f", &employees[i].Emp_Exp);

printf("Enter the street number: ");


scanf("%d", &employees[i].Emp_Add.streetNumber);
getchar();

printf("Enter the city: ");


gets(employees[i].Emp_Add.city);

printf("Enter the district: ");


gets(employees[i].Emp_Add.district);

printf("Enter the state: ");


gets(employees[i].Emp_Add.state);
printf("Do you want to continue? (1 for Yes, 0 for No) ");
scanf("%d", &continueToEnter);
getchar();
printf("\n");
if (!continueToEnter){
numberOfEmployees = i + 1;
break;
}
}

// struct Employee employee = {"Horace", 98178923, 23,


"MBA", 151,
{36, "Saket", "New Delhi", "Delhi"}};
// PrintEmployeeDetails();

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


printf("Employee %d:\n", i + 1);
PrintEmployeeDetails(employees[i]);
printf("\n\n");
}
}
Question no 33
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main()
{
char str[100];
int i, j, count;
int letter[26] = {0};
int digit[10] = {0};

FILE * filePtr = fopen("Input.txt", "r");

int k = 0;
char c = fgetc(filePtr);
while (c != EOF){
str[k] = c;
c = fgetc(filePtr);
k++;
}
str[k] = '\0';
fclose(filePtr);

for (i = 0; i < strlen(str); i++)


{
if (str[i] >= 'A' && str[i] <= 'Z')
{
count = str[i] - 'A';
letter[count]++;
}
else if (str[i] >= 'a' && str[i] <= 'z')
{
count = str[i] - 'a'; letter[count]++;
}
else if (str[i] >= '0' && str[i] <= '9')
{
count = str[i] - '0'; digit[count]++;
}
}

filePtr = fopen("Output.txt", "w");


fprintf(filePtr, "Frequency of letters:\n");
for (i = 0; i < 26; i++)
{
if (letter[i] > 0)
fprintf(filePtr, "%c: %d\n", (i + 'a'), letter[i]);
}

fprintf(filePtr, "Frequency of digits:\n");


for (j = 0; j < 10; j++)
{
if (digit[j] > 0)
fprintf(filePtr, "%d: %d\n", j, digit[j]);
}

fclose(filePtr);
}

Question no 34
#include <stdio.h>

void AddMatrices(int result[3][3], int mat1[3][3], int mat2[3][3])


{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
result[i][j] = mat1[i][j] + mat2[i][j];
}
}
}

void main()
{
int mat1[3][3] = {
{ 1, 2, 1 },
{ 3, 1, 6 },
{ 9, 6, 1 }
};
int mat2[3][3] = {
{ 5, 6, 3 },
{ 3, 5, 3 },
{ 1, 4, 5 }
};
int sum[3][3];
AddMatrices(sum, mat1, mat2);

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


for (int j = 0; j < 3; j++)
printf("%d ", sum[i][j]);
printf("\n");
}
}

Question no 35
#include <stdio.h>
#include <math.h>
#include <stdbool.h>

#define MAX 2500

int main() {
bool is_prime[MAX];
int i, j;
FILE *fp;

// Initialize the array with all numbers being prime


for (i = 0; i < MAX; i++) {
is_prime[i] = true;
}

// Mark multiples of 2 as non-prime


for (i = 4; i < MAX; i += 2) {
is_prime[i] = false;
}

// Use sieve of Eratosthenes to mark non-primes


for (i = 3; i <= sqrt(MAX); i += 2) {
if (is_prime[i]) {
for (j = i * i; j < MAX; j += i) { is_prime[j] = false;
}
}
}
// Open the file to write the primes
fp = fopen("primes.out", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write the prime numbers to the file
for (i = 2; i < MAX; i++) {
if (is_prime[i]) {
fprintf(fp, "%d\n", i);
}
}
// Close the file
fclose(fp);
return 0;
}

Question no 36(10)
data = {}
perks = {1:[(7000 + 3000), 0.10], 2:[(6000 + 2000), 0.08], 3:[(5000 + 1500), 0.05],
4:[(5000 + 1500), 0]}

def calculate_everything(emp_name):
# gross
try:
data[emp_name]
except:
return False
gross_ = data[emp_name][1] + (0.25*data[emp_name][1]) + perks[data[emp_name][0]][0]
tax = gross_ * perks[data[emp_name][0]][1]
net = gross_ - tax
return [gross_, tax, net]

print("Enter emp data...")

while True:
_name = input("Enter Emp name(enter q to exit): ")
if _name.lower() == 'q':
break
_level = int(input("Enter Emp level (1 to 4): "))
_base_salary = int(input("Enter Emp salary: "))

data[_name] = [_level, _base_salary]


print("Data Recorded!")

print("Searching...")

while True:
_name = input("Enter emp name to know gross and others: ")
if _name.lower() == 'q':
break
sals = calculate_everything(_name)
if sals != False:
print(f"Gross Salary: {sals[0]}\nTax: {sals[1]}\nNetSalary: {sals[2]}")
else:
print("No record found check the name entered!")

Question 36 (11)
num = input('Enter the number: ')
print(num[::-1])

Question 36(12)
# take input from the user
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))

# define a function to check if a number is prime


def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

# iterate over the range and check each number for primality
print("The prime numbers between", start, "and", end, "are:")
for num in range(start, end+1):
if is_prime(num):
print(num)

Question 36(13)
# define a function to calculate HCF
def calculate_hcf(num1, num2):
# choose the smaller number
if num1 > num2:
smaller = num2
else:
smaller = num1
hcf = 1
# find the HCF
for i in range(1, smaller+1):
if((num1 % i == 0) and (num2 % i == 0)):
hcf = i
return hcf

# take input from the user


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# calculate and display the HCF


print("The HCF of", num1, "and", num2, "is", calculate_hcf(num1, num2))

Question 36(14)
# take input from the user
m = int(input("Enter the value of m: "))

# initialize the first two Fibonacci numbers


fibonacci = [0, 1]

# calculate the remaining Fibonacci numbers


for i in range(2, m):
next_fibonacci = fibonacci[i-1] + fibonacci[i-2]
fibonacci.append(next_fibonacci)

# display the Fibonacci sequence


print("The first", m, "Fibonacci numbers are:")
for num in fibonacci:
print(num)
Question 36(15)
import math

# take input from the user


x = float(input("Enter the value of x (in degrees): "))

# convert x to radians
x = math.radians(x)

# initialize variables
term = x
sin_x = x
n = 1
error = 1

# calculate the sine function using the series expansion


while error > 0.0001:
term *= -x**2 / ((2*n)*(2*n+1))
sin_x += term
error = abs(term / sin_x)
n += 1

# display the result


print("The sine of", math.degrees(x), "degrees is:", sin_x)

Question 36(16)
n = 5 # size of the middle row

# upper half of the pattern


for i in range(1, n+1):
# print spaces before the numbers
print(" "*(n-i), end="")
# print the numbers in increasing order
for j in range(1, i+1):
print(j, end="")
# print the numbers in decreasing order
for j in range(i-1, 0, -1):
print(j, end="")
print()

# lower half of the pattern


for i in range(n-1, 0, -1):
# print spaces before the numbers
print(" "*(n-i), end="")
# print the numbers in increasing order
for j in range(1, i+1):
print(j, end="")
# print the numbers in decreasing order
for j in range(i-1, 0, -1):
print(j, end="")
print()

Question 36(17)
A = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
B = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
C = []

i = 0 # index for array A


j = 0 # index for array B

while i < len(A) and j < len(B):


if A[i] <= B[j]:
C.append(A[i])
i += 1
else:
C.append(B[j])
j += 1

# add remaining elements from array A


while i < len(A):
C.append(A[i])
i += 1

# add remaining elements from array B


while j < len(B):
C.append(B[j])
j += 1

print(C)

Question 36(18)
def count_char_occurrences(text, char):
count = 0
for c in text:
if c == char:
count += 1
return count

# Example usage
text = "The quick brown fox jumps over the lazy dog"
char = 'o'

print(f"The character '{char}' appears {count_char_occurrences(text, char)} times in the


text.")
Question 37
MAX_MARKS = 100

def calculate_percentage(marks):
total_marks = sum(marks)
percentage = (total_marks / (len(marks) * MAX_MARKS)) * 100
return percentage

# Example usage
try:
marks = [75, 85, 92]
# marks = [75, 85, 102]
for mark in marks:
if mark > MAX_MARKS:
raise ValueError(f"Mark {mark} is greater than the maximum marks
({MAX_MARKS})")
percentage = calculate_percentage(marks)
print(f"The percentage of marks is: {percentage:.2f}%")
except ValueError as e:
print(f"Error: {e}")

Question 38
# Define the employee records as a list of dictionaries
employees = [
{'name': 'Alice', 'age': 30, 'department': 'Sales', 'salary': 50000},
{'name': 'Bob', 'age': 40, 'department': 'Marketing', 'salary': 60000},
{'name': 'Charlie', 'age': 50, 'department': 'Finance', 'salary': 70000},
]

# Print the entire collection of employee records


print("Initial collection of employee records:")
print(employees)

# Access and print the individual components of the first record using indexing
print("\nAccessing individual components of the first record:")
print(f"Name: {employees[0]['name']}")
print(f"Age: {employees[0]['age']}")
print(f"Department: {employees[0]['department']}")
print(f"Salary: {employees[0]['salary']}")

# Modify the department of the second record using indexing


print("\nModifying the department of the second record:")
employees[1]['department'] = 'IT'
print(employees)
# Add a new employee record to the collection using indexing
print("\nAdding a new employee record:")
new_employee = {'name': 'Dave', 'age': 35, 'department': 'HR', 'salary': 55000}
employees.append(new_employee)
print(employees)

Question 39
# Open the input file in read mode
with open('input.txt', 'r') as f1:
# Read the contents of the input file
contents = f1.read()

# Open the output file in write mode


with open('output.txt', 'w') as f2:
# Write the contents to the output file
f2.write(contents)

You might also like