0% found this document useful (0 votes)
9 views4 pages

Complete the C Program Statements

This document is a homework assignment for CS 222, detailing various programming tasks and questions related to C programming concepts. It includes exercises on temperature conversion, cumulative sums, scope of identifiers, string manipulation, and structures. The assignment is due on February 28, 2025, and is worth a maximum of 100 points.

Uploaded by

fahoodyalmutairy
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)
9 views4 pages

Complete the C Program Statements

This document is a homework assignment for CS 222, detailing various programming tasks and questions related to C programming concepts. It includes exercises on temperature conversion, cumulative sums, scope of identifiers, string manipulation, and structures. The assignment is due on February 28, 2025, and is worth a maximum of 100 points.

Uploaded by

fahoodyalmutairy
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

Student Name: ________________________________ Student ID: _______________________

CS 222 – Homework #2 – Spring 2025


Instructions: Please provide or choose the most appropriate answer. Max score is 100 points. Due 2/28.

1. (25 points total) On slide 8 of lecture Week3_Class1, there’s code to convert Celsius (oC) to Fahrenheit
(oF) temperatures based on Figure 5.8 from the textbook. The code below converts from oF to oC.
a) (20 pts) Please fill in the printf below and circles/rows for the table by tracing program’s for loop.
Trace for loop execution fahrenheit celsius oop printf
Complete trace of for (enter line number) condition output
loop by completing
1 #include <stdio.h> the table and filling in
11(1) fahrenheit
2 empty circles with the
F I 42.0
#define 42.0 line # for each step
4 #define M T 2 True
5 #define ST 10
12(2) fahrenheit F IMIT 42 42.0 32
7
8
int main() {
float fahrenheit,
42 5.6
celsius; 1
(5) prin ( .1f F .1f C , 42.0 F
10 17
fahrenheit, celsius)
42 5.6 5. C
11 for (fahrenheit = ;
12 fahrenheit >= M T;
1 fahrenheit -= ST ) 32
14
15
{
celsius = (fahrenheit 2) 5.0 .0;
32 True 32>=32

1
17
printf("%.1f = %.1f \n",
___________, ___________);
15(4) c (f 32) 5.0 / 9.0 32 0.0
fahrenheit Celsius
18 }
1 32 0 32F=0 C

20 } end main
13(3) fahrenheit FST P 22.0
Please
Please fill in
complete
these arguments 22 False (22<32)

xits for loop

N
b) (5 points) Would (fahrenheit - 32) * 5 / 9 and 5 / 9 * (fahrenheit - 32) be equivalent? (Y or N): _____
No, because 5 / 9 performs integer division (resulting in 0), whereas (fahrenheit - 32) * 5 /
Explain (note fahrenheit is float, 5 is int, 5.0 is double): _______________________________________
9 correctly computes the conversion when at least one operand is a float or double.
2. (25 points total) Write a program that returns the smallest, largest, and running total (aka rolling total,
aka cumulative sum) array given quarterly transactions #define QTRS 4. This cumulative sum (cusum) at
each index is equal to the sum of all previous indexes plus itself, e.g. cusum of [4,3,2,1] is [4, 7, 9, 10].

a) (5 points) Write a function declaration/prototype for a void function called qtrMinMaxRunningTotal


with input array qtr_trans[QTRS] and outputs min_trans, max_trans, array cusum[QTRS]. Note:
transactions are int. Ensure function cannot modify array qtr_trans, i.e. it is an input parameter.
void qtrMinMaxRunningTotal(const int qtr_trans[QTRS], int *min_trans, int *max_trans, int cusum[QTRS]);

b) (5 points) From calling function main(), write a function call to qtrMinMaxRunningTotal.


#include <stdio.h>
#define QTRS 4
/* Enter function declaration from 2a) here when check your answers with code! */
int main() {
int qtr_trans[] = {100, 78, 222, 125}, min_trans, max_trans;
int cusum[QTRS];
qtr_trans
qtrMinMaxRunningTotal(____________, &min_trans
_____________, &max_trans _____________);
_____________, cusum
printf("min=%d, max=%d, and total=%d\n", min_trans, max_trans, cusum[QTRS - 1]);
return (0);
}

