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

Osw Assignment 3

This document contains an assignment for an operating systems workshop course. It asks students to write programs using repetition control structures like for, while, and do-while loops. It provides 5 programming questions as examples for students to practice with, including questions to find the output of code snippets using loops and developing a program to check if a number is divisible by 9. It also asks students to write a program to calculate the greatest common divisor of two numbers.

Uploaded by

Debarchan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views

Osw Assignment 3

This document contains an assignment for an operating systems workshop course. It asks students to write programs using repetition control structures like for, while, and do-while loops. It provides 5 programming questions as examples for students to practice with, including questions to find the output of code snippets using loops and developing a program to check if a number is divisible by 9. It also asks students to write a program to calculate the greatest common divisor of two numbers.

Uploaded by

Debarchan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Department of Computer Science and Engineering

Institute of Technical Education & Research, SOA, Deemed to be University

W EEK -E ND A SSIGNMENT-03
Operating Systems Workshop (CSE 3541)

Problem Statement:
Working with repetition control structure (for, while and do-while) in programming.

Assignment Objectives:
To learn how to use C repetition control structure in programming and when to use each type in developing
programs.

Instruction to Students (If any):


Students are required to write his/her own program by avoiding any kind of copy from any sources.
Additionally, They must be able to realise the outcome of that question in relevant to systems pro-
gramming. You may use additional pages on requirement.

Programming/ Output Based Questions:


1. Find the output/ error of following code snippet
Code snippet: 1(a)
Output
int i = 0;
0 10
while (i <= 5) { 1 9
printf("%3d %3d\n", i, 10 - i); 2 8
i = i + 1; 3 7
} 4 6
5 5

Code snippet: 1(b)


int i=l; Output
while ( )
{
1 2 3 4 5 6 7 8 9 10
printf ( "%d ", i++ ) ;
if(i>10)
break ;
}

Output
Code snippet: 1(c)
123456789
int a=1;
do {
printf("%d ", a++);
} while ( a < 10 );

1
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

Output
Code snippet: 1(d) 11
int i, j,n=5; 31
for(i=1, j=1; j<= n; i+= 2, j++){ 51
71
printf("%d%d\n", i, j); 91
}

Output

count down is 0
Code snippet: 1(e)
int count = 11;
while (--count+l);
printf("count down is %d \n",count);

Code snippet: 1(e) Output


float x = 1.1 ; 1.1
while ( x == 1.1 ) {
printf ( "%f\n", x ) ;
x = x - 0.1 ;
}

2. During execution of the following program segment, how many lines of hash marks are displayed?
Output

45
for (m = 9; m > 0; --m)
for (n = 6; n > 1; --n)
printf("#########\n");

3. During execution of the following program segment:

a. How many times does the first call to printf execute?


b. How many times does the second call to printf execute?
c. What is the last value displayed?

Outputt
for (m = 10; m > 0; --m){ a. 10 times
for (n = m; n > 1; --n)
printf("%d ", m + n); b. 9 times
printf("\n"); c. The last value
} displayed is 1,
2
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

4. An integer n is divisible by 9 if the sum of its digits is divisible by 9. Develop a program to display
each digit, starting with the rightmost digit. Your program should also determine whether or not the
number is divisible by 9. Test it on the following numbers:
n = 154368
n = 621594
n = 123456
Hint: Use the % operator to get each digit; then use / to remove that digit. So 154368 % 10 gives 8
and 154368 / 10 gives 15436. The next digit extracted should be 6, then 3 and so on.

Space for Program and output t

#include <stdio.h>

int main() {
int n, sum, digit;

printf("Enter a number: ");


scanf("%d", &n);

sum = 0;
while (n > 0) {
digit = n % 10;
sum += digit;
n /= 10;
}

if (sum % 9 == 0) {
printf("%d is divisible by 9.\n", n);
} else {
printf("%d is not divisible by 9.\n", n);
}

printf("The digits of %d, starting with the rightmost digit, are: ", n);
while (n > 0) {
digit = n % 10;
printf("%d ", digit);
n /= 10;
}

printf("\n");

return 0;
}

Output:-
Enter a number: 154368
154368 is divisible by 9.
The digits of 154368, starting with the rightmost digit, are: 8 6 3 4 1 5

3
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

