CS201 – Introduction to Programming: Midterm Important Subjective (36 Solved Q&As)
Computer Science • Read every solved subjective question with its model answer directly on this page. Free, no login required.
All 664 Midterm Packs · CS201 Course Page · CS201 MCQ Pack (436 MCQs)
-
To which category of software do "Compiler and Interpreter" belong?
Topic: Programming Basics, Design & Development Tools • 1 mark marks
System software. Compilers and interpreters are system software, because they are programs that help in developing and running other programs.
-
What is compiler?
Topic: Programming Basics, Design & Development Tools • 3 marks marks
A compiler is a program (system software) that translates a program written in a high-level language into machine language. It translates the whole source program at once and produces an object/executable file; the list of errors, if any, is displayed after scanning the complete program. Once compiled, the executable file can be run any number of times without translating again.
-
Why do we include iostream.h in our programs?
Topic: Programming Basics, Design & Development Tools • 1 mark marks
Because the standard stream handling functions are stored in this file. Before using these functions in our program, it is necessary to tell the compiler about the location of these functions.
-
Which programming tool is helpful in tracing the logical errors?
Topic: Programming Basics, Design & Development Tools • 1 mark marks
Debugger. A debugger is used to debug the program; it helps in tracing logical (run-time) errors by executing the program step by step and examining the values of variables.
-
How is learning to design programs like learning to play soccer?
Topic: Programming Basics, Design & Development Tools • 3 marks marks
"Learning to design programs is like learning to play soccer. A player must learn to trap a ball, to dribble with a ball, to pass, and to shoot a ball. Once the player knows those basic skills, the next goals are to learn to play a position, to play certain strategies, to choose among feasible strategies, and, on occasion, to create variations of a strategy because none fits." In the same way, a programmer first learns the basic building blocks (variables, loops, functions) and then learns to combine them into designs for solving complete problems.
-
What is the output of the following program? #include iostream.h main ( ) { int RollNo; int rollno; RollNo = 5; rollno = 8; cout << "Roll No is " << rollno; }
Topic: Expressions, Output Prediction & Error Finding • 1 mark marks
The program should not compile, because of the missing <> in the following statement: #include iostream.h If we ignore this error, then the output should be: Roll No is 8 (C++ is case-sensitive, so RollNo and rollno are two different variables; rollno has the value 8.)
-
Find out the error in the code given below: if ( num % 2 = 0 ) cout << "The number is even" << endl;
Topic: Expressions, Output Prediction & Error Finding • 2 marks marks
In if ( num % 2 = 0 ) there should be an extra = sign; the correct statement is: if ( num % 2 == 0 ) A single = is the assignment operator, which assigns 0 to num % 2 (an error); == is the comparison operator used to test a condition.
-
What is the result of the expression x = 2 + 3 * 4 - 4 / 2 ?
Topic: Expressions, Output Prediction & Error Finding • 1 mark marks
12 (Multiplication and division are performed before addition and subtraction: 3 * 4 = 12 and 4 / 2 = 2, so x = 2 + 12 - 2 = 12.)
-
Suppose 'z' is a variable of type int. What will be the result of x = 27/4 ?
Topic: Expressions, Output Prediction & Error Finding • 1 mark marks
6. Both operands are integers, so integer division is performed and the fractional part is discarded (truncated): 27 / 4 = 6.75, which becomes 6.
-
What is the difference between switch statement and if statement?
Topic: Decision Making & Loops • 2 marks marks
The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.
-
What is the difference between while and for loop?
Topic: Decision Making & Loops • 5 marks marks
The for loop is used when the number of repetitions is known in advance; its initialization, condition and increment/decrement are all written in one line, e.g. for (int i = 0; i < 10; i++). The while loop is used when the number of repetitions is not known in advance and the loop continues as long as the given condition remains true; initialization is done before the loop and the increment/decrement is written inside the body. Both are entry-controlled (pre-test) loops, i.e. the condition is checked before entering the body, so the body may not execute even once if the condition is false initially.
-
Write a declaration statement for an array of 10 elements of type float. Include an initialization statement of the first four elements to 1.0, 2.0, 3.0 and 4.0.
Topic: Arrays & Two-Dimensional Arrays • 2 marks marks
float tmp [10] = {1.0, 2.0, 3.0, 4.0}; (The remaining six elements are automatically initialized to 0.0.)
-
Write down the output of the following code: int array[7], sum = 0; for(int i=0;i<7;i++) { array[i] = i; sum += array[i]; } cout<< " Sum = " <<sum;
Topic: Arrays & Two-Dimensional Arrays • 3 marks marks
Sum = 21 (The loop stores 0, 1, 2, 3, 4, 5, 6 in the array and adds them: 0+1+2+3+4+5+6 = 21.)
-
What will be the output of the following segment of C++ code? int A[5] = {1 , 2, 3, 4}; int i; for (i=0; i<5; i++) { A[i] = 2*A[i]; cout << A[i] << " "; } (Marks: Marks not stated in the source)
Topic: Arrays & Two-Dimensional Arrays
2 4 6 8 0 (Only four values are given in the initialization list, so the fifth element A[4] is 0. Each element is doubled before printing: 2, 4, 6, 8, 0.)
-
If int array[10]; is an integer array then write the statements which will store values at Fifth and Ninth location of this array.
Topic: Arrays & Two-Dimensional Arrays • 5 marks marks
array[4] = 200; array[8] = 300; (Array subscripts start from 0, so the fifth location is index 4 and the ninth location is index 8. Any values can be stored; the source solution uses 200 and 300.)
-
A two-dimensional array has 3 rows and 4 columns. Write down the syntax to initialize first element of all three rows of two-dimensional array with value 2.
Topic: Arrays & Two-Dimensional Arrays • 2 marks marks
int arr[3][4] = {{2}, {2}, {2}}; Or, by assignment statements: arr[0][0] = 2; arr[1][0] = 2; arr[2][0] = 2; (The first element of every row is at column index 0; in the initialization-list form the remaining elements of each row become 0.)
-
Using the given array declaration: int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int* arr_ptr = arr; Find out the value of each of the expressions below. 1. *(arr_ptr + 4) 2. (*arr_ptr)++ 3. *(arr_ptr++)
Topic: Pointers • 3 marks marks
arr_ptr points to arr[0], i.e. to the value 1. Evaluating the expressions in order: 1. *(arr_ptr + 4) = 5 - the value of the 5th element, arr[4]; the pointer itself does not move. 2. (*arr_ptr)++ = 1 - the current value at arr[0] is used first (1), and afterwards the value of arr[0] is incremented to 2. The pointer does not move. 3. *(arr_ptr++) = 2 - the value currently pointed to is used (arr[0], which has become 2 after expression 2), and afterwards arr_ptr moves to the next element arr[1].
-
Following are two programming statements; you have to write down the functionality of each statement. 1) int *const intPtr = &x ; 2) const int *intPtr = &x ;
Topic: Pointers • 5 marks marks
1) intPtr is a constant pointer to an integer. The pointer itself is constant, so it must be initialized at declaration and can never be made to point to another variable; however, the value stored at the address can still be changed through this pointer (*intPtr = 10; is allowed). 2) intPtr is a pointer to a constant integer. The value being pointed to cannot be changed through this pointer (*intPtr = 10; is an error), but the pointer itself is not constant, so it can be made to point to some other variable.
-
Identify the errors in the following code segment and give the reason of errors. main(){ int x = 10 const int *ptr = &x ; *ptr = 5 ; }
Topic: Pointers • 3 marks marks
Error: *ptr = 5; Reason: ptr is declared as a pointer to a constant integer (const int *ptr). You cannot use this pointer to change the value being pointed to, so assigning *ptr = 5 is not allowed. (Note: as printed in the paper, the statement int x = 10 is also missing its terminating semicolon.)
-
Give the general syntax of definition of structure.
Topic: Structures • 1 mark marks
struct structure_name { data_type member1; data_type member2; ... }; The keyword struct is used, followed by the structure name and its data members enclosed in braces; the definition ends with a semicolon.
-
Consider the structure struct Customer { int custnum; int salary; float commission; }; A programmer wants to assign 2000 for the structure member salary in the above example of structure Customer with structure variable cust1. What line of code should he write?
Topic: Structures • 2 marks marks
cust1.salary = 2000; (The member is accessed through the structure variable cust1 using the dot operator.)
-
Write a recursive function that takes three arguments (an integer array, starting subscript 's' and ending subscript 'e'). In first recursive call, the function should display the array from subscript 's' (s = 0) to 'e' (e = size of array). In each successive call, the function should print the array from index s+1 to e. The function should stop processing and return when starting subscript becomes equal to ending subscript. For example, if user enters values for array 2, 3, 4, 5, 6 then the recursive function must display the following output: 23456 3456 456 56 6
Topic: Functions & Recursion • 10 marks marks
#include <iostream.h> void PrintArray(int arrayInput[], int &s, int &e); main ( ) { int pause; int TestArray [6] = {1,2,3,4,5,6}; int StartPoint = 0; int EndPoint = 5; PrintArray(TestArray , StartPoint, EndPoint); cout<<"\n"; PrintArray(TestArray , StartPoint, EndPoint); cout<<"\n"; PrintArray(TestArray , StartPoint, EndPoint); cout<<"\n"; PrintArray(TestArray , StartPoint, EndPoint); cout<<"\n"; PrintArray(TestArray , StartPoint, EndPoint); cout<<"\n"; PrintArray(TestArray , StartPoint, EndPoint); cin >> pause; } void PrintArray(int arrayInput[], int& s, int& e) { for (int i = s; i<= e; i++) { cout<< arrayInput[i]; } s=s+1; } (s is passed by reference, so every call starts printing one element later than the previous call, producing the successive lines 123456, 23456, 3456, 456, 56, 6 for the test array.)
-
Write a function BatsmanAvg which calculate the average of a player (Batsman). Call this function in main program (Function). Take the input of Total Runs made and Total number of matches played from the user in main function.
Topic: Functions & Recursion • 10 marks marks
#include <iostream.h> int BatsmanAvg(int TotalRuns, int TotalMatches) ; main() { int stopit; int TotalRuns, TotalMatchesPlayed =0; cout << "Please Enter the total Runs made : " ; cin>> TotalRuns ; cout << "Please Enter the total match played : " ; cin>> TotalMatchesPlayed ; cout << "\n Avg Runs = " << BatsmanAvg(TotalRuns,TotalMatchesPlayed); cin>> stopit; } int BatsmanAvg(int TotalRuns, int TotalMatches) { return TotalRuns/TotalMatches; }
-
Write a void function( ); that takes integer numbers from the user and then displays the sum of odd and even numbers entered by the user. Your program should terminate if user enters a negative number.
Topic: Functions & Recursion • 10 marks marks
#include <iostream.h> void SumOddEven(void); main() { SumOddEven(); } void SumOddEven(void) { int num; int sumEven = 0, sumOdd = 0; cout << "Enter the numbers (negative number to stop): " << endl; cin >> num; while (num >= 0) { if (num % 2 == 0) sumEven = sumEven + num; else sumOdd = sumOdd + num; cin >> num; } cout << "Sum of even numbers = " << sumEven << endl; cout << "Sum of odd numbers = " << sumOdd << endl; } (The function returns nothing (void). Numbers are read one by one; each number is added to the even sum or the odd sum according to num % 2, and the loop stops as soon as a negative number is entered.)
-
Write the procedure of data insertion in middle of the files by Merge Method practiced in older systems.
Topic: File Handling • 5 marks marks
Opened the data file and a new empty file. Started reading the data file from beginning of it. Kept on copying the read data into the new file until the location we want to insert data into is reached. Inserted (appended) new data in the new file. Skipped or jumped the data in the data file that is to be overwritten or replaced. Copied (appended) the remaining part of the file at the end of the new file.
-
Give the syntax of opening file 'myFile.txt' with 'app' mode using ofstream variable 'out'.
Topic: File Handling • 1 mark marks
out.open("myfile.txt" , ios::app); (The ios::app mode opens the file for output so that all data is appended at the end of the file.)
-
Identify any logical or syntax error in the statement below and explain the reason of the error. seekg (-10L, ios::beg);
Topic: File Handling • 2 marks marks
It is a logical error. ios::beg means the offset is measured from the beginning of the file, and the beginning of the file is position 0, so a negative offset (-10L) would try to move the get pointer 10 bytes before the start of the file, which is not possible. A negative offset can only be used with ios::cur (from the current position) or ios::end (from the end of the file).
-
If you are provided two methods for accessing a file; random and sequential. Which method will you prefer and why?
Topic: File Handling • 3 marks marks
Random access will be preferred. In random access, any part (record) of the file can be reached directly and quickly by moving the file pointer with seekg/seekp, without reading all the data before it. In sequential access the file must be read from the beginning, in order, until the required data is found, which wastes time for large files. Random access is therefore faster and more efficient whenever a particular record has to be read, inserted or updated in the middle of a file.
-
Find out errors in the program if any and after correction, write the output. int main() { ofstream outfile; long position; char outfilename[] = "abc.txt"; outfile.open(outfilename); if(!outfile) { cout<<"Error Occured while opening a file"; exit(1); } outfile.write("This is a car", 12); position = outfile.tellp(); outfile.seekp(position-5); outfile.write("jar", 3); outfile.close(); return 0; }
Topic: File Handling • 5 marks marks
Error: The program contains no #include directive at all, so the compiler does not know about the identifiers used in it - ofstream requires <fstream.h>, cout requires <iostream.h> and exit() requires <stdlib.h>. The corrected program must begin with: #include <iostream.h> #include <fstream.h> #include <stdlib.h> Output (contents of the file abc.txt after the program runs): The program prints nothing on the screen; it writes to the file. outfile.write("This is a car", 12) writes only the first 12 of the 13 characters, i.e. "This is a ca". tellp() then returns 12, so position = 12 and seekp(position - 5) moves the put pointer to position 7. Writing "jar" (3 characters) overwrites positions 7, 8 and 9. The final contents of abc.txt are: This isjarca
-
Write a C++ program that will determine if a departmental store customer has exceeded the credit limit on a charge account. Program should input the following facts in five variables: (1) Account number (2) Balance at the beginning of month (Beginning balance) (3) Total of all items charged by customer this month (charges) (4) Total of all credits (credits) (5) Allowed credit limit. Calculate the new balance: New balance = Beginning balance + charges - credits. Determine if new balance exceeds the allowed credit limit. For those customers whose credit limit is exceeded, the program should display the message "Credit Limit exceeded."
Topic: Complete Program Writing • 10 marks marks
#include <iostream.h> main() { int accountNumber; float begBalance, charges, credits, creditLimit, newBalance; cout << "Enter account number: "; cin >> accountNumber; cout << "Enter balance at the beginning of the month: "; cin >> begBalance; cout << "Enter total of all items charged this month: "; cin >> charges; cout << "Enter total of all credits: "; cin >> credits; cout << "Enter allowed credit limit: "; cin >> creditLimit; newBalance = begBalance + charges - credits; cout << "New balance = " << newBalance << endl; if (newBalance > creditLimit) cout << "Credit Limit exceeded." << endl; }
-
Write the syntax for calling a string manipulation function which compares the first 5 characters of an array "name" with the string "asdf". (Marks: 2)
Topic: Arrays & Strings
The strncmp() function of the string.h header file is used to compare a specified number of characters of two strings: strncmp(name, "asdf", 5); It returns 0 if the first 5 characters of both strings are equal, a negative value if the first string is smaller, and a positive value if the first string is greater.
-
What will be the value of x after the execution of the following code segment? int x = 10; int y = 30; int *xptr = &x; x = *xptr + 10; (Marks: 2)
Topic: Pointers
xptr stores the address of x, so *xptr gives the value of x, which is 10. Therefore x = *xptr + 10 = 10 + 10 = 20. The final value of x is 20.
-
Assume that you write a program to read the data from a text file. You have two options to do it: either reading the data character by character or reading multiple lines of data at a time. Which option do you think is more better and why? (Marks: 3)
Topic: File Handling
Reading multiple lines of data at a time is better. Reading character by character requires a separate read operation for every single character, which creates a large overhead and makes the program slow, especially for big files. Reading a bigger block (multiple lines) in one operation reduces the number of read calls, so the data is processed faster and more efficiently.
-
Consider that an integer pointer xptr contains the memory address 0x22ff50. Now if the statement xptr += 4; is executed, how many bytes will the pointer xptr jump in memory and what will be the new address of xptr? (Marks: 3)
Topic: Pointers
Pointer arithmetic moves in steps of the size of the pointed data type. An integer occupies 4 bytes, so adding 4 to an integer pointer moves it forward by 4 x 4 = 16 bytes. New address = 0x22ff50 + 16 (0x10) = 0x22ff60.
-
Write a program which takes a string from the user and searches it within another string "This is my Pakistan". For example, if the user enters the string "my" then after search, the program should display the message "String found"; otherwise it should display the message "string not found". (Marks: 5)
Topic: Arrays & Strings
#include <iostream> #include <string.h> using namespace std; int main() { char text[] = "This is my Pakistan"; char search[30]; cout << "Enter the string to search: "; cin >> search; if (strstr(text, search) != NULL) cout << "String found"; else cout << "string not found"; return 0; } The strstr() function searches the user-entered string inside the text and returns a pointer to its first occurrence, or NULL if it is not present.
-
Detect and correct the compile time error(s) in the following code. (Hint: The following code prints numbers from 1 to 100.) void main() { int counter; float *ptr; for (counter = 1; counter <= 100; counter++) { ptr = counter; cout << ptr << " "; } getch(); return 0; } (Marks: 5)
Topic: Loops
There are two compile-time errors: 1. ptr = counter; assigns an integer value to a float pointer. An integer cannot be assigned to a pointer variable (type mismatch). Moreover, cout << ptr would print a memory address, not the number. 2. return 0; is used inside void main(). A void function cannot return a value; main should be declared as int main(). Corrected code: int main() { int counter; for (counter = 1; counter <= 100; counter++) { cout << counter << " "; } getch(); return 0; }