2181 Final

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Write the code for function, named cube_volume. The function takes one perimeter, the side of a cube, and Catholics, the volume of a cube. Assume that all values are of type float.

#include <stdio.h> // Function declaration float cube_volume(float side); int main() { float side = 4.0; // Example side length of the cube // Call the cube_volume function and display the result it returns float volume = cube_volume(side); printf("The volume of the cube with side %.2f is: %.2f\n", side, volume); return 0; } // Function definition for cube_volume float cube_volume(float side) { float volume = side * side * side; return volume; }

Provide the code that would be used in main() to use a function named sohere_volume and display the result that it returns. The function takes one parameter of type float, which represents the radius of a sphere.

#include <stdio.h> // Function declaration float sphere_volume(float radius); int main() { float radius = 5.0; // Example radius for the sphere // Call the sohere_volume function and display the result it returns float volume = sphere_volume(radius); printf("The volume of the sphere with radius %.2f is: %.2f\n", radius, volume); return 0; } // Function definition for sphere_volume float sphere_volume(float radius) { const float PI = 3.14159; float volume = (4.0 / 3.0) * PI * radius * radius * radius; return volume; }

Provide the code that would be used in main () to use a function (call it or invoke it) named sphere_volume and display the result that it returns. The function takes one parameter of type float, which represents the side of a cube.

#include <stdio.h> // Function to calculate the volume of a sphere float sphere_volume(float radius) { const float PI = 3.14159; return (4.0 / 3.0) * PI * radius * radius * radius; } int main() { float radius = 5.0; // Replace with your desired value for the radius float volume = sphere_volume(radius); printf("The volume of the sphere with radius %.2f is: %.2f\n", radius, volume); return 0; }

Write the code for a function that calculates the are of a rectangle, as follows: 1. The function uses the standard formula: area = length x width 2. The function accepts two floating point parameters for the length and width values. 3. The function returns the result to the caller.

#include <stdio.h> float calculateRectangleArea(float length, float width) { float area = length * width; return area; } int main() { float length = 5.0; // Replace with your desired length float width = 3.0; // Replace with your desired width float result = calculateRectangleArea(length, width); printf("The area of the rectangle is: %.2f\n", result); return 0; }

Write the code to display the numbers from 4 to 96 in increments of 4. You need to use a for or a while loop

#include <stdio.h> int main() { for (int i = 4; i <= 96; i += 4) { printf("%d ", i); } return 0; }

Write a for loop that displays and adds the contents of an array of size 25, that contains integers. The results of the addition is shown only once

#include <stdio.h> int main() { int array_of_integers[25]; int array_sum = 0; // Populating the array with integers from 1 to 25 for (int i = 0; i < 25; i++) { array_of_integers[i] = i + 1; } // Displaying the contents of the array and calculating the sum printf("Contents of the array:\n"); for (int i = 0; i < 25; i++) { printf("%d\n", array_of_integers[i]); array_sum += array_of_integers[i]; } // Displaying the sum after looping through the array printf("The sum of all elements in the array is: %d\n", array_sum); return 0; }

Given two int variables, num1 and num2, write the code to do the following: Use conditionals to divide the greater number by the smaller number and store the result in an int variable named result. Display the value of result on the console.

#include <stdio.h> int main() { int num1 = 20; // Replace with your values int num2 = 10; // Replace with your values int result; if (num1 > num2) { result = num1 / num2; } else { result = num2 / num1; } printf("Result: %d\n", result); return 0; }

Write the code to reverse the contents of an array. The array contains whole numbers (int). Your code needs to use pointer arithmetic, i.e., you cannot use array indexing. Note: There is no standard C function to do this. You need to write all the code yourself.

#include <stdio.h> void reverseArray(int *arr, int size) { int *start = arr; int *end = arr + size - 1; while (start < end) { // Swap values using pointer arithmetic int temp = *start; *start = *end; *end = temp; // Move pointers start++; end--; } } int main() { int myArray[] = {1, 2, 3, 4, 5}; int size = sizeof(myArray) / sizeof(myArray[0]); printf("Original Array: "); for (int i = 0; i < size; i++) { printf("%d ", myArray[i]); } printf("\n"); reverseArray(myArray, size); printf("Reversed Array: "); for (int i = 0; i < size; i++) { printf("%d ", myArray[i]); } printf("\n"); return 0; }

Write a function named to_lowercase, which does the following: 1. Takes as input a character array. 2. Converts each letter in the array to upper case, using the toupper () function from the C Standard Library. See the prototype below. int tolower(int ch); You may assume that the character array is null terminated and that the array only contains letters. The code must use pointers to access the contents of the array.