1 OF 4
Student Name: ________________________________ Student ID: _______________________

c) (10 points) Write the function definition for void function qtrMinMaxRunningTotal. Try to answer
first without a compiler but then please check your answers by running the code!
const int qtr_trans[QTRS]
void qtrMinMaxRunningTotal(________________________, int *min_trans
_____________________,
int *max_trans int cusum[QTRS]
________________________, _____________________) {

cusum[0] = qtr_trans[0]; cusum for cumulative sum and cusum[0] equals Q1


min_trans = qtr_trans[0]; max_trans = qtr_trans[0]; init min max to Q1

for (int qtr = 1; qtr < QTRS; qtr++) {


qtr
cusum[__________] qtr-1
= cusum[__________] qtr
+ qtr_trans[__________];

if (qtr_trans[qtr] < min_trans) {


*min_trans
____________ qtr_trans[qtr]
= ______________; update output param min_trans
} else if (qtr_trans[qtr] > max_trans) {
*max_trans = ______________;
____________ qtr_trans[qtr] update output param max_trans
}
} end of for loop
} end of function qtrMinMaxRunningTotal

d) (5 points) What will be the print output from main of the program in 2b on the Mason platform?
min=78, max=222, and total=525

3. (20 points total) The scope of a name is the region in a program where a particular meaning of a name
is visible or can be referenced. If an identifier is referenced outside of its scope, an undeclared symbol
syntax error will result. Scope of constant macros (e.g. #define I _ 80) begin at their definition and
continue to the end of the source file. A function name is visible from its declaration/prototype to the
end of the source file except within functions that have local variables of the same name (bad practice).

a) (10 points) What will be the print output values of the program on Mason platform? Test run code!
#include <stdio.h>
void pass yValue(int copy);
int main() {
int x = 2025;
pass yValue(x);
2025
printf("After pass yValue: x = %d\n", x); // Ans: _______________________________
if (x == 202 );
printf("Will this print? if();?\n"); // Answer (Y or N): ______ Y
return 0; f yes, why? otice ; after if();
} Hint: search empty statement in
void pass yValue(int x) { This only modifies the local x
Explain: ___________________________
x = 202 ; inside the function, not the x in
____________________________________
} ____________________________________
main.
b) (5 points) Does the code above in question 3a) compile on Mason platform?
No
Answer (Yes or No): _________. If not, what are the errors? ___________________________________
Does not compile due to incorrect function naming (pass yValue vs. pass_yValue),
an unnecessary semicolon after if (x == 202);, and typos in the return statement.
2 OF 4
Student Name: ________________________________ Student ID: _______________________

c) (5 points) The part of a program where an identifier can be referenced is called the ________ of the
identifier.

O driver
O scope
O stub
4. (15 points total) elow is example code reading strings line by line from a file and storing them in a
string array, which is a 2D array because each string is a char array. Please answer the following
questions to a) assign each line read from file to an element in the string array and b) use strcmp to
search for a target word. Week 4 class video may help. Question 4c has programming mistakes that may
lead to segmentation fault run time errors or unexpected results.

int log_no = 0;
char firewall_logs[ O _ ][ _ ], line[ _ ], status;
inp = fopen( AM , "r");

for (status = fgets(line, _ , inp);


status != 0;
status = fgets(line, _ , inp)
)
{
/* Question 4a} how can we assign line to firewall_logs[log_no++]? */
}

fclose(inp);

a) (5 points) How can we assign string line to variable firewall_logs[log_no++]? (5 points)

O i) strcpy(firewall_logs[log_no++], line);
O ii) firewall_logs[log_no++] = line;
O ither i) or ii) work
b) (5 points) If strings char target_word[STR_SIZE] and char log_token[STR_SIZE] are
equal, what value does strcmp(target_word, log_token) return? (5 points)

