0% found this document useful (0 votes)
16 views12 pages

Top-Down Design in C Programming

The document outlines a week-end assignment for students in the Department of Computer Science and Engineering, focusing on top-down design and modular programming using functions. It includes various programming tasks, such as calculating the area and circumference of a circle, computing taxi fares, and converting numbers between bases, with specific instructions for implementation and expected outputs. Students are encouraged to develop their own programs without copying from sources and to demonstrate their understanding of systems programming concepts.

Uploaded by

sinhashourya02
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)
16 views12 pages

Top-Down Design in C Programming

The document outlines a week-end assignment for students in the Department of Computer Science and Engineering, focusing on top-down design and modular programming using functions. It includes various programming tasks, such as calculating the area and circumference of a circle, computing taxi fares, and converting numbers between bases, with specific instructions for implementation and expected outputs. Students are encouraged to develop their own programs without copying from sources and to demonstrate their understanding of systems programming concepts.

Uploaded by

sinhashourya02
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

Department of Computer Science and Engineering

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


W EEK -END A SSIGNMENT -04
Top-Down Design with Functions
Operating Systems Workshop (CSE 3541)

Problem Statement:
Demonstrate the top-down design method of problem solving and emphasize the role of modular program-
ming using functions.

Assignment Objectives:
To learn about functions and how to use them to write programs with separate modules.

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. Describe the problem input(s), output(s) and write the algorithm for a program that computes the
circle’s area and circumference. Also write a function prototype to compute the same using radius as
input to the function and return type void.

Input, Output, Algorithm and Function Prototype ▼


#include <stdio.h> Enter the radius of the circle: 15
#include <math.h> Area of the circle: 706.86
void calculateCircleProperties(double radius, double area, double circumference){
area = M_PI * radius * radius; Circumference of the circle: 94.25
circumference = 2 * M_PI * radius;
}
int main() {
double radius, area, circumference;
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
calculateCircleProperties(radius, &area, &circumference);
printf("Area of the circle: %.2lf\n", area);
printf("Circumference of the circle: %.2lf\n", circumference);
return 0;
}

2. During execution of the following program segment, how many lines of star marks will be displayed?
Output
void nonsense(void){
printf("*****\n"); *****
printf("* *\n"); * *
printf("*****\n"); *****
*****
} * *
int main(void){ *****
nonsense(); *****
nonsense(); * *
*****
nonsense();
return (0);
}

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

3. Consider the following C program; [GATE 2004]


The program computes
int main(void){
int x,y,m,n; (a) x + y using repeated subtraction
scanf("%d%d",&x,&y);
/* Assume x > 0 and y > 0 */ (b) x mod y using repeated subtraction
m = x; n = y;
while(m!=n){ (c) the greatest common divisor of x and y
if(m>n) (d) the least common multiple of x and y
m=m-n;
else
Output▼
n=n-m;
}
printf("%d",n); the greatest common divisor of x
and y
}