#include <stdio.h> #include <ctype.h> void to_lowercase(char *str) { for (; *str != '\0'; str++) { *str = tolower(*str); } } int main() { char myString[] = "Convert This To Lowercase!"; printf("Original string: %s\n", myString); to_lowercase(myString); printf("Converted to lowercase: %s\n", myString); return 0; }

Given the following function prototype; int *allocate_array(int size, int default_value); Provide the code to implement the allocate _array function. The function needs to do the following: 1. Use dynamic memory allocation to create an array of int values, using the parameter size to determine the total elements that the array will hold. 2. Check for errors and return NULL if the memory for the array could not be allocated. 3. Set every element of the array to the value given in default_value and return a pointer to the newly created array.

#include <stdio.h> #include <stdlib.h> int *allocate_array(int size, int default_value) { int *newArray = (int *)malloc(size * sizeof(int)); // Allocate memory for the array if (newArray == NULL) { return NULL; // Return NULL if memory allocation fails } for (int i = 0; i < size; i++) { newArray[i] = default_value; // Set each element to the default_value } return newArray; // Return a pointer to the newly created array } int main() { int size = 5; // Specify the size of the array int default_value = 10; // Specify the default value for the elements int *resultArray = allocate_array(size, default_value); if (resultArray != NULL) { printf("Array created with default value %d:\n", default_value); for (int i = 0; i < size; i++) { printf("%d ", resultArray[i]); // Print the elements of the array } printf("\n"); free(resultArray); // Free the dynamically allocated memory } else { printf("Memory allocation failed.\n"); } return 0; }

Given the following struct declarations: struct coord { int x, y, z; 3; struct cube { struct coord location; int side; struct cube *tool_box; Provide the code to do the following: 1. Use dynamic memory allocation to allocate memory for the tool box struct, i.e., create the tool box instance of a cube. 2. Set the fields in the struct so the box is located at coordinates (320, 100, 20). Assume that you are dealing with 3D space in a video game. 3. Set the size of the cube's sides to 15. 4. Print the coordinates and dimensions of the tool_box to the console.

#include <stdio.h> #include <stdlib.h> struct coord { int x, y, z; }; struct cube { struct coord location; int side; struct cube *tool_box; }; int main() { // Allocate memory for the tool box struct (cube) struct cube *toolBox = (struct cube *)malloc(sizeof(struct cube)); // Check if memory allocation was successful if (toolBox == NULL) { printf("Memory allocation failed.\n"); return -1; } // Set the coordinates and size of the tool box toolBox->location.x = 320; toolBox->location.y = 100; toolBox->location.z = 20; toolBox->side = 15; // Print the coordinates and dimensions of the tool box printf("Tool Box Coordinates:\n"); printf("X: %d, Y: %d, Z: %d\n", toolBox->location.x, toolBox->location.y, toolBox->location.z); printf("Dimensions (Side): %d\n", toolBox->side); // Free the allocated memory for the tool box free(toolBox); return 0; }

Provide the code to create a string with the following format: "Mr. <patient-last-name> is <age> years old." where <patient-last-name> is replaced byfthe contents of a character string and <age> is replaced by the contents of an int variable. • Your code must use functions from the C Standard Library (‹string.h>). • Declare variables as needed to store and process the data.

#include <stdio.h> #include <string.h> int main() { char patientLastName[] = "Smith"; int age = 35; int totalLength = strlen("Mr. ") + strlen(patientLastName) + strlen(" is ") + 3 + strlen(" years old."); char formattedString[totalLength]; sprintf(formattedString, "Mr. %s is %d years old.", patientLastName, age); printf("%s\n", formattedString); return 0; }

Assume that the following function prototype is at the top of a program: void get_extension (const char *file_name, char *extension); Write the code to implement the get_extension function, as follows: 1. The function parses the string given in file_name and finds the file's extension. For example, given "MyPhoto.jpg" the value pointed to by extension will end up being "jpg" 2. The extension value is stored in the string that extension points to. 3. If the file does not have an extension, the function stores an empty string in extension. 4. You may use functions from <string.h > to implement the function.

#include <stdio.h> #include <string.h> void get_extension(const char *file_name, char *extension) { const char *dot = strrchr(file_name, '.'); // Find the last occurrence of '.' if (dot == NULL || dot == file_name) { strcpy(extension, ""); // Empty string for files without an extension } else { strcpy(extension, dot + 1); // Copy the extension into the provided string } } int main() { const char file1[] = "MyPhoto.jpg"; const char file2[] = "Document"; const char file3[] = "Archive.tar.gz"; char extension1[20]; // Sufficient size for the extension char extension2[20]; char extension3[20]; get_extension(file1, extension1); get_extension(file2, extension2); get_extension(file3, extension3); printf("File: %s, Extension: %s\n", file1, extension1); printf("File: %s, Extension: %s\n", file2, extension2); printf("File: %s, Extension: %s\n", file3, extension3); return 0; }

Assume that the variable float total _salary contains the dollar amount of an employee's yearly salary, e.g. $65,500. Write the code to do the following: If the employee's salary is $50,000 or less, assess a 10% income tax. Display the amount of the salary, minus the income tax. If the employee's salary is more than $50,000, assess a 12% income tax. Display the amount of the salary, minus the income tax. The program continues to ask users for salary data, until they type -1.

#include <stdio.h> int main() { float total_salary; while (1) { printf("Enter the employee's yearly salary (or type -1 to exit): "); scanf("%f", &total_salary); if (total_salary == -1) { break; } float tax_rate; if (total_salary <= 50000) { tax_rate = 0.1; } else { tax_rate = 0.12; } float income_tax = total_salary * tax_rate; float net_salary = total_salary - income_tax; printf("Salary: $%.2f\n", total_salary); printf("Income Tax: $%.2f\n", income_tax); printf("Net Salary: $%.2f\n", net_salary); } return 0; }

When using the scarf function, what is the format to read an integer from the console?

%d

When using the scarf function, what is the first specifier to read a floating point number from the console?

%f

What flag prints out all relevant information in the uname command ?

-a

What is the 4-bit output of adding two unsigned binary integers 1100 and 0100

0000

Given two unsigned binary numbers, A and B, of the same length, add them together and write result in binary form A=1001 B= 1010

0011

Convert the decimal number 1234 to a binary number

10000000010

Given two unsigned binary numbers, A and B of the same length, perform a bit wise logical OR operation between them A = 10001001 B= 10010010

10011011

Given an unsigned binary number A of length 8, perform a left shift by 2 places operation and also a logical right shift by 3 places operation. A=10101100

10110000, 0001010

Convert the decimal number -8 to a two complement binary

1111 1000

Convert the decimal number 123 to a binary number and select the right answer

1111011

What is the largest number that can represented with 4 digits in base 2?

15

What is the maximum decimal value that can be represented by 2 hexadecimal digits?

255

Given the following code, what is the output? void f lint a[101 ) printf ("§d\n", a[3]) ; a [3] = a[3] + 900; } " int main (void) int a[10] = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; (void) f(a); (void) f(a); print ("8d)n", a[3]) ; return 0;