O i) 1
O ii) 0
O iii) 1
c) (5 points) Which of the following may cause a Segmentation fault (core dumped) run-time error?

O i) prin (“ s”, firewall_logs[0][5]) (i.e. passing char non pointer for s to prin )
O ii) firewall_logs[log_no++] //where log_no O _ , i.e. read more lines than dimension size
O iii) oth i) and ii) may cause a segmentation fault run time error

3 OF 4
Student Name: ________________________________ Student ID: _______________________

5. (15 points total) Strings in C are char arrays. When declaring a string, we usually use #define STR_SIZ ,
for example, to specify the length of the char array (aka string). Therefore, while indexing the char array,
we must be careful to stay within the bounds or we may receive a run time error or incorrect results.

a) (10 points) What will be the print output values of the program on Mason platform? Please write
“Invalid” if the printf statement may result in a run-time error or would print incorrect results.

float x[8] = {2. , -1.0, . , -4.7, 2.0, 10.0, 0.1, -54.5};


int i = 5;
printf("%p\n", x); // 5a) Answer: 0x7ffeefbff4c0
__________________
printf("%p\n", &x[0]); // 5a) Answer: 0x7ffeefbff4c0
__________________
printf("%.1f\n", x[i] - 2); // 5a) Answer: 8.0
__________________
printf("%.1f\n", x[2 i]); // 5a) Answer: Undefined or garbage value
__________________
printf("%.1f\n", x[(int)x[0]]); // 5a) Answer: 3.9
__________________

b) (5 points) What include statement is missing based on the syntax compilation error below causing a
string.h
“warning: implicit declaration of function ‘strlen…” when compiling?. Answer: #include <__________>

. (10 points). A structure (aka struct) in C is a self defined data type that includes multiple components.
We will cover C structures more in weeks and 7. What will be the print output values of the program
on Mason pla orm [Link]?
#include <stdio.h>
#include <stdlib.h>
#define STR_S Z 80 max number of characters for our string
typedef struct {
char name[STR_S Z ];
double price; in USD
} product_t;

int main() {
product_t calculator = {"T -84+", 14 . };
printf(" ame: % s\n", [Link]); T-84+
// 6) Ans: Name: __________________
$14.99
printf(" rice: $%.2lf\n", [Link]); // 6) Ans: Price: _________________
return ( X T_SU SS);
}

4 OF 4

Common questions

Powered by AI

The 'void' data type in C function definitions indicates that the function does not return any value. For the 'qtrMinMaxRunningTotal' function, using 'void' is appropriate because its purpose is to modify existing variables via pointers (for example, updating 'min_trans', 'max_trans', and the 'cusum' array) rather than compute and return a new value to the caller. This design leverages direct data modification instead of returning results, which can be beneficial for managing multiple outputs and keeping the function usage intact within larger programs where related data needs simultaneous updating .

'typedef struct' in C is used to define complex data types that aggregate variables of different types under a single identifier, allowing structured data handling. Arrays, on the other hand, are homogeneous data structures used primarily for sequential storage of elements of the same type. Within the document's context, 'typedef struct' is used to define a product type combining a character array for a name and a double for price, providing a compact representation of an entity like a calculator. Arrays are employed to store sequential data, for instance, transaction values or strings, facilitating loop-based manipulations and iterations over consistent data types. Each serves distinct, complementary roles, enabling effective data organization and manipulation .

Using array indices within expressions in 'printf' statements can significantly affect output based on how indices and the data they access are evaluated. In the provided example, 'printf("%.1f\n", x[i] - 2);' directly accesses and operates on the sixth element of the array, modifying its value for the output. However, 'printf("%.1f\n", x[2 * i]);' attempts to access a position beyond allocated array bounds, potentially yielding undefined or garbage values. Furthermore, expressions such as 'x[(int)x[0]]' use floating-point to integer conversion, which might inadvertently access unintended data leading to logical errors or unpredictable results. Proper understanding of these implications is crucial to ensure consistent and accurate output in C programs .