5. The greatest common divisor (gcd) of two integers is the product of the integers common factors.
Write a program that inputs two numbers and implements the following approach to finding their gcd.
We will use the numbers −252 and 735. Working with the numbers’ absolute values, we find the
remainder of one divide by the other.

0
735 252
- 0
252

Now we calculate the remainder of the old divisor divided by the remainder found.

2
252 735
- 504
231

We repeat this process until the remainder is zero.


11
1 21 231
231 252 - 21
Ü
- 231 21
21 - 21
0

The last divisor (21) is the gcd.


Space for Program and output t

4
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

Space for Program and output t

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

int gcd(int a, int b) {


// Calculate the absolute values of a and b.
a = abs(a);
b = abs(b);

// While b is not equal to 0, find the remainder of a divided by b and assign the remainder to a.
while (b != 0) {
int remainder = a % b;
a = b;
b = remainder;
}

// Return the value of a, which is now the gcd of a and b.


return a;
}

int main() {
int a, b;

printf("Enter two numbers: ");


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

// Find the gcd of a and b.


int gcd = gcd(a, b);

// Print the gcd to the console.


printf("The gcd of %d and %d is %d.\n", a, b, gcd);

return 0;
}

Enter two numbers: -252 735


The gcd of -252 and 735 is 9.

5
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

6. Write a program to process a collection of the speeds of vehicles. Your program should count and
print the number of vehicles moving at a high speed (90 miles/hour or higher), the number of vehicles
moving at a medium speed (50-89 miles/hour), and the number of vehicles moving at a slow speed
(less than 50 miles/hour). It should also display the category of each vehicle. Test your program on
the following data in a file:
43 23 54 57 68 67 51 90 33 22 11 88 34 52 75 12 78 32 89 14 65 67 97
53 10 47 34

a. Also code to display the average speed of a category of vehicle (a real number) at the end of the
run.
b. Store the data into a file vspeed.txt. Use input redirection to read all numbers from that file.
(i.e. ./a.out < vspeed.txt)
c. While reading the input from the file, apply the idea of scanf function returns. The scanf
returns: (1) On success, this function returns the number of input items successfully matched and assigned (ii) The
value EOF is returned if the end of input is reached before either the first successful conversion or a matching
failure occurs.

Space for Program and output t

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

typedef struct {
int s;
int c;
} V;

int cvic(V* v, int n, int c) {


int count = 0;
for (int i = 0; i < n; i++) {
if (v[i].c == c) {
count++;
}
}
return count;
}

float cavic(V* v, int n, int c) {


float averageSpeed = 0.0f;
int count = cvic(v, n, c);
for (int i = 0; i < n; i++) {
if (v[i].c == c) {
averageSpeed += v[i].s;
}
}
return averageSpeed / count;
}

6
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

Space for Program and output t

void dr(V* v, int n) {


printf("Number of high speed vehicles: %d\n", cvic(v, n, SPEED_CATEGORY_HIGH));
printf("Number of medium speed vehicles: %d\n", cvic(v, n,
SPEED_CATEGORY_MEDIUM));
printf("Number of low speed vehicles: %d\n", cvic(v, n, SPEED_CATEGORY_LOW));
printf("Average high speed: %.2f mph\n", cavic(v, n, SPEED_CATEGORY_HIGH));
printf("Average medium speed: %.2f mph\n", cavic(v, n,
SPEED_CATEGORY_MEDIUM));
printf("Average low speed: %.2f mph\n", cavic(v, n, SPEED_CATEGORY_LOW));
}

void rvif(V* v, int n, char f) {


FILE* file = fopen(f, "r");
if (file == NULL) {
printf("Error opening file: %c\n", f);
exit(1);
}

int speed;
int count = 0;
while ((fscanf(file, "%d", &speed)) != EOF) {
v[count].s = speed;
v[count].c = (speed >= SPEED_CATEGORY_HIGH) ? SPEED_CATEGORY_HIGH :
(speed >= SPEED_CATEGORY_MEDIUM) ? SPEED_CATEGORY_MEDIUM :
SPEED_CATEGORY_LOW;
count++;
}

fclose(file);
}

int main() {
V* v = malloc(sizeof(V) * 100);
if (v == NULL) {
printf("Error allocating memory for vehicles.\n");
exit(1);
}

rvif(v, 100, 'f');

dr(v, 100);

free(v);

return 0;
}