3 903 1803

What is the size of addressable memory in 32-bit architectures?

4 gigabytes

What is the standard size of a memory address in modern processors according to the text?

64 bits

Assuming int a = 9; what is the value of a after the expression a—; executes

8

Given the following code fragment, how many elements can be stored in the array scores? [0] [2] [7]

8

Given the following code fragment, how many elements can be stored in the array first_initial? char first_initial[] ={ [0] ='J' , [2] = 'M' , [8] = 'S'}

9

What is the preprocessor directive needed to use the functionality in the C string library ?

<string.h>

What preprocessor directive would be need to use basic input/outputs in a C program?

<studio.h>

What is a computer system?

A combination of hardware and system software

What is the purpose of a register in the van Neumann architecture?

A small+, fast unit of storage used to hold program data and instructions

Which of the following is not an I/O unit?

ALU IS NOT A I/O UNIT. Monitor, Touchscreen, keyboard

(1011)2 represents which hexadecimal value ?

B

What system was developed by Claude Shannon applying Boolean logic?

Binary computing system

What hardware component is usually obscured by a fan in both desktop and laptop systems

CPU

What is referred to as the brain of the computer?

CPU

Suppose that you to add read permission for everyone on a file named readme within the current directory, while keeping other existing permissions intact.

Chmod o+r readme

Suppose that you want to set "read" and "write" permissions only for the owner of a file named I_am_editable within the current directory.

Chmod u=row i_am_editable

What made the connection between Boolean algebra and electrical circuit design in 1937?

Clause Shannon

What does the "read" permission on a Unix file indicate?

Contents of a file can be read

Where is CISC more common today?

Desktop and many server-class computer

What is the difference in power consumption between desktop computers and laptops?

Desktop consume 100-400 W

Quit

Ends the debugger session

What does the execute permission on a Unix file indicate?

Executable file

Next

Executes the current line of a code in the program and pauses