The difference between the expressions '(fahrenheit - 32) * 5 / 9' and '5 / 9 * (fahrenheit - 32)' lies in type conversion and the order of operations. In C, '5 / 9' performs integer division resulting in zero, because both 5 and 9 are integers. This makes the entire expression '5 / 9 * (fahrenheit - 32)' yield zero regardless of the 'fahrenheit' value. In contrast, '(fahrenheit - 32) * 5 / 9' computes the subtraction first, preserving precision if 'fahrenheit' is a float or double, before multiplying by 5, and then divides by 9, ensuring a correct conversion is achieved, as the expression contains a float or double value. This is significant because it results in correct temperature conversion when using a float or double for 'fahrenheit' .

Segmentation faults often occur when a program attempts to access memory that it's not allowed to. In C, improper indexing or operations such as writing beyond the allocated bounds of a string array can lead to such errors. For example, if 'firewall_logs[log_no++]' were used beyond its defined size, this would cause an access violation because it tries to write data outside the allocated memory space, leading to a segmentation fault. Similarly, using an incorrect format specifier, such as 'prin(_____, firewall_logs[0][5])', without properly treating the terminating null character or considering the 2D array dimensions, may result in trying to access nonexistent memory, again causing a segmentation fault .

In C, function prototypes can enforce non-modification of input arrays by using the 'const' qualifier in the parameter declaration. For example, 'void qtrMinMaxRunningTotal(const int qtr_trans[QTRS], ...)' specifies that the input array 'qtr_trans' cannot be altered within the function. This protection is beneficial as it ensures the original data passed to the function remains intact, enhancing program stability and preventing unexpected side effects. By enforcing immutability of the input data, it supports safer and more predictable code execution .

The 'stdio.h' library in C provides necessary functions for input and output operations including handling string data. For example, functions such as 'fgets' read strings from a file into an array, while 'strcpy', typically declared in 'string.h', is used for assigning strings between arrays like 'firewall_logs[log_no++]'. It is crucial for correctly assigning and manipulating string data, ensuring valid operations are performed and preventing run-time errors, especially when dealing with string length or buffer limitations. Proper inclusion of these libraries is essential for managing strings effectively, as reflected in the document's explanation of assigning values and comparing strings using 'strcmp', a function requiring inclusion of 'string.h' to eliminate implicit declaration warnings .

Scope determines where an identifier such as a variable or function is valid within a program. Improper scope management can lead to compile-time errors because identifiers may be accessed outside of their permissible regions. For example, if an identifier is used outside its defined scope, such as referencing a function within another function where a local variable of the same name exists, it results in an undeclared symbol error. In the document, misuse of scope is illustrated where the function 'pass yValue(int x)' might mistakenly alter the global scope expectation by locally overriding 'x' without affecting 'x' in 'main', highlighting the importance of understanding and managing scope to avoid logical errors and maintain code stability .

Implicit type conversions in C can lead to unexpected behavior due to the conversion rules that are applied automatically by the compiler based on operator types. In the document, problems arise when integer division occurs implicitly, such as '5 / 9', resulting in zero, because the operands are integer types. This division result can adversely affect expressions, leading to inaccurate computations such as in temperature conversion. Understanding how automatic conversion affects operations, particularly in mixed-type arithmetic where floats or doubles are involved, is essential for predicting and ensuring correct behavior in C programs .

Managing cumulative totals while adhering to constraints such as mutability requires careful planning and use of parameters. The 'qtrMinMaxRunningTotal' function showcases this by using 'const' to prevent modification of 'qtr_trans', ensuring the data array remains intact while calculating cumulative totals. Challenges arise in needing to maintain state across function calls without altering inputs. This is overcome by separately tracking cumulative data through 'cusum' and using pointers to min and max for updates, illustrating the importance of thoughtful parameter usage and understanding pointer manipulation, crucial for effectively managing aggregate computations in immutable contexts .

You might also like