7
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

7. A baseball player’s batting average is calculated as the number of hits divided by the official number
of at-bats. In calculating official at-bats, walks, sacrifices, and occasions when hit by the pitch are
not counted. Write a program that takes an input file containing player numbers and batting records.
Trips to the plate are coded in the batting record as follows: H-hit, O-out, W-walk, S-sacrifice, P-hit
by pitch. The program should output for each player the input data followed by the batting average.
Each batting record is followed by a newline character. Your program should not use any kind of
array and array processing.
Corresponding output:

Sample input file: Player 12’s record: HOOOWSHHOOHPWWHO


Player 12’s batting average: 0.455
Player 4’s record: OSOHHHWWOHOHOOO
12 HOOOWSHHOOHPWWHO Player 4’s batting average: 0.417
4 OSOHHHWWOHOHOOO Player 7’s record: WPOHOOHWOHHOWOO
7 WPOHOOHWOHHOWOO Player 7’s batting average: 0.364

Space for Program and output t


#include <stdio.h>

int main() {
// Open the input file.
FILE* input_file = fopen("input.txt", "r");
if (input_file == NULL) {
printf("Error opening input file.\n");
return 1;
}

// Read the player number and batting record from the input file.
int player_number;
char batting_record[100];
while (fscanf(input_file, "%d %s", &player_number, batting_record) != EOF) {
// Calculate the number of hits and at-bats for the player.
int hits = 0;
int at_bats = 0;
for (int i = 0; i < strlen(batting_record); i++) {
if (batting_record[i] == 'H') {
hits++;
} else if (batting_record[i] == 'O') {
at_bats++;
}
}

// Calculate the player's batting average.


float batting_average = (float) hits / at_bats;

// Output the player's record and batting average.


printf("Player %d's record: %s\n", player_number, batting_record);
printf("Player %d's batting average: %.3f\n", player_number, batting_average);
}

// Close the input file.


fclose(input_file);

return 0;
}
8
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

Space for Program and output t

9
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

8. Write a program to process a collection of scores obtained by students of a class of certain strength.
Your program should count and print the number of students with Grade A ( 80 and higher), Grade
B(65-79), Grade C(40-64) and Grade F(39 and below). Ensure that the entered scores must remain in
between 0 and 100(inclusive). Test your program on the following data:
8
23 67 65 12
89 32 17 45
41 58 60 78
82 88 19 22
70 88 41 89
78 79 72 68
74 59 75 81
44 59 23 12