A label used in a program has effects on the actual execution of a program

False

What enabled a computer to take information from its environment?

Input/outputs ports

What unique feature does the raspberry pi single board computer contain?

It contains a system on a chip processor with integrated RAM and CPU

What does the program counter in the control unit do?

Keeps the memory address of the next instruction to execute

What is the main software part of the computer system?

Operating system

Part A (4 points) Show the code to read and store: a single character, a floating point number and an integer. Assume that the user will type these at the console, one after the other, separated by white space and in that order. You need to use scanf() to read the data. Pick any suitable name for the variables needed. Part B (4 points) Show the code to display the values read above. You must show each value in a separate line and set the precision of the floating point number to three (3) disits. You need to use printf() to display the values. Bonus Points (2 points): Show the code to display the floating point number in scientific notation.

Part A scanf(%c %f %d", &character, &floating, &integer); Part B printf(A single character: %c\n", character); printi( A floating number: %.3fIn", floating ); printf(A integer: %dIn", integer); Part C is the floating point number %.2f?

What is the difference between primary and secondary memory?

Primary memory is faster and smaller and is used for program data; secondary memory is larger and slower and stores files

What does the uname command do?

Prints information about the system

What stores the data and instructions of running programs and is typically lost when power is lost?

RAM

What does RAM stand for?

Random Access Memory

What is the role of the central processing unit in a computer system?

Runs instructions and computes data and memory addresses

Break

Sets a breakpoint in a program

List

Shows the source code around pause point or specified point

The stack _____ as a program calls functions and ______ on return from a function

Shrinks, grows

In computing architecture, the memory wall refers to what happens when the processors ______ is faster than the _______ at which data can be transferred to from memeodh

Speed, rate

What does the instruction register do in the control unit of the vin Neumann architecture

Stores the instruction that is currently being executed

What technology is found on the raspberry Pi and commonly in smartphones?

System-on-a-chop (SoC)

Which of the following correctly explains the main role of the gcc compiler

The gcc complied is a software development tool that enabled developers to write code in high level programming languages and translate that code into machine executable binaries

What is assembly as mentioned in the context of computer system?

The human readable form of machine code

What does a variable scope define?

The scope of a variable defines the block of code in which this variable is applicable

What is the processing unit responsibility?

To perform mathematical operations on data, according to the instructions loaded from memory

Shifting Right has two variants logical right shift and arithmetic right shift

True

Heap

Where dynamically allocated memory is stored

Code

Where function instructions are stored

Data

Where global variables are stored

Stack

Where local variables and function parameters are stored

Which ones are the control flow statements

While loop, switch loop, for loop, and if else statement

What is used in CPU design to address the memory

cache

Suppose that you have a text file named strangerthings.txt. Provide a Unix/Linux command to show the contents of the file o the terminal.

cat strangerthings.txt

Suppose that you want to navigate to a directory named myrcella that is within a directory named Cersei, which is housed in a directory named Tywin, which in turn is in the root directory.

cd / tywin/ cersei / myrcella

Write the code to open a file named customer_data.txt for reading. Assume that a file pointer named dataFile has already been declared

dataFile = fopen("customer_data.txt", "r");

Provide to see come to initialize a 1-D array with 10 float elements, with the first, fourth, and six elements initialize to the values of 1.5, 4.5, and 6.5 and the rest uninitialized.

float arr[0] = {[1] =1.5 [4]=4.5 [6]= 6.5}

Write a for loop that displays and adds the contents of an array of size 20, that contains floating point numbers. The result of the addition is shown only once, after the calculation is complete.

float sum = 0.0; for (int i = 0; i < 20; i++) { // Displaying array contents printf("%.2f ", floatArray[i]); // Adding array elements to sum sum += floatArray[i]; } // Displaying the total sum printf("\nTotal sum: %.2f\n", sum); return 0; }

What is the compiler directive needed to enable use of the GNU debugger tool?

gcc -g or g

Write the command a program file named my_application.c into executable file named myapp

gcc -o my_application.c -o my app

Write the code for a function named max, that does the following: • Accepts two parameters: • data, an array of int values. o data size, the size of the array. • Finds the largest number in the array. • Returns a pointer that contains the address of the largest element in the array.

int * maxint datal], int data size) { // Initialize the pointer to the first element int* max_ptr = &data[0]; for (int i : i++) { if (datali] > *max_ptr) {// Update the pointer to the larger element max_ptr = datali]; ] 3 return max_ptr; ]

Write a switch statement whose controlling expression is the variable error _code. The statement prints the corresponding error message, based on the following table: Error Code Message No error. Everything is fine. 1 File not found. 2 Permission denied. 3 Invalid input. All other codes Unknown error code.

int error_code; printf( Message: %d\n"); scanfl%d/n", error_code); switcherror_code){ case 0; printf("No error. Everything is fine."); break; case 1; printf("File is not found."); break; case 2; printf("Permission denied"); break; case 3; printf("Invalid input."); break; default; printf(Unknown error code) break; }

