Computer Programming Question and Answers
( Suggestion : keep refreshing the page for updated content & Search Questions Using Find )
Q1) A. C program to print the following pattern?
1
23
456
789 10
11 12 13 14 15
Answer :
#include <stdio.h> int main() { int rows = 5; // Number of rows in the pattern int num = 1; // Initialize the starting number for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { printf("%d ", num); num++; } printf("\n"); } return 0; }
Q1) B. Hare and Rama are top students in computer programming. As part of this, Hare saw a White Benz with the licence plate 5678 and instantly asked Rama if he could use the concept of recursion to find the sum of those digits. Rama started tackling it. Dear students, your current goal is to create a code that complies with Hare requirements.
Answer :
#include <stdio.h> int sumOfDigits(int num) { // Base case: if the number is a single digit, return it if (num < 10) { return num; } else { // Recursive case: sum the last digit and call the function with the remaining digits return num % 10 + sumOfDigits(num / 10); } } int main() { int input; printf("Input: "); scanf("%d", &input); int result = sumOfDigits(input); printf("Output: %d\n", result); return 0; }
Q2) (a) Consider a scenario where a company gives its employees a yearly bonus based on their performance rating. The bonus is calculated as follows: if the rating is Excellent, the employee receives 20% of their salary, if the rating is ‘Good’, they receive 15% of their salary, for Satisfactory’, it’s 10%; and for Needs Improvement’, no bonus is given. Write a C program that takes an employee’s performance rating and salary as input and calculates the bonus amount. Explain your code’s logic and analyze its efficiency.
Answer :
calculates the bonus amount based on the employee’s performance rating and salary:
#include <stdio.h> int main() { char rating; double salary, bonus; // Input the performance rating and salary printf("Enter the employee's performance rating (E for Excellent, G for Good, S for Satisfactory, N for Needs Improvement): "); scanf(" %c", &rating); printf("Enter the employee's salary: "); scanf("%lf", &salary); // Calculate the bonus based on the rating switch (rating) { case 'E': bonus = 0.20 * salary; break; case 'G': bonus = 0.15 * salary; break; case 'S': bonus = 0.10 * salary; break; case 'N': bonus = 0.00; // No bonus for Needs Improvement break; default: printf("Invalid rating!\n"); return 1; // Exit with an error code } // Output the calculated bonus printf("The bonus amount is: $%.2lf\n", bonus); return 0; }
Explanation of the code logic:
- The program first declares variables for the employee’s performance rating, salary, and bonus.
- It prompts the user to input the performance rating and salary using
printf
andscanf
. - It then uses a
switch
statement to calculate the bonus based on the entered rating. Depending on the rating, it applies the corresponding bonus percentage to the salary. If the rating is ‘Needs Improvement’, the bonus is set to 0. - If an invalid rating is entered, the program prints an error message and exits with a non-zero error code.
- Finally, it outputs the calculated bonus amount.
Efficiency analysis:
- This code has a simple and straightforward logic, making it easy to understand and maintain.
- It uses a
switch
statement, which is efficient and suitable for this scenario since there are a limited number of rating options. - The program performs a fixed number of operations regardless of the salary value or rating, so its time complexity is constant, O(1).
- Memory usage is also minimal, as it only stores a few variables, making it efficient in terms of memory.
Overall, this code is efficient and effective for calculating bonuses based on performance ratings and salaries.
Q3) A. You are given a non-empty sequence of non-negative integers terminated by a-1. The -1 is not part of the input sequence. The sequence has length at most 100, including the -1. There will be at least one non-negative number. You have to output the sequence of running averages, where: The first average is the first input number. The second output is the average of the first two input numbers. The third output is the average of the first three input numbers, and so on. Output Format: You should output exactly 2 digits after the decimal place. Different numbers in the output should be separated by spaces. At the end, you should print a newline. Note: Kindly do not use arrays in the code. Using C language. Private Test cases used for evaluation Input Expected Output Test Case 1 0000-1 0.00 0.00 0.00 0.00 n Test Case 2 4620-1 4.00 5.00 4.00 3.00 m Test Case 3 420-1 4.00 3.00 2.00 n Test Case 4 2222222-1 2.00 2.00 2.00 2.00 2.00 2.00 2.00 a
Answer :
a C program that reads the input sequence of non-negative integers and calculates the running averages as described:
#include <stdio.h> int main() { int num; int total = 0; int count = 0; while (1) { scanf("%d", &num); if (num == -1) break; total += num; count++; float average = (float)total / count; printf("%.2f ", average); } printf("n\n"); return 0; }
You can use this C program by providing the input sequence as described in the test cases, and it will calculate the running averages and produce the expected output format.
Q3) B. You are given a sequence of non-negative integers terminated by -1. You have to output 1 if there are atleast 2 distinct elements in the sequence and 0 if the sequence consists of only 1 integer. Note that -1 is not part of the sequence. The sequence is not necessarily sorted. Note: Don’t use arrays to this question.
Answer :
a Python code snippet to accomplish this without using arrays:
# Initialize variables to store the two distinct elements distinct1 = None distinct2 = None # Read input sequence until -1 is encountered while True: num = int(input()) # Check if -1 is encountered if num == -1: break # Check if this is the first distinct element if distinct1 is None: distinct1 = num # Check if this is the second distinct element elif distinct2 is None and num != distinct1: distinct2 = num # If we have more than 2 distinct elements, exit early elif num != distinct1 and num != distinct2: print(1) break # Check if there were two distinct elements or not if distinct1 is not None and distinct2 is not None: print(1) else: print(0)
This code reads the input sequence and tracks the two distinct elements. If it encounters a third distinct element, it exits early and prints 1. Otherwise, if only one or no distinct elements are found, it prints 0.
Q4) Fill the following table (To denote the number bytes occupied by each data types): Datatype No. of bytes of memory occupied 15 marks 16-Bit 32-bit 64-bit Compiler int Compiler Compiler float char unsigned int unsigned char short int long int double long double long long
Answer :
Here’s a table indicating the typical number of bytes occupied by each data type on a system with 8-bit bytes:
Data Type | 16-Bit | 32-Bit | 64-Bit |
---|---|---|---|
int | 2 | 4 | 8 |
float | 4 | 4 | 8 |
char | 1 | 1 | 1 |
unsigned int | 2 | 4 | 8 |
unsigned char | 1 | 1 | 1 |
short int | 2 | 4 | 8 |
long int | 4 | 4 | 8 |
double | 8 | 8 | 8 |
long double | 10 | 16 | 16 |
long long | 8 | 8 | 8 |
Please note that the exact memory usage may vary depending on the compiler and platform, but these are the typical sizes for each data type on most systems.
Q5) Find the value of the expl, exp2 and exp 3 int operand1=0X42; int operand2-=0X32; expl – operand1 & operand2 exp2 – operand1<<2 exp3 operand2>>3
Answer :
It looks like you’re trying to perform some calculations in C or a similar programming language. However, there are a few issues in your code. Let me correct them and provide the values of expl
, exp2
, and exp3
:
int operand1 = 0x42; // Operand1 is assigned the hexadecimal value 0x42, which is 66 in decimal.
int operand2 = 0x32; // Operand2 should be assigned the hexadecimal value 0x32, which is 50 in decimal.
int expl = operand1 & operand2; // Calculate the bitwise AND of operand1 and operand2.
int exp2 = operand1 << 2; // Left-shift operand1 by 2 bits.
int exp3 = operand2 >> 3; // Right-shift operand2 by 3 bits.
Now, let’s calculate the values:
expl
is the result ofoperand1 & operand2
, which is 0x22 in hexadecimal or 34 in decimal.exp2
is the result ofoperand1 << 2
, which is 0x108 in hexadecimal or 264 in decimal.exp3
is the result ofoperand2 >> 3
, which is 0x6 in hexadecimal or 6 in decimal.
B) Convert the following 67(10) – (2) 10000010(2)- (10) 367(8)- (2) F56(16)- (2)
Answer :
Let’s convert the given numbers between different number bases:
- 67 (decimal) to binary:
- 67 in decimal is 1000011 in binary.
- 10000010 (binary) to decimal:
- 10000010 in binary is 130 in decimal.
- 367 (octal) to binary:
- 367 in octal is 11111111 in binary.
- F56 (hexadecimal) to binary:
- F56 in hexadecimal is 111101010110 in binary.
Q6) What are the different data types available in C. Explain them.
Answer :
In C programming, there are several data types available, each with its own characteristics. Here are some of the main data types in C:
- int: This data type is used to store integer values. It typically uses 4 bytes of memory on most modern systems.
- float: Float is used to store floating-point or real numbers. It’s useful for representing numbers with decimal points. It typically uses 4 bytes of memory.
- double: Double is used for double-precision floating-point numbers. It can store larger and more precise floating-point values compared to float. It typically uses 8 bytes of memory.
- char: Char is used to store a single character. It typically uses 1 byte of memory.
- _Bool: This data type is used to store Boolean values, which can be either true (1) or false (0). It typically uses 1 byte of memory.
- short: Short is used to store integers, but it typically uses 2 bytes of memory, making it more memory-efficient than int for smaller integer values.
- long: Long is used for storing larger integer values. It typically uses 4 bytes on 32-bit systems and 8 bytes on 64-bit systems.
- long long: This is used for even larger integer values. It typically uses 8 bytes of memory.
- unsigned: This keyword can be applied to integer data types (e.g., unsigned int) to represent only positive values, effectively doubling the positive range of the variable.
- void: Void is a special data type used to indicate that a function does not return any value. It’s also used for pointers to data of unknown type.
These are the basic data types in C, and they serve as building blocks for creating more complex data structures and user-defined data types. Additionally, C allows for type modifiers like signed and unsigned, which affect the range and representation of some data types.
Q6) B. Analyze the following C code that’s intended to find the sum of even numbers from 1 to 50. Identify any errors, suggest improvements on the number of iterations, and explain why your improvements are better. #include <stdio.h> int main( { int sum = 0, i; for (i=1; i <= 50; i++) if (1% 2 =0) sum += i; printf(“Sum of even numbers from 1 to 50: %d”, sum); return 0;
Answer :
There are several issues in the provided C code. Let’s analyze it step by step and suggest improvements:
#include <stdio.h> int main( { int sum = 0, i; for (i=1; i <= 50; i++) if (1% 2 =0) sum += i; printf("Sum of even numbers from 1 to 50: %d", sum); return 0;
Here are the identified issues and suggested improvements:
- Syntax Errors: There is a syntax error in the
main
function declaration. It should beint main()
with empty parentheses. - Incorrect Condition: The condition inside the
for
loop and theif
statement is incorrect.1% 2 =0
should bei % 2 == 0
to check ifi
is an even number. - Initial Value: The code starts the loop from
i=1
. This means it’s checking even numbers starting from 1. To find the sum of even numbers from 1 to 50, it should start fromi=2
. - Inefficient Loop: The loop iterates through all numbers from 1 to 50, but since you’re looking for even numbers, you can improve efficiency by iterating from 2 to 50 with a step of 2. This way, you only check even numbers.
- Printing Sum: It’s a good practice to include a newline character ‘\n’ at the end of the
printf
statement to format the output nicely.
Here’s an improved version of the code:
#include <stdio.h> int main() { int sum = 0, i; for (i = 2; i <= 50; i += 2) { sum += i; } printf("Sum of even numbers from 1 to 50: %d\n", sum); return 0; }
In this improved version, we start the loop from 2, increment i
by 2 in each iteration (checking only even numbers), and format the output with a newline character for better readability. This reduces the number of iterations and makes the code more efficient.
For More Updates Join Our Channels :