4. What does the following algorithm approximate? (Assume m > 1, e > 0). [GATE 2004]
The program computes
1
x = m; y = 1; (c) m 2
(a) log m
while (x - y > e){ 1
(d) m 3
x = (x + y) / 2; (b) m2
y = m/x;
} `▼
printf("%d",x);
m 1/2

5. Consider the following two functions. [GATE 2017]


Find the output when fun1(15) is called;
void fun1(int n) void fun2(int n) Output▼
{ { 53423122222445
if(n==0) if(n==0)
return; return; 53423120112233
printf("%d",n); printf("%d",n);
fun2(n-2); fun1(++n); 53423122132435
printf("%d",n); printf("%d",n);
53423120213243
} }

6. The output of executing the following C program is; GATE

int total(int v){ int main(){ Output▼


int count=0; int x=0,i=5;
while(v){ for( ; i>0; i--){
count +=v&1; x=x+total(i);
v>>=1; } How many times the function call,
} printf("%d\n",x); total(), is called?
return count; return 0;
} }

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

7. Consider the following C function;


int fun(n){
int i,j; Output▼
for(i=1;i<=n;i++){ Determine the number of times the
for(j=1;j<n;j++){ printf() will be executed if n=5.
printf("%d %d\n",i,j);
} ANS – 5 times
}
return 1;
}

8. Write a program that prompts the user for the two legs of a right triangle and makes use of the pow
and sqrt functions and the Pythagorean theorem to compute the length of the hypotenuse.

Space for Program and output ▼

#include <stdio.h> OUTPUT------


#include <math.h>
Enter the length of the first
int main() { leg: 5
double leg1, leg2, hypotenuse; Enter the length of the
second leg: 4
The length of the
printf("Enter the length of the first leg: "); hypotenuse is: 6.403124
scanf("%lf", &leg1);

printf("Enter the length of the second leg: ");


scanf("%lf", &leg2);
hypotenuse = sqrt(pow(leg1, 2) + pow(leg2, 2));
printf("The length of the hypotenuse is: %lf\n", hypotenuse);

return 0;
}

9. Write the prototype for a function called script that has three input parameters. The first parameter
will be the number of spaces to display at the beginning of a line. The second parameter will be the
character to display after the spaces, and the third parameter will be the number of times to display
the second parameter on the same line and return type of the function is of integer.

Function Prototype/ Declaration/ Signature ▼


int script(int numSpaces, char character, int numTimes);
numspaces represt the no f spaces to display in the beginning of a line
character display after the spaces
numTImes represent the number of times to display the character on the same line

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

10. In a particular jurisdiction, taxi fares consist of a base fare of $4.00, plus $0.25 for every 140 meters
traveled. Write a function that takes the distance traveled (in kilometers) as its only parameter and
returns the total fare as its only result. Write a main program that demonstrates the function.
Hint: Taxi fares change over time. Use constants to represent the base fare and the variable portion
of the fare so that the program can be updated easily when the rates increase.

Space for Program Output ▼


#include <stdio.h>
const double BASE_FARE = 4.00;
const double RATE_PER_METER = 0.25 / 140.0;
double calculateTaxiFare(double distanceInKilometers) {
double fare = BASE_FARE + (distanceInKilometers *
RATE_PER_METER);
return fare;
}

int main() {
double distanceInKilometers, totalFare;
printf("Enter the distance traveled in kilometers: ");
scanf("%lf", &distanceInKilometers);
totalFare = calculateTaxiFare(distanceInKilometers);
printf("Total fare: $%.2lf\n", totalFare);

return 0;
}

OUTPUT------------
Enter the distance traveled in kilometers: 2.5
Total fare: $7.14

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

11. Create a function named nextPrime that finds and returns the first prime number larger than some
integer, n. The value of n will be passed to the function as its only parameter. The main function in
the program that reads an integer from the user and displays the first prime number larger than the
entered value. Additionally, your program must specify the function prototype and identify the actual
argument(s) and formal parameters.

Space for Program Output ▼


#include <stdio.h>
#include <stdbool.h>
int nextPrime(int n);

bool isPrime(int num);

int main() {
int n, prime;

printf("Enter an integer (n): ");


scanf("%d", &n);

prime = nextPrime(n);

printf("The first prime number larger than %d is: %d\n", n,


prime);

return 0;
}

int nextPrime(int n) {
int num = n + 1;
while (true) {
if (isPrime(num)) {
return num;
}
num++;
}
}
bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

Enter an integer (n): 6


The first prime number larger than 6 is: 7

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

12. Write a program that allows the user to convert a number from one base to another. Your program
should support bases between 2 and 16 for both the input number and the result number. If the user
chooses a base outside of this range then an appropriate error message should be displayed and the
program should exit. Divide your program into several functions, including a function that converts
from an arbitrary base to base 10, a function that converts from base 10 to an arbitrary base, and a
main program that reads the bases and input number from the user.

Space for Program Output ▼


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

int convertToBase10(char number[], int base);

void convertFromBase10(int decimalNumber, int targetBase);

int main() {
int sourceBase, targetBase, decimalNumber;
char inputNumber[50];

printf("Enter the source base (between 2 and 16): ");


scanf("%d", &sourceBase);
printf("Enter the target base (between 2 and 16): ");
scanf("%d", &targetBase);

if (sourceBase < 2 || sourceBase > 16 || targetBase < 2 || targetBase >


16) {
printf("Invalid base. Bases should be between 2 and 16.\n");
return 1; // Exit program with an error code
}

printf("Enter the number in base-%d: ", sourceBase);


scanf("%s", inputNumber);

decimalNumber = convertToBase10(inputNumber, sourceBase);

printf("Converted to base-%d: ", targetBase);


convertFromBase10(decimalNumber, targetBase);

return 0;
}

int convertToBase10(char number[], int base) {


int decimalNumber = 0;
int length = strlen(number);

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


int digitValue;

if (number[i] >= '0' && number[i] <= '9') {


digitValue = number[i] - '0';
} else if (number[i] >= 'A' && number[i] <= 'F') {

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

Space for Program Output ▼


digitValue = number[i] - 'A' + 10;
} else {
printf("Invalid digit in the input number.\n");
exit(1); // Exit program with an error code
}

if (digitValue >= base) {


printf("Invalid digit for base-%d.\n", base);
exit(1); // Exit program with an error code
}

decimalNumber = decimalNumber * base + digitValue;


}

return decimalNumber;
}

void convertFromBase10(int decimalNumber, int targetBase) {


char result[50];
int index = 0;

while (decimalNumber > 0) {


int remainder = decimalNumber % targetBase;
char digit;

if (remainder < 10) {


digit = '0' + remainder;
} else {
digit = 'A' + (remainder - 10);
}

result[index++] = digit;
decimalNumber /= targetBase;
}

if (index == 0) {
printf("0\n");
} else {
for (int i = index - 1; i >= 0; i--) {
printf("%c", result[i]);
}
printf("\n");
}
}

OUTPUT-------

Enter the source base (between 2 and 16): 5


Enter the target base (between 2 and 16): 10
Enter the number in base-5: 8
Converted to base-10: 13

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

13. Write a program that calculates the speed of sound ( a ) in air of a given temperature T (◦F ). Formula
to compute the speed in ft/sec: r
5T + 297
a = 1086
247
Be sure your program does not lose the fractional part of the quotient in the formula shown. As part
of your solution, write and call a function that displays instructions to the program user.

Space for Program Output ▼

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

// Function to display instructions to the user


void displayInstructions() {
printf("This program calculates the speed of sound in air based on
temperature.\n");
printf("Please enter the temperature in degrees Fahrenheit.\n");
}

int main() {
double temperature, speedOfSound;

// Display instructions
displayInstructions();

// Input temperature in Fahrenheit


printf("Enter the temperature in degrees Fahrenheit: ");
scanf("%lf", &temperature);

// Calculate the speed of sound using the formula


speedOfSound = 1086 * sqrt((5 * temperature + 297) / 247.0);

// Display the result


printf("The speed of sound in air at %.2lf degrees Fahrenheit is %.2lf
ft/sec.\n", temperature, speedOfSound);

return 0;
}

OUTPUT------

This program calculates the speed of sound in air based on temperature.


Please enter the temperature in degrees Fahrenheit.
Enter the temperature in degrees Fahrenheit: 50
The speed of sound in air at 50.00 degrees Fahrenheit is 1090.53 ft/sec.

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

14. After studying the population growth of Gotham City in the last decade of the 20th century, we have
modeled Gotham’s population function as

P (t) = 52.966 + 2.184t

where t is years after 1990, and P is population in thousands. Thus, P (0) represents the population in
1990, which was 52.966 thousand people. Write a program that defines a function named population
that predicts Gotham’s population in the year provided as an input argument. Write a program that
calls the function and interacts with the user as follows:
Enter a year after 1990> 2015
Predicted Gotham City population for 2010 (in thousands): 107.566

Space for Program Output ▼

#include <stdio.h>

// Function to predict Gotham City's population based on the given function


double population(int year) {
return 52.966 + 2.184 * (year - 1990);
}

int main() {
int year;
double predictedPopulation;

// Prompt the user to enter a year after 1990


printf("Enter a year after 1990: ");
scanf("%d", &year);

// Calculate the predicted population using the function


predictedPopulation = population(year);

// Display the predicted population


printf("Predicted Gotham City population for %d (in thousands): %.3lf\n",
year, predictedPopulation);

return 0;
}

OUTPUT---------
Enter a year after 1990: 1920
Predicted Gotham City population for 1920 (in thousands): -40.578

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

Space for Program Output ▼

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

15. Positions on a chess board are identified by a two digit number from 11 to 88. The unit place digit
identifies the column, while the 10th place digit identifies the row, as shown below:

Row Position: 1 t0 8
Valid position

43
Row- 4
Column-3

1 2 3 4 5 6 7 8
Column Positions: 1 to 8

Write a program that reads a position ( i.e. 2 digit number) from the user. Write a use-defined
function to check whether 2 digit position is a valid cell or not as per the function protoype int
flag=IsvalidPosition (int);. If the position is valid, use an if statement to determine if
the column begins with a black square or a white square then report the color of the square in that
row. For example, if the user enters 11 then your program should report that the square is black. If
the user enters 34 then your program should report that the square is white.

Space for Program Output ▼

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

Space for Program Output ▼

#include <stdio.h>

// Function to check if the position is a valid cell


int isValidPosition(int position) {
return (position >= 11 && position <= 88 && (position % 10 >= 1 &&
position % 10 <= 8));
}

int main() {
int position;

// Input the position from the user


printf("Enter a 2-digit position (11-88): ");
scanf("%d", &position);

// Check if the position is valid


if (isValidPosition(position)) {
// Determine the color of the square
int row = position / 10;
int column = position % 10;

// Check if the column begins with a black square (odd number) or a white
square (even number)
if ((row % 2 == 1 && column % 2 == 1) || (row % 2 == 0 && column %
2 == 0)) {
printf("The square is black.\n");
} else {
printf("The square is white.\n");
}
} else {
printf("Invalid position. Please enter a valid 2-digit position between 11
and 88.\n");
}

return 0;
}

OUTPUT------------
Enter a 2-digit position (11-88): 55
The square is black.

12

You might also like