The function shown below is designed to calculate the sum and average of the values stored in the given array. Note that the function does not return a result, so the idea is to use pointers to change the original values of data_average and data sum. Unfortunately, the function is missing pointer operators in key places. Your task is to provide the corrected code. void add_and_average(double al], int n, double data_average, double data_sum) int i; data_sum = 0.0; for (i = 0; i < n; i++) data_sum += a[i]; data_average = data_sum / n; }

int main() { double array[] = {1.5, 2.5, 3.5, 4.5, 5.5}; int size = 5; double average, sum; add_and_average(array, size, &average, &sum); printf("Sum: %.2f\n", sum); printf("Average: %.2f\n", average); return 0; }

Write a function mean search_data that takes an array of interviews, the length of the array an integer name target as arguments. The search_data function searches do their array and returns the first index where target appears in there, array, if it does. If target is not an array, the function returns an invalid index value to indicate an error condition for example -1

int search_data(int interviews[], int length, int target) { for (int i = 0; i < length; i++) { if (interviews[i] == target) { return i; // Return index if target is found } } return -1; // Return -1 if target is not found }

Suppose that you want to see a detailed listing of all .pdf files stored in the current directory. Provide the Unix/Linux command to achieve this.

ls -l *.pdf

Suppose that you want to create a sub directory named child in the current directory .

mkdir child

Using the printf function, what would be the code to display the contents of three distinct variables, on the same line, separated by commas. Assume the following variable names and types: student type char, age type int and balance type float

printf("%c, %d, %.2f", student, age, balance);

Assuming that a struct has been defined as follows: struct box { int itemnum; char color [20]; int height; int width; int depth; float x; float y; float z; }; Write a printf statement that shows the values stored in the struct. The output needs to be formatted as shown in the following example: Item: 3, Color: red, Position: (1, 2, 3) Height: 3, Width: 2, Depth: 5

printf("Item: %d Color: %c\n", box.itemnum, box.color); printf '*Position: (%.2f, %.2f, %.2f) ", box.x, box.y,box.z); printf("Height: %d Width: %d Depth: %d", box.height, box.width, box.depth);

f = g - j * 17; hint: 17 = 16 +1

slli t3, t2, 4 add t3, t3, t2 add t0, t1, t3

f = g * 5 - j * 32;

slli t3, t2, 5 slli t4, t2, 2 add t4, t4, t2 add t4, t2, 4 add t4, t2, 4 add t4, t4, t2 sub t0, t2, t4

What is the preprocessor directive needed to use the C library that contains functions to allocate memory dynamically?

stdlib.h

Write a function that meets the following specifications: 1. The function prototype is: struct timestamp split_timestamp (long total _secs) ; 2. total secs represents the total number of seconds in the current day, i.e., the time since midnight. 3. The function calculates the total hours (0-23), minutes (0-59) and seconds (0-59) represented by total_secs and returns this data in a timestamp struct. Assume that this struct has already been defined, with fields named total hours, minutes and seconds.

struct timestamp split_timestamp(long total_secs) { struct timestamp result; result.total_hours = total_secs / 3600; result.minutes = (total_secs % 3600) / 60; result.seconds = total_secs % 60; return result; }

What C library is needed to use the printf function?

studio.h

Assuming that the following structs and function prototype have been defined: struct position { int x; int y; int z; }; struct box { int itemnum; char color [25]; struct position p; int height; int width; int depth; }; void move_box(struct box * the_box); Write the code (single line of code) to set the box's x coordinate to 0. Assume that this code is in the implementation of the move box function. Do NOT type any unnecessary spaces

the_box->x = 0;

Which of the following loops is good choice in C programming when the number of iterations is not known in advance?

while loop


Set pelajaran terkait

ITIL4 Foundation - Which of the following value chain activities will contribute

View Set

module 7 and most lab 4 objectives

View Set

Anatomy and Physiology Chapters 1, 5, & 6 (EXAM 1)

View Set

chapter 11 finance study guide questions

View Set

16-6: How Do Astronomers Measure Distance?

View Set

Ch13 (Extension) Reporting Systems and OLAP

View Set