a. Read the same input from a file using input redirection. First line represents number of students
and rest of the lines represent the marks obtained by each student in 4 subjects.
b. Display average score and grade of each student in form of a table.(Hint: Average score of a
student=(m1 + m2 + m3 + m4 )/4. where mi , i = 1, 2, 3, 4 represent mark in subject i and
calculate grade according to the specified condition given above.

Space for Program and output t


#include <stdio.h>

#define GRADE_A 80
#define GRADE_B 65
#define GRADE_C 40
#define GRADE_F 0

typedef struct {

int scores[4];
float average_score;
char grade;
} Student;

// Function to read the scores of a student from a file.


void readStudentScoresFromFile(Student* student, FILE* file) {
for (int i = 0; i < 4; i++) {
fscanf(file, "%d", &student->scores[i]);
}
}
float calculateAverageScore(Student* student) {
float average_score = 0.0f;
for (int i = 0; i < 4; i++) {
average_score += student->scores[i];
}
return average_score / 4.0f;
}
char calculateGrade(Student* student) {
float average_score = calculateAverageScore(student);
if (average_score >= GRADE_A) {
return 'A';
} else if (average_score >= GRADE_B) {
return 'B';
} else if (average_score >= GRADE_C) {
return 'C'; 10
} else {
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

Space for Program and output t

return 'F';
}
}

// Function to count the number of students with each grade.


int countStudentsWithGrade(Student* students, int num_students, char grade) {
int count = 0;
for (int i = 0; i < num_students; i++) {
if (students[i].grade == grade) {
count++;
}
}
return count;
}

// Function to display the average score and grade of each student in the form of a table.
void displayStudentScoresTable(Student* students, int num_students) {
printf("Student Number\tAverage Score\tGrade\n");
for (int i = 0; i < num_students; i++) {
printf("%d\t\t%.2f\t\t%c\n", i + 1, students[i].average_score, students[i].grade);
}
}

int main() {
// Open the input file.
FILE* input_file = fopen("input.txt", "r");
if (input_file == NULL) {
printf("Error opening input file.\n");
return 1;
}

// Read the number of students from the input file.


int num_students;
fscanf(input_file, "%d", &num_students);

// Allocate an array to store the student data.


Student* students = malloc(sizeof(Student) * num_students);
if (students == NULL) {
printf("Error allocating memory for students.\n");
return 1;
}

// Read the scores of each student from the input file.


for (int i = 0; i < num_students; i++) {
readStudentScoresFromFile(&students[i], input_file);
}

// Calculate the average score and grade of each student.


for (int i = 0; i < num_students; i++) {
students[i].average_score = calculateAverageScore(&students[i]);
students[i].grade = calculateGrade(&students[i]);
}

// Count the number of students with each grade.


int num_students_with_grade_a = countStudentsWithGrade(students, num_students, 'A');
int num_students_with_grade_b = countStudentsWithGrade(students, num_students, 'B');
int num_students_with_grade_c = countStudentsWithGrade(students, num_students, 'C');
11
int num_students_with_grade_f = countStudentsWithGrade(students, num_students, 'F');
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

9. Design a C program to display the following pattern;


A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
A B C D D C B A
A B C C B A
A B B A
A A

Write/paste your code here t

#include <stdio.h>

int main() {
int n = 7;

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


for (int j = 0; j < n; j++) {
if (i + j >= n - 1 && i - j <= n - 1) {
printf("%c", 'A' + n - i - 1);
} else {
printf(" ");
}
}
printf("\n");
}

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


for (int j = 0; j < n; j++) {
if (i + j >= n - 1 && j - i <= n - 2) {
printf("%c", 'A' + n - i - 1);
} else {
printf(" ");
}
}
printf("\n");
}

return 0;
}

12
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

10. The natural logarithm can be approximated by the following series.


 2  3  4
x−1 1 x−1 1 x−1 1 x−1
+ + + + ...
x 2 x 2 x 2 x
If x is input through the keyboard, write a program to calculate the sum of first nine terms of this
series.
Space for Program and output t

#include <stdio.h>
#include <math.h>

int main() {
// Get the input value for x.
float x;
printf("Enter a value for x: ");
scanf("%f", &x);

// Calculate the sum of the first nine terms of the series.


float sum = 0.0f;
for (int i = 1; i <= 9; i++) {
sum += (x - 1.0f / x) * powf(x - 1.0f / x, i) / i;
}

// Print the sum.


printf("The sum of the first nine terms of the series is: %.6f\n", sum);

return 0;
}

13
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

11. Write a menu driven program which has following options:

1. Factorial of a number.
2. Prime or not
3. Odd or even
4. Exit

Use input-validation loop and program should terminate only when option 4 is selected.

Space for Program and output t

#include <stdio.h>

int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}

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

int isEven(int n) {
return (n % 2 == 0);
}

int main() {
int option;
int number;

do {
printf("Menu:\n");
printf("1. Factorial of a number\n");
printf("2. Prime or not\n");
printf("3. Odd or even\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &option);

);

14
Department of Computer Science and Engineering
Institute of Technical Education & Research, SOA, Deemed to be University

Space for Program and output t

if (option < 1 || option > 4) {


printf("Invalid option. Please enter again.\n");
} else {
switch (option) {
case 1:
printf("Enter a number: ");
scanf("%d", &number);
printf("The factorial of %d is %d.\n", number, factorial(number));
break;
case 2:
printf("Enter a number: ");
scanf("%d", &number);
if (isPrime(number)) {
printf("%d is a prime number.\n", number);
} else {
printf("%d is not a prime number.\n", number);
}
break;
case 3:
printf("Enter a number: ");
scanf("%d", &number);
if (isEven(number)) {
printf("%d is an even number.\n", number);
} else {
printf("%d is an odd number.\n", number);
}
break;
case 4:
printf("Exiting the program.\n");
break;
}
}
} while (option != 4);

return 0;
}

15

You might also like