18.10.26

CS201 Mid Term Papers

Getting ready for the midterm of CS201 (Introduction to Programming)? Here is everything in one place: 549 solved MCQs, 130 subjective questions and 33 short notes, gathered from past papers and files shared by students. Duplicates are removed, and wherever a shared answer key turned out to be wrong it has been corrected, so you can trust what you revise. Use the Objective and Subjective buttons above to switch between the two sections, and tap Show answer only after you have tried the question yourself. Best of luck with your exam!

Part 1: MCQs

Q1. How many dimensions does an n-dimensional array have?

  1. n dimensions
  2. 2n dimensions
  3. (n+1) dimensions
  4. (n-1) dimensions
Show answer

Answer: (a) n dimensions

Q2. Which of the following function calls is "call by reference" for the function prototype void func(int *);?

  1. func(int &num);
  2. func(&num);
  3. func(*num);
  4. func(num);
Show answer

Answer: (b) func(&num);

Q3. The operators ++ and -- are used to increment or decrement the value of a variable by ______.

  1. 3
  2. 2
  3. 1
  4. 4
Show answer

Answer: (c) 1

Q4. The loop which is most suitable to be used when the number of iterations is known is called ______.

  1. for
  2. while
  3. do-while
  4. all looping processes require that the iterations be known
Show answer

Answer: (a) for

Q5. In C/C++, a string constant is enclosed in ______.

  1. curly braces {}
  2. parentheses ()
  3. single quotes ' '
  4. double quotes " "
Show answer

Answer: (d) double quotes " "

Q6. In order to get the right-most digit of a number, we divide the number by 10 and take ______.

  1. Its remainder
  2. Its quotient
  3. Its divisor
  4. The number
Show answer

Answer: (a) Its remainder

Q7. What is the correct syntax to declare an array of size 10 of int data type?

  1. int [10] name;
  2. name[10] int;
  3. int name[10];
  4. int name[];
Show answer

Answer: (c) int name[10];

Q8. How many bytes of memory are occupied by the array 'str'? char str[] = "programming";

  1. 10
  2. 11
  3. 12
  4. 13
Show answer

Answer: (c) 12
Note: The source key marked 11, but "programming" has 11 letters plus the null character '\0' that C/C++ appends to every string constant, so the array occupies 12 bytes.

Q9. When an if statement consists of more than one statement, enclosing these statements in curly braces is ______.

  1. Not required
  2. Good programming
  3. Relevant
  4. Must
Show answer

Answer: (d) Must

Q10. Suppose an integer-type pointer contains the memory address 0x22f230. What will be the new memory address after the pointer is incremented (ptr++), assuming an int takes 4 bytes?

  1. 0x22f231
  2. 0x22f234
  3. 0x22f226
  4. 0x22f238
Show answer

Answer: (b) 0x22f234
Note: Pointer arithmetic: incrementing an int pointer moves it by sizeof(int) = 4 bytes, so 0x22f230 + 4 = 0x22f234.

Q11. Which of the following, if missing, would result in infinite recursion in a recursive function?

  1. Recursive call
  2. Base case
  3. Function parameters
  4. Local variables
Show answer

Answer: (b) Base case
Note: The source key marked 'Recursive call', but a recursive function without a base case never stops calling itself; without the recursive call it would not be recursion at all.

Q12. Whenever we use a library function or a predefined object or macro, we need to use a ______.

  1. source file
  2. object file
  3. header file
  4. exe file
Show answer

Answer: (c) header file

Q13. A switch statement deals with ______ type of data.

  1. Integer
  2. Float
  3. Character
  4. Both Integer and Character
Show answer

Answer: (d) Both Integer and Character

Q14. Both the compiler and the ______ are used to translate a program into machine language code.

  1. debugger
  2. linker
  3. loader
  4. interpreter
Show answer

Answer: (d) interpreter

Q15. TWAIN stands for ______.

  1. Technology With An Interesting Name
  2. Technology Without An Informative Name
  3. Technology Without An Interesting Name
  4. Technology With An Informative Name
Show answer

Answer: (c) Technology Without An Interesting Name

Q16. The parameter passed to the isdigit() function is ______.

  1. a character variable
  2. a boolean variable
  3. an integer variable
  4. a character string
Show answer

Answer: (a) a character variable

Q17. C++ views each file as a sequential stream of ______.

  1. Bits
  2. Bytes
  3. Numbers
  4. Words
Show answer

Answer: (b) Bytes

Q18. A structure is a collection of ______ under a single name.

  1. only functions
  2. only variables
  3. both functions and variables
  4. only data types
Show answer

Answer: (b) only variables
Note: As taught in this course, a structure groups variables (of possibly different types) under one name.

Q19. The default mode for writing into a file using an ofstream object is ______.

  1. out
  2. bin
  3. app
  4. ate
Show answer

Answer: (a) out

Q20. The memory address of the first element of an array is called ______.

  1. floor address
  2. foundation address
  3. first address
  4. base address
Show answer

Answer: (d) base address

Q21. We want to access an array in random order. Which of the following approaches is better?

  1. Pointers
  2. Array index
  3. Both pointers and array index are better
  4. Matrix
Show answer

Answer: (b) Array index

Q22. The ______ structure is a multiple-selection construct which makes the code more efficient and easier to read.

  1. multiple-if
  2. switch
  3. if-else
  4. else-if
Show answer

Answer: (b) switch

Q23. Which of the following is not a reserved word in C/C++?

  1. int
  2. float
  3. double
  4. sum
Show answer

Answer: (d) sum

Q24. To access rand(), which library (header file) is required to be included in the program?

  1. conio.h
  2. stdio.h
  3. stdlib.h
  4. iostream.h
Show answer

Answer: (c) stdlib.h

Q25. What is the highest legal index for the following array? int arr[4];

  1. 4
  2. 3
  3. 2
  4. 1
Show answer

Answer: (b) 3

Q26. When an array element is passed to a function, it is passed by ______.

  1. reference
  2. data type
  3. value
  4. data
Show answer

Answer: (c) value
Note: The source key marked 'reference', but an individual array element is passed by value (only the whole array name, i.e. the address, is passed by reference).

Q27. While programming, it is good to provide an easy-to-understand and easy-to-use interface; this property is called ______.

  1. scalability
  2. usability
  3. reliability
  4. sustainability
Show answer

Answer: (b) usability

Q28. A word processor is a type of ______.

  1. operating system
  2. application software
  3. device driver
  4. utility software
Show answer

Answer: (b) application software

Q29. A 'while' loop may execute ______ or more times.

  1. three
  2. zero
  3. two
  4. one
Show answer

Answer: (b) zero

Q30. The keyword ______ is used to get some value back from a function.

  1. return
  2. break
  3. continue
  4. goto
Show answer

Answer: (a) return

Q31. Identify the correct option which is used for calling the function float area(int).

  1. area(&num);
  2. area(num);
  3. area(int num);
  4. area(*num);
Show answer

Answer: (b) area(num);
Note: The source key marked 'area(int num);', but that is a declaration/definition style (it names the parameter type). A call passes just the argument: area(num);

Q32. The ______ statement allows us to select from multiple choices based on a set of fixed values.

  1. switch
  2. break
  3. continue
  4. goto
Show answer

Answer: (a) switch

Q33. C is widely known as the development language of the ______ operating system.

  1. Windows
  2. Unix
  3. Mac OS
  4. Linux
Show answer

Answer: (b) Unix

Q34. The syntax of a union is identical to that of a ______.

  1. structure
  2. class
  3. function
  4. loop
Show answer

Answer: (a) structure

Q35. The function write() takes ______ as parameter(s).

  1. String of pointer type
  2. String of variable lengths, no. of bytes to be read and flags
  3. Pointer array of characters and a delimiter
  4. String and no. of bytes to be written
Show answer

Answer: (d) String and no. of bytes to be written

Q36. When the logical operator AND (&&) combines two expressions exp1 and exp2, the result is true:

  1. When both exp1 and exp2 are true
  2. When both exp1 and exp2 are false
  3. When exp1 is true and exp2 is false
  4. When exp1 is false and exp2 is true
Show answer

Answer: (a) When both exp1 and exp2 are true

Q37. The null character is used to indicate the ______ of a string.

  1. Start
  2. End
  3. Begin
  4. Middle
Show answer

Answer: (b) End

Q38. Which one of the symbols is used to represent a decision in a flow chart?

  1. Circle
  2. Diamond
  3. Rectangle
  4. Rounded rectangle (terminator)
Show answer

Answer: (b) Diamond
Note: Shapes are shown as pictures in the source: circle, diamond, rectangle, rounded rectangle.

Q39. In a flow chart, the flow of control is represented by ______.

  1. Rectangle
  2. Circle
  3. Diamond
  4. Arrow
Show answer

Answer: (d) Arrow

Q40. There can be ______ 'default' statement(s) in any switch structure.

  1. 1
  2. 2
  3. 3
  4. n
Show answer

Answer: (a) 1
Note: The source key marked '2', but a switch structure can have at most one default label.

Q41. The condition in a loop should be a(n) ______.

  1. Constant Expression
  2. Boolean Expression
  3. Primary Expression
  4. Arithmetic Expression
Show answer

Answer: (b) Boolean Expression

Q42. How many nested loops would be required to manipulate an n-dimensional array?

  1. n
  2. n + 1
  3. n - 1
  4. 2n
Show answer

Answer: (a) n
Note: The source key marked '2n', but each dimension needs one loop, so an n-dimensional array needs n nested loops.

Q43. Which of the following is not an example of the int data type?

  1. 0
  2. -32
  3. 65531
  4. -4.0
Show answer

Answer: (d) -4.0

Q44. We should use ______ for clarity and to force the order of evaluation in an expression.

  1. Brackets []
  2. parentheses ()
  3. curly braces {}
  4. quotation marks " "
Show answer

Answer: (b) parentheses ()

Q45. Which of the following is the starting index of an array in C++?

  1. 0
  2. 1
  3. -1
  4. 2
Show answer

Answer: (a) 0

Q46. An array is a data structure that stores ______.

  1. Memory addresses
  2. Variables
  3. Data type
  4. Data
Show answer

Answer: (b) Variables
Note: Judgment call: the source key says 'Variables' (a collection of variables of the same type).

Q47. A program statement that invokes a function is called a ______.

  1. function declaration
  2. function call
  3. function definition
  4. function prototype
Show answer

Answer: (b) function call

Q48. The compiler of the C language is written in ______ language.

  1. JAVA
  2. BASIC
  3. FORTRON
  4. C
Show answer

Answer: (d) C

Q49. Which one of the following functions is not included in the ctype.h header file?

  1. isdigit(int c)
  2. isxdigit(int c)
  3. tolower(int c)
  4. getdigit(int c)
Show answer

Answer: (d) getdigit(int c)
Note: No such function as getdigit() exists in ctype.h; the other three do.

Q50. Which function is used to locate the first occurrence of a character in a string?

  1. strchr()
  2. strstr()
  3. strtok()
  4. strlen()
Show answer

Answer: (a) strchr()
Note: The source key marked strlen(), which only returns the length of a string. strchr() finds the first occurrence of a character; strstr() finds a substring.

Q51. ______ is the pointer which determines the position in a file from where the next read operation will occur.

  1. put
  2. seek
  3. get
  4. tell
Show answer

Answer: (c) get
Note: The get pointer controls reading (the put pointer controls writing). No sticker was visible in the scan, so this is based on the lesson.

Q52. Which of the following operators is used to access the value of the variable pointed to by a pointer?

  1. * operator
  2. -> operator
  3. && operator
  4. & operator
Show answer

Answer: (a) * operator
Note: The source key marked '&' (the address-of operator). The dereference operator * gives the value a pointer points to.

Q53. In case of single dereferencing, the value of the ______ is the address of the ______.

  1. pointer, variable
  2. pointer, constant
  3. variable, pointer
  4. constant, pointer
Show answer

Answer: (a) pointer, variable

Q54. The remainder (%) operator is a ______ operator.

  1. Logical
  2. Arithmetic
  3. Relational
  4. Conditional
Show answer

Answer: (b) Arithmetic

Q55. What will be the output of the following code? int x = 10; cout << "x =" << x;

  1. 10
  2. "x=10"
  3. x=10
  4. 10=x
Show answer

Answer: (c) x=10

Q56. The purpose of using cout<< is to ______.

  1. Display information on the screen
  2. Read the data from keyboard
  3. Read the data from a file
  4. Write into a file
Show answer

Answer: (a) Display information on the screen

Q57. ______ executes all the lines before an error and stops at the line which contains the error.

  1. Interpreter
  2. Compiler
  3. Linker
  4. Debugger
Show answer

Answer: (a) Interpreter

Q58. Which one of the following is the correct syntax to access the value of the first element of an array using a pointer ptr?

  1. ptr[0]
  2. *(ptr+1)
  3. ptr[1]
  4. *ptr[0]
Show answer

Answer: (a) ptr[0]
Note: Only ptr[0] reads the first element; *(ptr+1) and ptr[1] give the second element, and *ptr[0] is invalid.

Q59. C is a/an ______ language.

  1. low level
  2. object based
  3. object oriented
  4. function oriented
Show answer

Answer: (d) function oriented

Q60. The ______ of a function is also known as the signature of the function.

  1. Definition
  2. Declaration
  3. Calling
  4. Invoking
Show answer

Answer: (b) Declaration

Q61. ______ are very good tools for code reuse.

  1. operators
  2. loops
  3. functions
  4. variables
Show answer

Answer: (c) functions

Q62. If a break statement is missed in a switch statement then ______.

  1. compiler will give error
  2. this may cause a logical error
  3. no effect on program
  4. program stops its execution
Show answer

Answer: (b) this may cause a logical error

Q63. A 2D array multi[5][10] can be accessed using the array name as **multi; this technique is called ______.

  1. Single referencing
  2. Single dereferencing
  3. Double referencing
  4. Double dereferencing
Show answer

Answer: (d) Double dereferencing

Q64. In C/C++, the default command line arguments passed to the main function are ______.

  1. float argc, char **argv
  2. int argc, char **argv
  3. int *argc, char *argv
  4. int argc, float **argv
Show answer

Answer: (b) int argc, char **argv

Q65. A record is a group of related ______.

  1. Files
  2. Bytes
  3. Fields
  4. Data
Show answer

Answer: (c) Fields
Note: The source key marked 'Data', but in file processing a field is a group of characters, a record is a group of related fields, and a file is a group of related records.

Q66. The statement x += y can be interpreted as ______.

  1. Adding the value of x to the value of y and storing the result in x
  2. Adding the value of y to the value of x; store the result in y
  3. Adding the value of x to the value of x; store the result in x
  4. Adding the value of y to the value of y; store the result in x
Show answer

Answer: (a) Adding the value of x to the value of y and storing the result in x
Note: x += y is shorthand for x = x + y, so the result is stored in x. No answer sticker was visible in the scan for this question.

Q67. The function seekg() takes ______ parameter(s).

  1. 0
  2. 1
  3. 2
  4. 3
Show answer

Answer: (c) 2

Q68. In order to get 256 from the number 2568 we divide this number by 10 and take,

  1. Its remainder
  2. The number
  3. Its quotient
  4. Its divisor
Show answer

Answer: (c) Its quotient

Q69. The correct syntax of do-while loop is,

  1. (condition ) while; do { statements; };
  2. { statements; } do-while ();
  3. while(condition); do { statements; };
  4. do { statements; } while (condition);
Show answer

Answer: (d) do { statements; } while (condition);

Q70. Which of the following function(s) is/are included in stdlib.h header file?

  1. double atof(const char *nptr)
  2. int atoi(const char *nptr)
  3. char *strcpy ( char *s1, const char *s2)
  4. 1 and 2 only
Show answer

Answer: (d) 1 and 2 only

Q71. If the break statement is missed in switch statement then,

  1. The compiler will give error
  2. This may cause a logical error
  3. No effect on program
  4. Program stops its execution
Show answer

Answer: (b) This may cause a logical error

Q72. The data type before a function name represents its,

  1. Return Type
  2. Function data
  3. Function arguments
  4. Function name
Show answer

Answer: (a) Return Type

Q73. Member function tellg() returns the current location of the _ pointer.

  1. tellptr()
  2. write()
  3. seekg()
  4. get()
Show answer

Answer: (d) get()

Q74. What does 5 | 6 , evaluate to in decimal where ‘|’ is bitwise OR operator?

  1. 3
  2. 4
  3. 5
  4. 7
Show answer

Answer: (d) 7

Q75. What will be the result of arithmetic expression 6+27/3*3?

  1. 33
  2. 45
  3. 9
  4. 30
Show answer

Answer: (a) 33
Note: The source key marked 9, but multiplication and division are evaluated left to right: 27/3 = 9, 9*3 = 27, and 6 + 27 = 33.

Q76. What will be the correct syntax for initialization of pointer ptr with string "programming"?

  1. char ptr = ’programming’ ;
  2. char *ptr = “programming” ;
  3. char *ptr = ‘programming’ ;
  4. *ptr = “programming” ;
Show answer

Answer: (b) char *ptr = “programming” ;

Q77. What will be the result of expression x%= 2, if x = 7?

  1. x = 1
  2. x = 3
  3. x = 7
  4. x = 2
Show answer

Answer: (a) x = 1

Q78. UNIX has been developed in language.

  1. JAVA
  2. B
  3. C
  4. FORTRAN
Show answer

Answer: (c) C

Q79. Declaring structures does not mean that memory is allocated.

  1. True
  2. False
Show answer

Answer: (a) True

Q80. What is the output of the following statement? int i = 2.5; do { cout i * 2; } while (i > 3 && i < 10);

  1. 510
  2. 5
  3. 48
  4. error
Show answer

Answer: (d) error
Note: As printed, 'cout i * 2' has no << operator, so the code does not compile.

Q81. The condition in while loop may contain logical expression but not relational expression.

  1. True
  2. False
Show answer

Answer: (b) False

Q82. Searching is easier when an array is already sorted

  1. True
  2. False
Show answer

Answer: (a) True

Q83. If an array has 100 elements, what is allowable range of subscripts?

  1. 0 - 99
  2. 1 - 99
  3. 0 - 100
  4. 1 - 100
Show answer

Answer: (a) 0 - 99

Q84. What will be the value of ‘a’ and ‘b’ after executing the following statements? a = 3; b = a++;

  1. 3, 4
  2. 4, 4
  3. 3, 3
  4. 4, 3
Show answer

Answer: (d) 4, 3
Note: b = a++ first copies the old value of a (3) into b and then increments a, so a = 4 and b = 3.

Q85. Which of the following function returns the size of a string variable?

  1. strlength()
  2. stringlen()
  3. strlen()
  4. strLength()
Show answer

Answer: (c) strlen()

Q86. What will be the range of numbers generated by function rand () % 9?

  1. 0 to 9
  2. 1 to 9
  3. 0 to 8
  4. 1 to 8
Show answer

Answer: (c) 0 to 8

Q87. Computer can understand only machine language code.

  1. True
  2. False
Show answer

Answer: (a) True

Q88. Which of the following header file include string conversion functions?

  1. string.h
  2. stdlib.h
  3. ctype.h
  4. sconvert.h
Show answer

Answer: (b) stdlib.h

Q89. A precise sequence of steps to solve a problem is called

  1. Statement
  2. Program
  3. Utility
  4. Routine
Show answer

Answer: (b) Program

Q90. The Compiler of C language is written in

  1. Java Language
  2. UNIX
  3. FORTRON Language
  4. C Language
Show answer

Answer: (d) C Language

Q91. Initialization of variable at the time of definition is,

  1. Must
  2. Necessary
  3. Good Programming
  4. None of the given options
Show answer

Answer: (c) Good Programming

Q92. In if structure the block of statements is executed only,

  1. When the condition is false
  2. When it contain arithmetic operators
  3. When it contain logical operators
  4. When the condition is true
Show answer

Answer: (d) When the condition is true

Q93. Dealing with structures and functions passing by reference is the most economical method

  1. True
  2. False
Show answer

Answer: (a) True

Q94. Pointer is a variable which store,

  1. Data
  2. Memory Address
  3. Data Type
  4. Values
Show answer

Answer: (b) Memory Address

Q95. Preprocessor program perform its function before phase takes place.

  1. Editing
  2. Linking
  3. Compiling
  4. Loading
Show answer

Answer: (c) Compiling

Q96. Which of the following can not be a variable name?

  1. area
  2. _area
  3. 10area
  4. area2
Show answer

Answer: (c) 10area

Q97. Which character is inserted at the end of string to indicate the end of string?

  1. new line
  2. tab
  3. null
  4. carriage return
Show answer

Answer: (c) null

Q98. Which of the following header file defines the rand() function?

  1. iostream.h
  2. conio.h
  3. stdlib.h
  4. stdio.h
Show answer

Answer: (c) stdlib.h

Q99. Commenting the code

  1. Makes a program easy to understand for others.
  2. Make programs heavy, i.e. more space is needed for executable.
  3. Makes it difficult to compile
  4. All of the given options.
Show answer

Answer: (a) Makes a program easy to understand for others.

Q100. What's wrong with this for loop? for (int k = 2, k <=12, k++)

  1. the increment should always be ++k
  2. the variable must always be the letter i when using a for loop
  3. there should be a semicolon at the end of the statement
  4. the commas should be semicolons
Show answer

Answer: (d) the commas should be semicolons

Q101. For which array, the size of the array should be one more than the number of elements in an array?

  1. int
  2. double
  3. float
  4. char
Show answer

Answer: (d) char

Q102. The function of cin is

  1. To display message
  2. To read data from keyboard
  3. To display output on the screen
  4. To send data to printer
Show answer

Answer: (b) To read data from keyboard

Q103. In C/C++ language the header file which is used to perform useful task and manipulation of character data is

  1. cplext.h
  2. ctype.h
  3. stdio.h
  4. delay.h
Show answer

Answer: (b) ctype.h

Q104. How many parameter(s) function getline() takes?

  1. 0
  2. 1
  3. 2
  4. 3
Show answer

Answer: (d) 3

Q105. For which values of the integer _value will the following code becomes an infinite loop? int number=1; while (true) { cout << number; if (number == 3) break; number += integer_value; }

  1. any number other than 1 or 2
  2. only 0
  3. only 1
  4. only 2
Show answer

Answer: (a) any number other than 1 or 2
Note: The loop ends only when number reaches 3, which happens only for integer_value 1 or 2 (1+1+1 or 1+2). For any other value (0, negative, 3 and above) it never reaches 3. The source key 'only 0' is incomplete.

Q106. Each pass through a loop is called a/an

  1. enumeration
  2. Iteration
  3. culmination
  4. pass through
Show answer

Answer: (b) Iteration

Q107. A continue statement causes execution to skip to

  1. the return 0; statement
  2. the first statement after the loop
  3. the statements following the continue statement
  4. the next iteration of the loop
Show answer

Answer: (d) the next iteration of the loop

Q108. Consider the following code segment. What will the following code segment display? int main(){ int age[10] = {0}; cout << age ; }

  1. Values of all elements of array
  2. Value of first element of array
  3. Starting address of array
  4. Address of last array element
Show answer

Answer: (c) Starting address of array
Note: The source key said 'value of first element', but cout << age prints the name of the array, which is the address of its first element.

Q109. How many bytes will the pointer intPtr of type int move in the following statement? intPtr += 3 ;

  1. 3 bytes
  2. 6 bytes
  3. 12 bytes
  4. 24 bytes
Show answer

Answer: (c) 12 bytes

Q110. The statement interrupts the flow of control.

  1. switch
  2. continue
  3. goto
  4. break
Show answer

Answer: (d) break

Q111. Analysis is the --------------- step in designing a program

  1. Last
  2. Middle
  3. Post Design
  4. First
Show answer

Answer: (d) First

Q112. Paying attention to detail in designing a program is

  1. Time consuming
  2. Redundant
  3. Necessary
  4. Somewhat Good
Show answer

Answer: (c) Necessary

Q113. There are mainly ------------------ types of software

  1. Two
  2. Three
  3. Four
  4. Five
Show answer

Answer: (a) Two

Q114. In C/C++ the #include is called,

  1. Header file
  2. Preprocessor Directive
  3. Statement
  4. Function
Show answer

Answer: (b) Preprocessor Directive

Q115. && is ------------------operator.

  1. An arithmetic
  2. Logical
  3. Relational
  4. Unary
Show answer

Answer: (b) Logical

Q116. In flow chart, the symbol used for decision making is,

  1. Rectangle
  2. Circle
  3. Arrow
  4. Diamond
Show answer

Answer: (d) Diamond

Q117. C++ views each file as a sequential stream of .

  1. Bytes
  2. Bits
  3. 0’s or 1’s
  4. Words
Show answer

Answer: (a) Bytes

Q118. If the elements of an array are already sorted then the useful search algorithm is,

  1. Linear search
  2. Binary search
  3. Quick search
  4. Random search
Show answer

Answer: (b) Binary search

Q119. The address operator (&) can be used with,

  1. Statement
  2. Expression
  3. Variable
  4. Constant
Show answer

Answer: (c) Variable

Q120. When a pointer is incremented, it actually jumps the number of memory addresses

  1. According to data type
  2. 1 byte exactly
  3. 1 bit exactly
  4. A pointer variable can not be incremented
Show answer

Answer: (a) According to data type

Q121. Call by reference mechanism should be used in a program when there is i. large amount of data to be passed ii. small amount of data to be passed iii. need to change the passed data iv. no need to change the passed data Choose the appropriate option for the above case.

  1. (i) and (ii) only
  2. (i) and (iii) only
  3. (ii) and (iii) only
  4. (ii) and (iv) only
Show answer

Answer: (b) (i) and (iii) only

Q122. Which of the following is the starting index of an array in C++?

  1. 0
  2. 1
  3. -1
  4. any number
Show answer

Answer: (a) 0

Q123. The return type of a function that do not return any value must be

  1. int
  2. void
  3. double
  4. float
Show answer

Answer: (b) void

Q124. Which of the following is an extension of header file?

  1. .exe
  2. .txt
  3. .h
  4. .c
Show answer

Answer: (c) .h

Q125. We want to access array in random order which approach is better?

  1. Pointers
  2. Array index
  3. Both pointers and array index are better
  4. None of the given options.
Show answer

Answer: (b) Array index

Q126. When we declare a multidimensional array the compiler store the elements of multidimensional array in the form of,

  1. Columns
  2. Rows
  3. Contiguous memory location
  4. Matrix
Show answer

Answer: (c) Contiguous memory location

Q127. In C/C++ the string constant is enclosed

  1. In curly braces
  2. In small braces
  3. In single quotes
  4. In double quotes
Show answer

Answer: (d) In double quotes

Q128. The size of int data type is

  1. 1 bytes
  2. 2 bytes
  3. 3 bytes
  4. 4 bytes
Show answer

Answer: (d) 4 bytes

Q129. In Flow chart process is represented by

  1. Rectangle
  2. Arrow symbol
  3. Oval
  4. Circle
Show answer

Answer: (a) Rectangle

Q130. When we are using const keyword with a variable x then initializing it at the time of declaration is,

  1. Must
  2. Optional
  3. Not necessary
  4. A syntax error
Show answer

Answer: (a) Must

Q131. Which of the following is the correct way to assign an integer value 5 to element of a matrix say ‘m’ at second row and third column?

  1. m[2][3] = 5 ;
  2. m[3][2] = 5 ;
  3. m[1][2] = 5 ;
  4. m[2][3] = ‘5’;
Show answer

Answer: (c) m[1][2] = 5 ;
Note: Array indexes start at 0, so the second row is index 1 and the third column is index 2: m[1][2]. The source key m[2][3] was wrong.

Q132. How many total elements must be in two-dimensional array of 3 rows and 2 columns?

  1. 4
  2. 5
  3. 6
  4. 7
Show answer

Answer: (c) 6

Q133. Which of the following is the correct statement for the following declaration? const int *ptr.

  1. ptr is a constant pointer
  2. ptr is constant integer pointer
  3. ptr is a constant pointer to int
  4. ptr is a pointer to const int
Show answer

Answer: (d) ptr is a pointer to const int

Q134. Consider the following code segment. What will be the output of this code segment? int arr[6] = {2, 3, 7, 4, 5, 6} ; int *ptr1 =&arr[1] ; int *ptr2 = &arr[4] ; cout << (ptr2-ptr1) ;

  1. 3
  2. 9
  3. 12
  4. 2
Show answer

Answer: (a) 3
Note: ptr2 - ptr1 counts elements between the pointers: index 4 minus index 1 = 3. The source key said 2.

Q135. What will be the correct syntax to assign an array named arr of 5 elements to a pointer ptr?

  1. *ptr = arr ;
  2. ptr = arr ;
  3. *ptr = arr[5] ;
  4. ptr = arr[5] ;
Show answer

Answer: (b) ptr = arr ;

Q136. The variables having a name, type and size are just like empty boxes.

  1. False
  2. True
Show answer

Answer: (b) True

Q137. Most efficient method of dealing with structure variables is to define the structure globally

  1. True
  2. False
Show answer

Answer: (a) True

Q138. Syntax of union is identical to

  1. Structure
  2. Class
  3. Function
  4. None of the given options
Show answer

Answer: (a) Structure

Q139. Compiler is a ______.

  1. System software
  2. Application software
  3. Driver
  4. Editor
Show answer

Answer: (a) System software

Q140. If Num is an integer variable then Num++ means ______.

  1. Add 1 two times with Num
  2. Add 1 with Num
  3. Add 2 with Num
  4. Subtract 2 from Num
Show answer

Answer: (b) Add 1 with Num

Q141. For one byte there are ______ combinations of values that can be stored in a computer.

  1. 2^6
  2. 2^7
  3. 2^8
  4. 2^4
Show answer

Answer: (c) 2^8
Note: One byte = 8 bits, and n bits can hold 2^n different values, so 2^8 = 256.

Q142. The default case in a switch statement is ______.

  1. Must
  2. Optional
  3. Syntax error
  4. Necessary
Show answer

Answer: (b) Optional

Q143. When the break statement is encountered in a switch statement, it ______.

  1. Stops the entire program
  2. Stops the execution of the current statement
  3. Exits from the switch statement
  4. None of the given options
Show answer

Answer: (c) Exits from the switch statement

Q144. What will be the correct syntax to access the value of the fourth element of an array using pointer ptr?

  1. ptr[3]
  2. (ptr+3)
  3. *(ptr+3)
  4. Both 1 and 3
Show answer

Answer: (d) Both 1 and 3
Note: ptr[3] and *(ptr+3) are equivalent. (ptr+3) without * is only an address.

Q145. Which values does C++ use to represent true and false?

  1. 1 and 0
  2. 1 and -1
  3. 11 and 00
  4. Any numerical value
Show answer

Answer: (a) 1 and 0

Q146. If a variable is passed by value to a function and the function changes that variable, then it ______.

  1. Does not affect the original variable
  2. Affects the original variable
  3. Causes a syntax error
  4. None of the given options
Show answer

Answer: (a) Does not affect the original variable

Q147. Loops are ______ structures.

  1. Decision
  2. Repetition
  3. Sequential
  4. Hierarchical
Show answer

Answer: (b) Repetition

Q148. Switch statement deals with ______.

  1. Integer data only
  2. float data only
  3. character data only
  4. Integer and character data
Show answer

Answer: (d) Integer and character data

Q149. If it is required to copy an array to another array, then ______.

  1. Both arrays must be of the same size and data type
  2. Both arrays may be of different size
  3. Both arrays may be of different data type
  4. Both arrays may be of different size and type
Show answer

Answer: (a) Both arrays must be of the same size and data type

Q150. The precedence of * (dereference) is higher than the dot operator.

  1. True
  2. False
Show answer

Answer: (b) False
Note: The dot (member access) operator has higher precedence than the unary * operator.

Q151. Pointers work by pointing to a data type, which can be of the form ______.

  1. Integer only
  2. double only
  3. character only
  4. All of the given options
Show answer

Answer: (d) All of the given options

Q152. Which looping process checks the test condition at the end of the loop?

  1. for
  2. while
  3. do while
  4. no looping process checks the test condition at the end
Show answer

Answer: (c) do while

Q153. What is the correct syntax for the statement: ptr is a constant pointer to integer?

  1. const int *ptr;
  2. const *int ptr;
  3. int const *ptr;
  4. int *const ptr;
Show answer

Answer: (d) int *const ptr;
Note: int *const ptr means the pointer itself is constant. const int *ptr (or int const *ptr) is a pointer to a constant int.

Q154. A function must always return a value.

  1. True
  2. False
Show answer

Answer: (b) False
Note: A function with return type void returns nothing.

Q155. The assignment operator is used for ______.

  1. calculation
  2. reading
  3. assigning values to variables
  4. None of the given options.
Show answer

Answer: (c) assigning values to variables

Q156. Which of the following functions are included in the ctype.h header file?

  1. isdigit(int c)
  2. isxdigit(int c)
  3. tolower(int c)
  4. All of the above
Show answer

Answer: (d) All of the above

Q157. Both the compiler and the interpreter are used to translate a program into machine language code.

  1. True
  2. False
Show answer

Answer: (a) True

Q158. A missing semicolon ';' at the end of a C++ statement is a ______.

  1. Logical error
  2. Syntax error
  3. Runtime error
  4. None of the given options
Show answer

Answer: (b) Syntax error

Q159. A switch statement is an alternative to the ______ statement.

  1. multiple if
  2. continue
  3. break
  4. goto
Show answer

Answer: (a) multiple if

Q160. An array is passed by value to a function by default.

  1. True
  2. False
Show answer

Answer: (b) False
Note: Arrays are passed by reference: the function receives the address of the first element.

Q161. Which of the following is the correct function call for an array named student of 10 elements as a parameter?

  1. addRecord(student[]);
  2. addRecord(student);
  3. addRecord(student[10]);
  4. addRecord(*student);
Show answer

Answer: (b) addRecord(student);

Q162. What will be the output of the following code? main(){ int x = 5; { int x = 4; cout << x; } cout << x; }

  1. 5, 5
  2. 4, 4
  3. 4, 5
  4. 5, 4
Show answer

Answer: (c) 4, 5
Note: The inner block's own x (4) is printed first, then the outer x (5). The source code omits the << operator and semicolons.

Q163. The object ______ may be used for both file input and file output.

  1. fstream
  2. ifstream
  3. ofstream
  4. none of the given options
Show answer

Answer: (a) fstream

Q164. union intorDouble { int ival; double charvar; }; What is the value of size = sizeof(VAZ) if int occupies 4 bytes and double occupies 8 bytes?

  1. 2
  2. 4
  3. 8
  4. 12
Show answer

Answer: (c) 8
Note: A union is as large as its largest member, so sizeof is 8.

Q165. C language was developed by ______.

  1. Bill Gates
  2. Robert Lafore
  3. Dennis Ritchie
  4. Deitel & Deitel
Show answer

Answer: (c) Dennis Ritchie

Q166. The name of an array represents the address of the first element of the array.

  1. True
  2. False
Show answer

Answer: (a) True

Q167. When an identifier is declared with the keyword const then ______.

  1. Its value can be changed during execution
  2. Its value cannot be changed
  3. Its value can be changed with an arithmetic operator
  4. Its value can be overwritten
Show answer

Answer: (b) Its value cannot be changed

Q168. In C/C++ if we define an array of size eight, int Arr[8]; then the last element is stored at ______.

  1. Arr[0]
  2. Arr[8]
  3. Arr[7]
  4. Arr[-1]
Show answer

Answer: (c) Arr[7]

Q169. When a pointer is incremented, it actually jumps the number of memory addresses ______.

  1. According to data type
  2. 1 byte exactly
  3. 1 bit exactly
  4. A pointer variable cannot be incremented
Show answer

Answer: (a) According to data type

Q170. A do-while loop executes at least ______.

  1. Zero times
  2. One time
  3. Two times
  4. N times
Show answer

Answer: (b) One time

Q171. +=, *=, /=, etc. are called ______.

  1. Assignment operators
  2. Logical operators
  3. Compound assignment operators
  4. Unary operators
Show answer

Answer: (c) Compound assignment operators
Note: Both 'Assignment operators' and 'Compound assignment operators' describe them loosely; the course term for these is compound assignment operators.

Q172. Compilers and interpreters also belong to the System Software category.

  1. True
  2. False
Show answer

Answer: (a) True

Q173. Editors are used to compile the code.

  1. True
  2. False
Show answer

Answer: (b) False
Note: Compilers compile source code; editors are only used to write it.

Q174. Application Softwares are use to

  1. Type letters
  2. Control computer hardware
  3. Solve end user problems
  4. Develop Graphics
Show answer

Answer: (c) Solve end user problems

Q175. Computer can do,

  1. More than what we tell it
  2. Less then what we tell it
  3. Like human being
  4. Exactly what we tell it
Show answer

Answer: (d) Exactly what we tell it

Q176. we can control our program while it is running by using

  1. Debugger
  2. Linker
  3. Loader
  4. Editor
Show answer

Answer: (a) Debugger

Q177. The remainder (%) operator is,

  1. An arithmetic operator
  2. A logical operator
  3. A relational operator
  4. A division operator
Show answer

Answer: (a) An arithmetic operator

Q178. int x = 2 * 3 + 4 * 5; What value will x contain in the sample code above?

  1. 22
  2. 26
  3. 46
  4. 50
Show answer

Answer: (b) 26

Q179. What is the correct value to return to the operating system upon the successful completion of a program?

  1. -1
  2. 1
  3. 0
  4. Programs do not return a value.
Show answer

Answer: (c) 0

Q180. What is the only function all C++ programs must contain?

  1. start()
  2. system()
  3. main()
  4. program()
Show answer

Answer: (c) main()

Q181. What punctuation ends most lines of C++ code?

  1. (dot)
  2. (semi-colon)
  3. (colon)
  4. (single quote)
Show answer

Answer: (b) (semi-colon)

Q182. Which of the following is a correct comment?

  1. */ Comments */
  2. ** Comment **
  3. /* Comment */
  4. { Comment }
Show answer

Answer: (c) /* Comment */

Q183. Which of the following is not a correct variable type?

  1. float
  2. real
  3. int
  4. double
Show answer

Answer: (b) real

Q184. Which of the following is the correct operator to compare two variables?

  1. :=
  2. =
  3. equal
  4. ==
Show answer

Answer: (d) ==

Q185. Identify the correct statement

  1. Programmer can use comments to include short explanations within the source code itself.
  2. All lines beginning with two slash signs are considered comments.
  3. Comments very important effect on the behavior of the program
  4. both
Show answer

Answer: (d) both
Note: Both statements are true, so 'both' is correct. The source key marked only the second statement.

Q186. There is a unique function in C++ program by where all C++ programs start their execution

  1. Start()
  2. Begin()
  3. Main()
  4. Output()
Show answer

Answer: (c) Main()

Q187. Every statement in C++ program should end with

  1. A full stop (.)
  2. A Comma (,)
  3. A Semicolon (;)
  4. A colon (:)
Show answer

Answer: (c) A Semicolon (;)

Q188. A variable is/are

  1. String that varies during program execution
  2. A portion of memory to store a value
  3. Those numbers that are frequently required in programs
  4. None of these
Show answer

Answer: (b) A portion of memory to store a value
Note: The source key marked 'numbers frequently required in programs' (that describes constants). A variable is a named portion of memory that stores a value.

Q189. The value of 2*15/3*7+3*2 is

  1. 146
  2. 76
  3. 8
  4. 70
Show answer

Answer: (b) 76

Q190. The size of a double variable is

  1. 2 bytes
  2. 4 bytes
  3. 8 bytes
  4. 10 bytes
Show answer

Answer: (c) 8 bytes

Q191. Which of the following can not be used as identifiers?

  1. Letters
  2. Digits
  3. Underscores
  4. Spaces
Show answer

Answer: (d) Spaces

Q192. Is the result of 'number = number / 10;' equal to the result of 'number = number % 10;'?

  1. True
  2. False
Show answer

Answer: (b) False

Q193. int x,y =10; cout << x << endl; The value of the x will be in the above code

  1. 0
  2. 10
  3. unknown Value
  4. -1
Show answer

Answer: (c) unknown Value

Q194. Which of the following is the boolean operator for logical-and?

  1. &
  2. &&
  3. |
  4. |&
Show answer

Answer: (b) &&

Q195. Evaluate !(1 && !(0 || 1)).

  1. TRUE
  2. FALSE
  3. Unevaluatable
  4. None Of The Above
Show answer

Answer: (a) TRUE

Q196. Which one of the following operators is a unary operator?

  1. OR ( || )
  2. AND ( && )
  3. XOR ( ^ )
  4. Logical NOT ( ! )
Show answer

Answer: (d) Logical NOT ( ! )

Q197. Which of the following shows the correct syntax for an if statement?

  1. if expression
  2. if{ expression
  3. if( expression)
  4. expression if
Show answer

Answer: (c) if( expression)

Q198. In if structure the block of statements is executed only,

  1. Type letters
  2. When it contain arithmetic operators
  3. When it contain logical operators
  4. When the condition is true
Show answer

Answer: (d) When the condition is true

Q199. Loader transfers the executable code from main memory to hard disk.

  1. TRUE
  2. FALSE
Show answer

Answer: (b) FALSE

Q200. What is the final value of x when the code int x; for(x=0; x < 10; x++) {} is run?

  1. 10
  2. 9
  3. 0
  4. 8
Show answer

Answer: (a) 10

Q201. When does the code block following while(x< 100) execute?

  1. When x is less than one hundred
  2. When x is greater than one hundred
  3. When x is equal to one hundred
  4. While it wishes
Show answer

Answer: (a) When x is less than one hundred
Note: The source key said 'greater than one hundred'. while(x<100) runs the block while x is less than 100.

Q202. Which is not a loop structure?

  1. For
  2. Do while
  3. While
  4. Repeat Until
Show answer

Answer: (d) Repeat Until

Q203. for (int n=10; n >0; n++) { cout << n << ", "; } How many Time Loop will run

  1. 100
  2. Infinite Time
  3. 1000
  4. 10000000
Show answer

Answer: (b) Infinite Time

Q204. When break statement is encountered in switch statement, it

  1. Stops the entire program
  2. Stops the execution of current statement
  3. Exits from switch statement
  4. None of the given options
Show answer

Answer: (c) Exits from switch statement

Q205. How many times is a do while loop guaranteed to loop?

  1. 0
  2. Variable
  3. Infinitely
  4. 1
Show answer

Answer: (d) 1

Q206. x = x + 4 ; Is Equal to

  1. x += 4 ;
  2. x =+ 4 ;
  3. x == 4 ;
  4. x =! 4 ;
Show answer

Answer: (a) x += 4 ;

Q207. The first expression in a for loop is

  1. The test expression.
  2. The step value of the loop.
  3. The first value of our counter variable.
  4. None of the above.
Show answer

Answer: (c) The first value of our counter variable.

Q208. What is the continue statement used for ?

  1. To continue to the next line of code.
  2. To stop the current iteration and begin the next iteration from the beginning.
  3. As an alternative to the else statement.
  4. None of the above.
Show answer

Answer: (b) To stop the current iteration and begin the next iteration from the beginning.

Q209. What is required to avoid falling through from one case to the next?

  1. end;
  2. break;
  3. Stop;
  4. A semicolon.
Show answer

Answer: (b) break;

Q210. What keyword covers unhandled possibilities in switch case?

  1. all
  2. contingency
  3. default
  4. other
Show answer

Answer: (c) default

Q211. What is the result of the following code? x=0; switch(x) { case 1: cout<< "One"; case 0: cout<< "Zero"; case 2: cout<< "Hello World"; }

  1. One
  2. Zero
  3. Hello World
  4. ZeroHello World
Show answer

Answer: (d) ZeroHello World

Q212. Which of the following is true?

  1. 1
  2. -1
  3. 0.1
  4. All of the above
Show answer

Answer: (d) All of the above
Note: All of the values 1, -1 and 0.1 are non-zero, so each is treated as true. The source key marked only '1'.

Q213. Every function in C++ are followed by

  1. Parameters
  2. Parenthesis
  3. Curly braces
  4. None of these
Show answer

Answer: (b) Parenthesis

Q214. Which is not a proper prototype?

  1. int funct(char x, char y);
  2. double funct(char x)
  3. void funct();
  4. char x();
Show answer

Answer: (b) double funct(char x)

Q215. What is the return type of the function with prototype: " int func(char x, float v, double t); "

  1. char
  2. int
  3. float
  4. double
Show answer

Answer: (b) int

Q216. Which of the following is a valid function call (assuming the function exists)?

  1. funct;
  2. funct x, y;
  3. funct();
  4. int funct();
Show answer

Answer: (c) funct();

Q217. Which of the following is a complete function?

  1. int funct();
  2. int funct(int x) {return x=x+1;}
  3. void funct(int) {cout&tl; < "Hello"}
  4. void funct(x) {cout << "Hello"}
Show answer

Answer: (b) int funct(int x) {return x=x+1;}

Q218. A function prototypes are useful

  1. Because they tell the compiler that a function is declared later.
  2. Because they make the program more readable.
  3. Because they allow the programmer to see a quick list of functions in the program along with the arguments for each function.
  4. All of the above.
Show answer

Answer: (d) All of the above.

Q219. A function that calls itself is known as

  1. Iterative function
  2. Inline function
  3. Recursive function
  4. main ()
Show answer

Answer: (c) Recursive function

Q220. A preprocessor directive is identified by symbol

  1. #
  2. {
  3. (
  4. ~
Show answer

Answer: (a) #

Q221. When a call to function statement is encountered,

  1. The control is transfer to its Prototype
  2. The control is transfer to its definition
  3. The compiler stop execution of whole program
  4. The program hangs
Show answer

Answer: (b) The control is transfer to its definition
Note: A call transfers control to the function's definition (its body), not to its prototype. The source key was wrong.

Q222. The directives for the preprocessors begin with

  1. Less than symbol (< )
  2. Ampersand symbol (&&#41;
  3. Two Slashes (//)
  4. Number Sign (#)
Show answer

Answer: (d) Number Sign (#)
Note: Preprocessor directives begin with the number sign (#). Two slashes start a comment. The source key was wrong.

Q223. The file iostream includes

  1. The declarations of the basic standard input-output library.
  2. The streams of includes and outputs of program effect.
  3. Both of these
  4. None of these
Show answer

Answer: (a) The declarations of the basic standard input-output library.

Q224. Which of the following is false?

  1. Cout represents the standard output stream in c++.
  2. Cout is declared in the iostream standard file
  3. Cout is declared within the std namespace
  4. None of above
Show answer

Answer: (d) None of above

Q225. If the statements int j,k; j = 123; k= 234; int* q, * r; cout<< *q<< ' '<< *r; are executed, what will be displayed?

  1. The addresses of q and r
  2. The addresses of j and k
  3. 132 , 234
  4. garbage values
Show answer

Answer: (d) garbage values

Q226. Which of the following correctly declares an array?

  1. int anarray[10];
  2. int anarray;
  3. anarray{10};
  4. array anarray[10];
Show answer

Answer: (a) int anarray[10];

Q227. Which of the following correctly accesses the seventh element stored in foo, an array with 100 elements?

  1. foo[6];
  2. foo[7];
  3. foo(7);
  4. foo;
Show answer

Answer: (a) foo[6];
Note: Indexing starts at 0, so the seventh element is foo[6]. The source key said foo[7].

Q228. Consider the following statement: int age [ ] = { 0, 2, 1, 3, 4, 5, 6, 7, 8, 9 }; Array Length is

  1. 10
  2. 11
  3. 9
  4. 0
Show answer

Answer: (a) 10

Q229. c[ 3 ] = 33; by this Code we are assigning the value to

  1. 3rd element
  2. 4th element
  3. 1st element
  4. None of the Given
Show answer

Answer: (b) 4th element

Q230. for (i = 0; i < 10 ; i ++) { b[i] = a[i]; } by given loop we are

  1. Deleting the two Arrays
  2. Comparing the two Arrays
  3. Copying the two arrays
  4. Doing Nothing
Show answer

Answer: (c) Copying the two arrays

Q231. int z, i ; int a [ 100 ] ; z=5; for ( i =0 ; i < 100 ; i ++ ) { a [ i ] = i ; } for ( i = 0 ; i < 100 ; i ++ ) { if ( z == a [ i ] ) { found = 1 ; break ; } } Loop will be executed for

  1. 6 Time
  2. 5 Time
  3. 4 Time
  4. 0 Time
Show answer

Answer: (a) 6 Time

Q232. Given that #define sum(a,b) a+b what is the value of: sum(3+1,2);

  1. 18
  2. 6
  3. 30
  4. 5*6
Show answer

Answer: (b) 6

Q233. Because of variable scope

  1. Variables created in a function cannot be used another function.
  2. Variables created in a function can be used in another function.
  3. Variables created in a function can only be used in the main function
  4. None of the above.
Show answer

Answer: (a) Variables created in a function cannot be used another function.

Q234. void allocateme(int* p){ p = new int; *p = 2; } int main(){ int i = 1; allocateme(&i); std::cout<< i; return 0; } What is displayed?

  1. Outputs '1'
  2. Outputs '2'
  3. Outputs some rubbish value
  4. Will not compile
Show answer

Answer: (a) Outputs '1'

Q235. int numarray[4][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; What value does numarray [0][3] in the sample code above contain?

  1. 3
  2. 5
  3. 7
  4. 4
Show answer

Answer: (d) 4

Q236. If the statements int j,k; j = 123; k= 234; int* q, * r; cout << *q << ' ' << * r ; are executed, what will be displayed?

  1. The values of j and k
  2. The addresses of q and r
  3. The addresses of j and k
  4. garbage values
Show answer

Answer: (d) garbage values

Q237. An array is also called

  1. an array variable
  2. array declaration
  3. struct
  4. constant pointer
Show answer

Answer: (d) constant pointer

Q238. Which of the following is the proper declaration of a pointer?

  1. int x;
  2. int &x;
  3. ptr x;
  4. int *x;
Show answer

Answer: (d) int *x;

Q239. Which of the following gives the memory address of integer variable a (int a;)?

  1. &a;
  2. *a;
  3. address(a);
  4. a;
Show answer

Answer: (a) &a;

Q240. Which of the following is the proper Operator to allocate memory?

  1. new
  2. malloc
  3. create
  4. value
Show answer

Answer: (a) new

Q241. Which of the following is the proper keyword to deallocate memory?

  1. free
  2. delete
  3. clear
  4. remove
Show answer

Answer: (b) delete

Q242. When we are calling function i.e. swap(&x, &y); then it is a call by

  1. Reference
  2. Value
  3. Name
  4. Nick Name
Show answer

Answer: (a) Reference

Q243. Which symbol is used to declare a pointer ?

  1. &
  2. @
  3. *
  4. $
Show answer

Answer: (c) *

Q244. In the given code int y[10]; int *x ; x= y; y is giving

  1. Address
  2. Whole Array Address
  3. Address of the first element of the array
  4. Error
Show answer

Answer: (c) Address of the first element of the array

Q245. Adding to a pointer that points to an array will

  1. Cause an error.
  2. Increase the value of the element that the pointer is pointing to.
  3. Cause the pointer to point to the next element in the array.
  4. None of the above.
Show answer

Answer: (c) Cause the pointer to point to the next element in the array.

Q246. Which one of the following operators is a unary operator?

  1. OR ( || )
  2. AND ( &&)
  3. XOR ( ^ )
  4. Complement operator ( ~ )
Show answer

Answer: (d) Complement operator ( ~ )

Q247. The statement i++; is equivalent to

  1. i = i + i;
  2. i = i + 1;
  3. i = i - 1;
  4. i --;
Show answer

Answer: (b) i = i + 1;

Q248. A variable which is defined inside a function is called

  1. Automatic variable
  2. Global variable
  3. Functional variable
  4. None of the given option
Show answer

Answer: (a) Automatic variable
Note: A variable defined inside a function is a local (automatic) variable. Global variables are defined outside every function. The source key was wrong.

Q249. Which of the following is a two-dimensional array?

  1. array anarray[20][20];
  2. int anarray[20][20];
  3. int array[20, 20];
  4. char array[20];
Show answer

Answer: (b) int anarray[20][20];

Q250. An array of pointers is the same as .

  1. pointers to pointers.
  2. pointers to Arrray
  3. null
  4. None of the Given
Show answer

Answer: (a) pointers to pointers.

Q251. Pointers may be like any other data type.

  1. char
  2. arrayed (stored in an array)
  3. int
  4. float
Show answer

Answer: (b) arrayed (stored in an array)

Q252. In C/C++ language when an array is passed to a function then by default its passing Mechanism is,

  1. Call by value
  2. It depends on type of array
  3. Call by Reference
  4. It depends on the return type of function.
Show answer

Answer: (c) Call by Reference

Q253. int isdigit( int c ) Returns true if c is a

  1. char
  2. int
  3. digit
  4. None of the Given
Show answer

Answer: (c) digit

Q254. int isupper( int c ) Returns true if c is a

  1. uppercase letter
  2. lowercase letter
  3. int
  4. float
Show answer

Answer: (a) uppercase letter

Q255. double atof( const char *nPtr ) Converts the string nPtr to

  1. double.
  2. int
  3. char
  4. float
Show answer

Answer: (a) double.

Q256. The basic steps of file handling are:

  1. Open the file, Read and write, Close the file
  2. Read, Close the file, Open the file
  3. Open the file, Close the file, write
  4. Non of the Given
Show answer

Answer: (a) Open the file, Read and write, Close the file

Q257. ofstream outFile; char outputFileName[] = "myFileOut.txt"; char ouputText[100] = "Welcome to VU"; outFile.open(outputFileName); at the end of the code

  1. file is opened for Writing
  2. file is opened for reading
  3. file is not opened
  4. file is closed
Show answer

Answer: (a) file is opened for Writing

Q258. If we open a file stream myfile for reading, what will give us the current position of the file pointer?

  1. tellg()
  2. tellp()
  3. seekg()
  4. seekp()
Show answer

Answer: (a) tellg()

Q259. Which of the following classes handlers file input?

  1. ofstream
  2. ifstream
  3. instream
  4. inputfile
Show answer

Answer: (b) ifstream

Q260. By writing: aFile. seekg (10L, ios::beg) We are asking to move 10 bytes

  1. back from the End
  2. forward from the begining
  3. forward from the Currant Position
  4. None of the above.
Show answer

Answer: (b) forward from the begining

Q261. we will call tellg () to give the current position in number. This number is the actual data bytes inside the file.

  1. int
  2. short
  3. long
  4. double
Show answer

Answer: (c) long

Q262. will return the number of bytes reserved for a variable or data type.

  1. sizeof operator
  2. free operator
  3. void pointer
  4. new operator
Show answer

Answer: (a) sizeof operator

Q263. A member is a

  1. Variable in a structure.
  2. Structure's datatype.
  3. Pointer to a structure.
  4. None of the above.
Show answer

Answer: (a) Variable in a structure.

Q264. Which of the following is a properly defined struct?

  1. struct {int a;}
  2. struct a_struct {int a;}
  3. struct a_struct int a;
  4. struct a_struct {int a;};
Show answer

Answer: (d) struct a_struct {int a;};

Q265. Using structures we can declare:

  1. Simple variables, Pointers and Arrays of structure
  2. Simple variables
  3. Pointers and Arrays of structure
  4. Nothing
Show answer

Answer: (a) Simple variables, Pointers and Arrays of structure

Q266. During compilation compiler looks for the and process it first

  1. source code
  2. object code
  3. built in functions
  4. preprocessor directives
Show answer

Answer: (d) preprocessor directives

Q267. Given a two-dimensional array of integers, what is the correct way of assigning the value 6 to the element at the third row and fourth column?

  1. array[2][3] = 6;
  2. array[3][4] = 6;
  3. array[2][4] = 6;
  4. array[4][3] = 6;
Show answer

Answer: (a) array[2][3] = 6;
Note: Indexes start at 0, so the third row is index 2 and the fourth column is index 3. The source marked array[3][4], which was wrong.

Q268. What is the purpose of the preprocessor directive #include <iostream.h> in the first C program?

  1. To define the main function
  2. To include a library for input-output streams
  3. To declare variables
  4. To link object code with libraries
Show answer

Answer: (b) To include a library for input-output streams

Q269. Why is the name "main" considered special in a C program?

  1. It is the only function allowed in a C program
  2. It is the last function executed in a C program
  3. It is the first function run when the program is used
  4. It is a reserved keyword
Show answer

Answer: (c) It is the first function run when the program is used

Q270. In C programming, what does the "cout" represent?

  1. Input stream
  2. Output stream
  3. Data type
  4. Main function
Show answer

Answer: (b) Output stream

Q271. What is the primary purpose of the "int" data type in C?

  1. To store whole numbers (integers)
  2. To store decimal numbers
  3. To store character values
  4. To declare variables
Show answer

Answer: (a) To store whole numbers (integers)

Q272. What does the statement "X = X + 1" achieve in C language?

  1. Subtraction operation
  2. Multiplication operation
  3. Division operation
  4. Incrementing the value of the variable by one
Show answer

Answer: (d) Incrementing the value of the variable by one

Q273. What is the purpose of the "iostream.h" file in C++?

  1. To declare variables
  2. To define the main function
  3. To include a library for input-output streams
  4. To link object code with libraries
Show answer

Answer: (c) To include a library for input-output streams

Q274. What does the curly bracket ({ }) signify in C programming?

  1. A syntax error
  2. The end of the program
  3. The beginning and end of a block of code
  4. A comment
Show answer

Answer: (c) The beginning and end of a block of code

Q275. Why is it recommended to avoid starting a variable name with an underscore (_) in C?

  1. Underscores are reserved keywords in C
  2. It may cause a syntax error
  3. It conflicts with library variable names
  4. Variables starting with underscores cannot be used in assignments
Show answer

Answer: (c) It conflicts with library variable names

Q276. What is the role of the linker in the compilation process?

  1. To process the code
  2. To create object code
  3. To link object code with libraries
  4. To put the program in memory
Show answer

Answer: (c) To link object code with libraries

Q277. Which part of the program is run first when a C program is executed?

  1. Linker
  2. Main function
  3. Preprocessor
  4. Compiler
Show answer

Answer: (b) Main function

Q278. What does the statement "cout << "Welcome to Virtual University of Pakistan";" do?

  1. Declares a variable named cout
  2. Prints the message to the screen using the cout stream
  3. Initializes the variable cout with a value
  4. Compares cout with a string
Show answer

Answer: (b) Prints the message to the screen using the cout stream

Q279. Why is it necessary to use the semicolon (;) at the end of C statements?

  1. It indicates the end of the program
  2. It is a syntax error if omitted
  3. It separates different blocks of code
  4. It increases the execution speed of the program
Show answer

Answer: (b) It is a syntax error if omitted

Q280. What is the function of the loader in C programming?

  1. To process the code
  2. To create object code
  3. To link object code with libraries
  4. To put the program in memory
Show answer

Answer: (d) To put the program in memory

Q281. What is the purpose of the "include" keyword in C programming?

  1. To define the main function
  2. To include external files or libraries
  3. To declare variables
  4. To link object code with libraries
Show answer

Answer: (b) To include external files or libraries

Q282. What is the purpose of the semicolon (;) in C programming?

  1. Signify the beginning of a statement
  2. Indicate the end of a statement
  3. Separate variables in a declaration
  4. Represent a mathematical operation
Show answer

Answer: (b) Indicate the end of a statement

Q283. What does the statement "z = x + y;" do in C programming?

  1. Assigns the value of x to z
  2. Adds the values of x and y and assigns the result to z
  3. Multiplies the values of x and y and assigns the result to z
  4. Compares the values of x and y and assigns the result to z
Show answer

Answer: (b) Adds the values of x and y and assigns the result to z

Q284. What is the purpose of the "short" data type in C?

  1. To store large whole numbers
  2. To store real numbers
  3. To store small whole numbers
  4. To store characters
Show answer

Answer: (c) To store small whole numbers

Q285. How many bytes does the "short" data type occupy in memory?

  1. 1 byte
  2. 2 bytes
  3. 4 bytes
  4. 8 bytes
Show answer

Answer: (b) 2 bytes

Q286. When dealing with very large whole numbers in C, which data type is recommended?

  1. int
  2. short
  3. long
  4. double
Show answer

Answer: (c) long

Q287. What does the modulus operator (%) do in C arithmetic operations?

  1. Adds two numbers
  2. Multiplies two numbers
  3. Returns the remainder after division
  4. Divides two numbers and returns the quotient
Show answer

Answer: (c) Returns the remainder after division

Q288. How is the result of 10 + 10 * 5 evaluated in C?

  1. 60
  2. 100
  3. 50
  4. 25
Show answer

Answer: (a) 60

Q289. What is the purpose of using parentheses in C arithmetic expressions?

  1. They are used for multiplication
  2. They force the evaluation order
  3. They indicate the end of a statement
  4. They are used for addition
Show answer

Answer: (b) They force the evaluation order

Q290. Why is float data type recommended for correct results in division?

  1. It uses less memory
  2. It can store larger values
  3. It avoids truncating the result in integer division
  4. It is faster in computation
Show answer

Answer: (c) It avoids truncating the result in integer division

Q291. How many bytes does the float data type use in C to store a real number?

  1. 1 byte
  2. 2 bytes
  3. 4 bytes
  4. 8 bytes
Show answer

Answer: (c) 4 bytes

Q292. What is the role of the cout statement when displaying a character in C?

  1. Displays the character name
  2. Displays the character value
  3. Prints the ASCII code of the character
  4. Converts the character to an integer before display
Show answer

Answer: (b) Displays the character value

Q293. In C programming, what happens if there are nested parentheses in an expression?

  1. The innermost parentheses are ignored
  2. The outermost parentheses are evaluated first
  3. The expression is invalid
  4. The innermost parentheses are evaluated first
Show answer

Answer: (d) The innermost parentheses are evaluated first

Q294. What does the modulus operator (%) return in C?

  1. Sum of two numbers
  2. Product of two numbers
  3. Quotient after division
  4. Remainder after division
Show answer

Answer: (d) Remainder after division

Q295. What should be used to force the evaluation order in C arithmetic expressions?

  1. Semicolon (;)
  2. Parentheses ( )
  3. Comma (,)
  4. Quotation marks (" ")
Show answer

Answer: (b) Parentheses ( )

Q296. What is mentioned as a disadvantage of using multiple if statements in a program?

  1. Increased readability
  2. Improved efficiency
  3. Computationally expensive
  4. Simplicity in code structure
Show answer

Answer: (c) Computationally expensive

Q297. What is the alternative to using multiple if statements to handle multi-way decisions efficiently?

  1. Nested loops
  2. Switch statement
  3. Compound conditions
  4. Function calls
Show answer

Answer: (b) Switch statement

Q298. Why is the use of nested if/else statements considered more efficient than using multiple if statements?

  1. It requires fewer lines of code
  2. It reduces the need for indentation
  3. It avoids unnecessary computation
  4. It allows compound conditions
Show answer

Answer: (c) It avoids unnecessary computation

Q299. In the switch statement, what is required for the variable or expression inside the parentheses?

  1. It must be a float
  2. It must be a char or int
  3. It must be a string
  4. It must be a double
Show answer

Answer: (b) It must be a char or int

Q300. How does the switch statement handle cases when there is no match with any of the specified constants?

  1. It executes the default statements
  2. It terminates the program
  3. It throws an error
  4. It continues to the next case
Show answer

Answer: (a) It executes the default statements

Q301. What is the purpose of the default statement in a switch structure?

  1. To provide a fallback option
  2. To handle unexpected errors
  3. To terminate the program
  4. To improve code efficiency
Show answer

Answer: (a) To provide a fallback option

Q302. What happens when a true case is found in a switch statement without using the break statement?

  1. It executes all statements below the true case
  2. It terminates the switch statement
  3. It ignores the true case and moves to the next one
  4. It throws an error
Show answer

Answer: (a) It executes all statements below the true case

Q303. How does the break statement affect the flow of control in a switch structure?

  1. It continues to the next case
  2. It jumps out of the switch statement
  3. It starts executing statements from the beginning
  4. It skips the current case and moves to the next
Show answer

Answer: (b) It jumps out of the switch statement

Q304. In the context of loops, where can the break statement be used to terminate the loop?

  1. Before the loop condition
  2. After the loop condition
  3. Inside the loop body
  4. Outside the loop body
Show answer

Answer: (c) Inside the loop body

Q305. How does the switch statement handle non-integer constants in case statements?

  1. It converts them to integers
  2. It throws an error
  3. It ignores them
  4. It treats them as strings
Show answer

Answer: (b) It throws an error

Q306. What is the key advantage of using the switch structure over multiple if statements?

  1. Improved readability
  2. Enhanced flexibility
  3. Increased computational cost
  4. Better efficiency
Show answer

Answer: (d) Better efficiency

Q307. In the switch statement, what does the default case handle?

  1. Error handling
  2. Program termination
  3. Execution when no case matches
  4. Common statements for all cases
Show answer

Answer: (c) Execution when no case matches

Q308. What is the primary drawback mentioned when using 'if statements' extensively in a program?

  1. Decreased computational cost
  2. Enhanced program performance
  3. Increased code efficiency
  4. Computationally expensive
Show answer

Answer: (d) Computationally expensive

Q309. What is the purpose of using braces { } in an if statement in C programming?

  1. To separate conditions
  2. To indicate the end of the if statement
  3. To create a block of statements to be executed if the condition is true
  4. To increase indentation for better style
Show answer

Answer: (c) To create a block of statements to be executed if the condition is true

Q310. What is the significance of indentation in C programming?

  1. It affects the logic of the program
  2. It is mandatory for correct syntax
  3. It improves program execution speed
  4. It makes the code easy to read and understand the structure
Show answer

Answer: (d) It makes the code easy to read and understand the structure

Q311. In C programming, what is the purpose of the '==' operator?

  1. Assignment
  2. Greater than or equal to
  3. Equal to
  4. Less than or equal to
Show answer

Answer: (c) Equal to

Q312. What is the primary role of flow charts in program design?

  1. Execute program instructions
  2. Visual representation of program logic
  3. Identify syntax errors
  4. Declare variables
Show answer

Answer: (b) Visual representation of program logic

Q313. What is the purpose of initializing variables in C programming?

  1. To declare the type of the variable
  2. To assign a value to a variable
  3. To improve program performance
  4. To create logical errors
Show answer

Answer: (b) To assign a value to a variable

Q314. In the given C programming example, what does the condition 'if ( AmerAge > AmaraAge)' check?

  1. Whether Amer's age is less than Amara's
  2. Whether Amer's age is equal to Amara's
  3. Whether Amer's age is greater than Amara's
  4. Whether Amer's age is not equal to Amara's
Show answer

Answer: (c) Whether Amer's age is greater than Amara's

Q315. What is the role of the assignment operator '=' in C programming?

  1. Comparison of values
  2. Declaration of variables
  3. Execution of statements
  4. Assigning a value to a variable
Show answer

Answer: (d) Assigning a value to a variable

Q316. What is the purpose of relational operators in C programming?

  1. To perform arithmetic operations
  2. To compare values and make decisions
  3. To declare variables
  4. To create logical errors
Show answer

Answer: (b) To compare values and make decisions

Q317. What does the flow chart symbolize in program design?

  1. Actual code execution
  2. Visual representation of a program's sequence
  3. Debugging process
  4. Compilation process
Show answer

Answer: (b) Visual representation of a program's sequence

Q318. Why is the indentation of lines in C programming considered a matter of style and not affecting program logic?

  1. It improves program performance
  2. It indicates syntax errors
  3. It is a matter of compiler preference
  4. It only affects code readability, not logic
Show answer

Answer: (d) It only affects code readability, not logic

Q319. What is the primary purpose of using comments in a C program?

  1. Improve program execution speed
  2. Explain the purpose of code blocks
  3. Declare variables
  4. Identify syntax errors
Show answer

Answer: (b) Explain the purpose of code blocks

Q320. What is the role of the '!=' operator in C programming?

  1. Comparison of values
  2. Logical NOT operation
  3. Equality check
  4. Not equal to check
Show answer

Answer: (d) Not equal to check

Q321. Why is it important to use relational operators while making decisions in C programming?

  1. They improve program performance
  2. They eliminate logical errors
  3. They are mandatory for correct syntax
  4. They allow the program to compare values and make decisions
Show answer

Answer: (d) They allow the program to compare values and make decisions

Q322. What is the consequence of writing 'if ( x = 2 )' in C programming?

  1. Syntax error
  2. Logical error
  3. No error
  4. Compiler warning
Show answer

Answer: (b) Logical error

Q323. What is the purpose of the if/else structure in programming?

  1. To execute a block of statements when a condition is true
  2. To execute a block of statements when a condition is false
  3. To execute different blocks of statements based on whether a condition is true or false
  4. To skip the execution of statements when a condition is false
Show answer

Answer: (c) To execute different blocks of statements based on whether a condition is true or false

Q324. According to the logical operators section, what does the && operator do?

  1. Combines conditions with OR
  2. Combines conditions with AND
  3. Negates a condition
  4. Reverses the meaning of a condition
Show answer

Answer: (b) Combines conditions with AND

Q325. How are logical operators AND (&&) and OR (||) used in programming?

  1. They are unary operators
  2. They are binary operators
  3. They work with numeric values
  4. They are used for looping
Show answer

Answer: (b) They are binary operators

Q326. In the truth table for the && operator, what is the result when both Expression 1 and Expression 2 are true?

  1. False
  2. True
  3. True only if Expression 1 is true
  4. False only if Expression 1 is false
Show answer

Answer: (b) True

Q327. What is the purpose of the logical negation operator (!)?

  1. To combine conditions with AND
  2. To reverse the meaning of a condition
  3. To create a truth table
  4. To check for equality
Show answer

Answer: (b) To reverse the meaning of a condition

Q328. What is the purpose of the else part in the if/else structure?

  1. To execute when the condition in the if statement is true
  2. To execute when the condition in the if statement is false
  3. To combine conditions with AND
  4. To create a truth table
Show answer

Answer: (b) To execute when the condition in the if statement is false

Q329. How are logical operators used in decision-making in programming?

  1. They are used to declare variables
  2. They are used to calculate values
  3. They are used to combine conditions for decision-making
  4. They are used to create loops
Show answer

Answer: (c) They are used to combine conditions for decision-making

Q330. How does the logical negation operator (!) affect a false condition?

  1. It remains false
  2. It becomes true
  3. It is not affected
  4. It depends on the other conditions in the expression
Show answer

Answer: (b) It becomes true

Q331. What is the definition of programming?

  1. A set of random activities
  2. A sequence of steps to solve a particular problem
  3. A creative expression of abstract ideas
  4. A mechanism for computer communication
Show answer

Answer: (b) A sequence of steps to solve a particular problem

Q332. According to Alan Perlis, what is his sarcastic statement about modern education?

  1. Programming is a boring activity
  2. Modern education teaches critical skills effectively
  3. Making plans and organizing thoughts are unnecessary skills
  4. Programming develops essential skills for everyone
Show answer

Answer: (c) Making plans and organizing thoughts are unnecessary skills

Q333. How does Mr. Steve Summit define programming at its most basic level?

  1. A complex set of instructions
  2. Telling the computer what to do
  3. Creating artificial mechanisms
  4. Solving a problem with natural language
Show answer

Answer: (b) Telling the computer what to do

Q334. Why does Matthias Felleisen argue that learning to program is important?

  1. To automate tasks effectively
  2. To use application software efficiently
  3. Develops analytical and problem-solving abilities
  4. Traditional programming is useful for everyone
Show answer

Answer: (c) Develops analytical and problem-solving abilities

Q335. Why is commenting code liberally recommended in programming?

  1. It improves program performance
  2. It adds unnecessary complexity
  3. Comments help explain the code without affecting performance
  4. Comments take up valuable memory space
Show answer

Answer: (c) Comments help explain the code without affecting performance

Q336. What is the comparison made between learning to design programs and playing soccer?

  1. Both involve physical activity
  2. Learning soccer is more complex
  3. Designing programs is not a creative process
  4. Both require learning basic skills before creativity
Show answer

Answer: (d) Both require learning basic skills before creativity

Q337. What is the emphasis on testing and checking in program evaluation?

  1. It is unnecessary
  2. It should be done only once
  3. It is crucial to refining the program
  4. It is only for large programs
Show answer

Answer: (c) It is crucial to refining the program

Q338. What is the problem statement in the sample program?

  1. Calculate the total age of ten students
  2. Sort out the ages of ten students
  3. Calculate the average age of a class of ten students
  4. Prompt the user to enter the age of each student
Show answer

Answer: (c) Calculate the average age of a class of ten students

Q339. Which data type is used for the variables "age1, age2, ..., age10"?

  1. double
  2. float
  3. int
  4. char
Show answer

Answer: (c) int

Q340. Why is the data type of "AverageAge" declared as int?

  1. To store only whole numbers
  2. To store real numbers with decimal points
  3. To allow the use of expressions in calculations
  4. To ensure accurate calculations
Show answer

Answer: (a) To store only whole numbers

Q341. What is the purpose of the "cin" statement in the program?

  1. Display the average age
  2. Take input from the user
  3. Sort the ages of students
  4. Calculate the total age
Show answer

Answer: (b) Take input from the user

Q342. What is the significance of the statement "TotalAge = age1 + age2 + ... + age10;"?

  1. Calculate the average age
  2. Display the total age
  3. Sort the ages of students
  4. Calculate the sum of ages
Show answer

Answer: (d) Calculate the sum of ages

Q343. What is the purpose of the "cout" statement at the end of the program?

  1. Display the average age
  2. Display the total age
  3. Sort the ages of students
  4. Prompt the user to enter the age of each student
Show answer

Answer: (a) Display the average age

Q344. What is the purpose of parentheses in expressions in C?

  1. They are optional and can be omitted
  2. They force the order of evaluation
  3. They are used for multiplication
  4. They indicate the power operator
Show answer

Answer: (b) They force the order of evaluation

Q345. What does the expression "x = a * (x + b * (y + c * z * z))" represent?

  1. Quadratic equation
  2. Cubic equation
  3. Nested expression
  4. Linear equation
Show answer

Answer: (c) Nested expression

Q346. What is the significance of the "main()" function in the program?

  1. It displays the average age
  2. It sorts the ages of students
  3. It calculates the total age
  4. It is the starting point of the program
Show answer

Answer: (d) It is the starting point of the program

Q347. Why is the "cout" statement used in the program?

  1. To take input from the user
  2. To declare variables
  3. To display output to the user
  4. To calculate the average age
Show answer

Answer: (c) To display output to the user

Q348. How many students' ages are taken as input in the program?

  1. 5
  2. 8
  3. 10
  4. 12
Show answer

Answer: (c) 10

Q349. What is the purpose of the "TotalAge" variable in the program?

  1. To store the average age
  2. To store the total age
  3. To display the result
  4. To prompt the user
Show answer

Answer: (b) To store the total age

Q350. What are the basic constructs of programming mentioned in the paragraph?

  1. Functions
  2. Sequence, decision making, and loops
  3. Declaration and Definition
  4. Tips
Show answer

Answer: (b) Sequence, decision making, and loops

Q351. What is the concept of functional design or top-down designing based on?

  1. Divide and conquer
  2. Decision making
  3. Sequence
  4. Loops
Show answer

Answer: (a) Divide and conquer

Q352. In top-down designing, what do we do when breaking up a task into smaller subtasks?

  1. Keep refining until the task becomes complex
  2. Stop at a reasonable level
  3. Use a goto statement
  4. Minimize the use of break and continue statements
Show answer

Answer: (b) Stop at a reasonable level

Q353. What is the specific function-calling methodology mentioned in the paragraph?

  1. Functions are called randomly
  2. Functions are invoked through a calling program
  3. Functions are called only by main ( )
  4. Functions are called by using a goto statement
Show answer

Answer: (b) Functions are invoked through a calling program

Q354. How many categories of functions are mentioned in the paragraph?

  1. Three
  2. One
  3. Two
  4. Four
Show answer

Answer: (c) Two

Q355. What is the return value type of a function that does not return any value?

  1. int
  2. float
  3. void
  4. char
Show answer

Answer: (c) void

Q356. What keyword is used to return some value from a function?

  1. return-value-type
  2. data type
  3. keyword
  4. return
Show answer

Answer: (d) return

Q357. What does the argument-list of a function contain?

  1. Information passed to the function
  2. Declarations and statements
  3. Valid data types like int number, double radius
  4. Body of the function
Show answer

Answer: (a) Information passed to the function

Q358. What is the default return_value_type if not mentioned for a function?

  1. float
  2. int
  3. void
  4. char
Show answer

Answer: (b) int

Q359. What is the body of the function composed of?

  1. Return-value-type
  2. Function-name
  3. Declarations and statements
  4. Argument-list
Show answer

Answer: (c) Declarations and statements

Q360. What is the keyword of the 'C' language for functions that do not return any value?

  1. return
  2. void
  3. data type
  4. function
Show answer

Answer: (b) void

Q361. How is the structure of a function declared in terms of syntax?

  1. function-name return-value-type ( argument-list )
  2. return-value-type function-name { declarations and statements }
  3. argument-list return-value-type function-name { declarations and statements }
  4. return-value-type function-name
Show answer

Answer: (b) return-value-type function-name { declarations and statements }

Q362. What does the top-down designing mechanism rely on?

  1. Sequence
  2. Decision making
  3. Loops
  4. Divide and conquer
Show answer

Answer: (d) Divide and conquer

Q363. What does the return statement in a function do?

  1. Exits from the program
  2. Exits from the function
  3. Returns some value to the calling program and exits from the function
  4. Minimizes the use of break and continue statements
Show answer

Answer: (c) Returns some value to the calling program and exits from the function

Q364. What is the recommended practice regarding reusing variable names at different scopes?

  1. Encouraged for better understanding
  2. Discouraged due to potential confusion
  3. Only allowed for global variables
  4. Mandatory for nested functions
Show answer

Answer: (b) Discouraged due to potential confusion

Q365. What does the term 'file scope variable' or 'global variable' refer to?

  1. A variable accessible only within a function
  2. A variable accessible within a single code block
  3. A variable accessible throughout the entire file
  4. A variable accessible across multiple files
Show answer

Answer: (c) A variable accessible throughout the entire file

Q366. What is the downside of using global variables, according to the paragraph?

  1. Limited accessibility
  2. Increased program logic
  3. Potential unintentional changes
  4. Improved encapsulation
Show answer

Answer: (c) Potential unintentional changes

Q367. What is the keyword used to declare a global variable in C?

  1. local
  2. global
  3. file
  4. extern
Show answer

Answer: (d) extern

Q368. What does the 'void' keyword indicate in a function declaration?

  1. No parameters
  2. No return value
  3. Both a and b
  4. A function prototype
Show answer

Answer: (c) Both a and b

Q369. What is the default function calling mechanism in C, according to the paragraph?

  1. Call by Name
  2. Call by Value
  3. Call by Reference
  4. Call by Pointer
Show answer

Answer: (b) Call by Value

Q370. What analogy is used to explain 'Call by Value' in the paragraph?

  1. Copying a letter for rectification
  2. Making corrections in the original letter
  3. Deputing somebody to make corrections
  4. None of the above
Show answer

Answer: (a) Copying a letter for rectification

Q371. When is 'Call by Reference' used in C?

  1. By default in all functions
  2. When we want to pass a copy of variables
  3. When we want the actual variable to be changed by the function
  4. Only in main() function
Show answer

Answer: (c) When we want the actual variable to be changed by the function

Q372. What does the transpose of a matrix involve?

  1. Swapping rows and columns.
  2. Reversing the matrix order.
  3. Interchanging odd and even elements.
  4. Doubling each element in the matrix.
Show answer

Answer: (a) Swapping rows and columns.

Q373. Why is a swapping mechanism needed when interchanging values in the transpose process?

  1. To speed up the program.
  2. To avoid losing information.
  3. To reverse the matrix.
  4. To perform diagonal swaps.
Show answer

Answer: (b) To avoid losing information.

Q374. What happens to the diagonal elements during matrix transposition?

  1. They are multiplied.
  2. They remain unchanged.
  3. They are swapped twice.
  4. They become zeros.
Show answer

Answer: (b) They remain unchanged.

Q375. What is the role of the temp variable in the transposeMatrix function?

  1. Stores the transposed matrix.
  2. Holds the original matrix values during swapping.
  3. Multiplies elements during transposition.
  4. Controls the loop iterations.
Show answer

Answer: (b) Holds the original matrix values during swapping.

Q376. What is the significance of the diagonal elements in matrix transposition?

  1. They are ignored.
  2. They are multiplied.
  3. They are swapped twice.
  4. They remain unchanged.
Show answer

Answer: (d) They remain unchanged.

Q377. Why are arrays considered a possible solution to the problem of storing the ages of multiple students?

  1. They occupy less memory.
  2. They require fewer variables.
  3. They allow storing data of the same type.
  4. They automatically calculate averages.
Show answer

Answer: (c) They allow storing data of the same type.

Q378. In C language, what does the index of an array start from?

  1. 1
  2. 2
  3. 0
  4. The size of the array
Show answer

Answer: (c) 0

Q379. What does the size of an array in C represent?

  1. Memory occupied by the array
  2. Number of elements in the array
  3. Total number of arrays
  4. Size of each element in the array
Show answer

Answer: (b) Number of elements in the array

Q380. In the memory image of an array, what does "C[6]" represent?

  1. The seventh element
  2. The sixth element
  3. The fifth element
  4. The eighth element
Show answer

Answer: (a) The seventh element

Q381. What is the significance of the value inside the square brackets when accessing an array element?

  1. Element's address
  2. Element's value
  3. Element's index
  4. Element's size
Show answer

Answer: (c) Element's index

Q382. How is the index of the last element of an array related to the size of the array?

  1. Equal to the size of the array
  2. One more than the size of the array
  3. One less than the size of the array
  4. Double the size of the array
Show answer

Answer: (c) One less than the size of the array

Q383. How is the total age calculated using a 'for loop'?

  1. Subtracting each element from the totalAge
  2. Multiplying each element with the totalAge
  3. Adding each element to the totalAge
  4. Dividing each element by the totalAge
Show answer

Answer: (c) Adding each element to the totalAge

Q384. Why is it advised not to use the default initialization of arrays?

  1. It leads to a compilation error.
  2. It may assign random values to the array.
  3. It increases memory consumption.
  4. It prevents the array from being accessed.
Show answer

Answer: (b) It may assign random values to the array.

Q385. In the given example, what does "age[5]" represent?

  1. The sixth element of the array
  2. The fifth element of the array
  3. The fourth element of the array
  4. The second element of the array
Show answer

Answer: (a) The sixth element of the array
Note: Indexes start at 0, so age[5] is the sixth element. The source key said fifth.

Q386. What is the maximum value returned by the rand() function?

  1. 32767
  2. 32768
  3. 65535
  4. 65536
Show answer

Answer: (a) 32767
Note: RAND_MAX is 32767 on the compiler used in the course (compiler-dependent).

Q387. How can we limit the generated random number in a smaller range, such as between 1 and 6 inclusive?

  1. x = rand() % 6
  2. x = 1 + rand() % 6
  3. x = rand() % 5
  4. x = 1 + rand() % 5
Show answer

Answer: (b) x = 1 + rand() % 6

Q388. What is the result of the statement rand() % 6?

  1. Between 0 and 5
  2. Between 1 and 6
  3. Between 0 and 6
  4. Between 1 and 5
Show answer

Answer: (a) Between 0 and 5

Q389. What does the keyword 'const' do in the statement "const int arraySize = 100;"?

  1. Declares an array named arraySize
  2. Declares a constant integer named arraySize
  3. Initializes an array with size 100
  4. Generates a random number with value 100
Show answer

Answer: (b) Declares a constant integer named arraySize

Q390. What is the ASCII code of the null character in C language?

  1. 0
  2. 1
  3. 32
  4. 127
Show answer

Answer: (a) 0

Q391. What does the statement "cin >> name;" do?

  1. Reads a single character
  2. Reads a string until the space
  3. Reads a string until the enter key is pressed
  4. Reads a number from the user
Show answer

Answer: (b) Reads a string until the space
Note: cin >> reads only up to the first whitespace; to read a whole line use cin.getline(). The source key said 'until the enter key'.

Q392. What is the size of the declared character array "char name[100];"?

  1. 50
  2. 100
  3. 101
  4. 99
Show answer

Answer: (b) 100

Q393. Why is 'Call by Reference' used in C?

  1. To avoid side-effects
  2. To change the value of the original variable
  3. To simplify function calls
  4. To speed up program execution
Show answer

Answer: (b) To change the value of the original variable

Q394. What does the '&' operator in C language do when applied to a variable?

  1. Multiplies the variable by itself
  2. Gets the value of the variable
  3. Returns the address of the variable
  4. Divides the variable by itself
Show answer

Answer: (c) Returns the address of the variable

Q395. In the provided square(double*) function, what does *x represent?

  1. The square of x
  2. The address of x
  3. Whatever x points to
  4. The memory location of x
Show answer

Answer: (c) Whatever x points to

Q396. What is the risk associated with using recursive functions in C?

  1. Increased efficiency
  2. Memory overhead
  3. Faster execution
  4. Limited functionality
Show answer

Answer: (b) Memory overhead

Q397. What is the significance of the #include <iostream.h> statement in the provided code?

  1. It defines the main function
  2. It includes the input/output stream library
  3. It declares constants
  4. It is irrelevant to the program
Show answer

Answer: (b) It includes the input/output stream library

Q398. Why is 'Call by Reference' considered risky in C?

  1. It causes syntax errors
  2. It slows down program execution
  3. It may lead to side-effects
  4. It is not supported in C
Show answer

Answer: (c) It may lead to side-effects

Q399. In the statement (*yptr) ++, what does it do?

  1. Increments the pointer yptr
  2. Increments the value where yptr points
  3. Decrements the pointer yptr
  4. Decrements the value where yptr points
Show answer

Answer: (b) Increments the value where yptr points

Q400. What happens when yptr is incremented by 1?

  1. It increments the pointer to the next element in the memory
  2. It increments the value where the pointer points
  3. It decrements the pointer to the previous element in the memory
  4. It decrements the value where the pointer points
Show answer

Answer: (a) It increments the pointer to the next element in the memory

Q401. How is the memory address changed when a pointer to an integer is incremented?

  1. By one byte
  2. By two bytes
  3. By four bytes
  4. By eight bytes
Show answer

Answer: (c) By four bytes

Q402. What is the result of subtracting two pointers pointing to the same memory address?

  1. Zero
  2. One
  3. The difference in bytes between the two addresses
  4. The sum of the two addresses
Show answer

Answer: (a) Zero

Q403. What information can be obtained by subtracting two pointers?

  1. The sum of the two addresses
  2. The difference in bytes between the two addresses
  3. The product of the two addresses
  4. The quotient of the two addresses
Show answer

Answer: (b) The difference in bytes between the two addresses

Q404. What is the result of comparing *yptr1 and *yptr2?

  1. It compares the addresses of yptr1 and yptr2
  2. It compares the values pointed to by yptr1 and yptr2
  3. It compares the sizes of yptr1 and yptr2
  4. It compares the types of yptr1 and yptr2
Show answer

Answer: (b) It compares the values pointed to by yptr1 and yptr2

Q405. What does the statement (*yptr) --; do?

  1. Decrements the pointer yptr
  2. Decrements the value where yptr points
  3. Increments the pointer yptr
  4. Increments the value where yptr points
Show answer

Answer: (b) Decrements the value where yptr points

Q406. How is pointer arithmetic affected by the data type it points to?

  1. It is not affected by the data type
  2. It changes the address by the number of bytes occupied by the data type
  3. It changes the address by a fixed amount regardless of the data type
  4. It increments the address by one byte for all data types
Show answer

Answer: (b) It changes the address by the number of bytes occupied by the data type

Q407. How is pointer subtraction useful, according to the paragraph?

  1. It allows us to find the sum of two addresses
  2. It allows us to find the difference in bytes between two addresses
  3. It allows us to find the product of two addresses
  4. It allows us to find the quotient of two addresses
Show answer

Answer: (b) It allows us to find the difference in bytes between two addresses

Q408. What does the statement *yptr += 3; do?

  1. Increments the pointer yptr by 3
  2. Decrements the pointer yptr by 3
  3. Increments the value where yptr points by 3
  4. Decrements the value where yptr points by 3
Show answer

Answer: (c) Increments the value where yptr points by 3

Q409. What problem does the Linear Search example aim to solve?

  1. Calculating the average of an array
  2. Finding a specific number in an array
  3. Sorting the elements of an array
  4. Reversing the order of an array
Show answer

Answer: (b) Finding a specific number in an array

Q410. What is the purpose of the flag variable in the Linear Search example?

  1. To indicate the end of the loop
  2. To determine the size of the array
  3. To check if the number has been found
  4. To control the loop iterations
Show answer

Answer: (c) To check if the number has been found

Q411. Why is a loop used in the array copying example instead of individual assignment statements?

  1. To demonstrate the use of loops
  2. To simplify the code for larger arrays
  3. To prevent copying of array elements
  4. To introduce a delay in the execution
Show answer

Answer: (b) To simplify the code for larger arrays

Q412. What information does a function accepting a two-dimensional array as an argument need to know?

  1. Only the number of rows
  2. Only the number of columns
  3. Both the number of rows and columns
  4. The size of the array
Show answer

Answer: (b) Only the number of columns

Q413. What is the purpose of using an array of pointers for storing variable- length character strings?

  1. To waste space
  2. To allocate fixed space for rows
  3. To minimize space wastage and accommodate variable lengths
  4. To simplify array manipulation
Show answer

Answer: (c) To minimize space wastage and accommodate variable lengths

Q414. What are the four basic data types mentioned in the paragraph?

  1. char, int, float, string
  2. char, int, float, double
  3. string, int, float, double
  4. char, integer, float, double
Show answer

Answer: (b) char, int, float, double

Q415. Why is a character array used to store a word or name like "Amir"?

  1. char variables can store multiple characters
  2. char variables can store only one character
  3. char variables automatically append null character
  4. char variables support escape characters
Show answer

Answer: (b) char variables can store only one character

Q416. What is the benefit of having a null character at the end of a string?

  1. It increases the size of the array
  2. It indicates the end of the string
  3. It allows using multiple characters in single quotes
  4. It prevents syntax errors
Show answer

Answer: (b) It indicates the end of the string

Q417. Why is the null character important when using cout to print a character array?

  1. It increases the efficiency of printing
  2. It is a syntax requirement
  3. cout uses it as the string terminating point
  4. It avoids using escape characters
Show answer

Answer: (c) cout uses it as the string terminating point

Q418. Why is the null character explicitly assigned to the destination array in the array copying program?

  1. To increase the size of the destination array
  2. To terminate the loop condition
  3. To indicate the end of the string in the destination array
  4. To avoid syntax errors
Show answer

Answer: (c) To indicate the end of the string in the destination array

Q419. What is the prototype of the myStringCopy function?

  1. void myStringCopy (char *source, const char *destination);
  2. void myStringCopy (const char *destination, char *source);
  3. void myStringCopy (char *destination, const char *source);
  4. void myStringCopy (int *destination, const int *source);
Show answer

Answer: (c) void myStringCopy (char *destination, const char *source);

Q420. Why is the keyword 'const' used with the second argument of the myStringCopy function?

  1. To make the function read-only
  2. To allow changes to the source array
  3. To indicate constant size
  4. To increase efficiency
Show answer

Answer: (a) To make the function read-only

Q421. What does the myStringCopy function do?

  1. Copies integers from one array to another
  2. Copies characters from one array to another
  3. Increments the array pointer
  4. Prints the address and value of a character pointer
Show answer

Answer: (b) Copies characters from one array to another

Q422. What is automatically passed when arrays are used as function arguments?

  1. Copies of the array elements
  2. Reference to the original array
  3. A null character
  4. Size of the array
Show answer

Answer: (b) Reference to the original array

Q423. What does the array name become when an array is created?

  1. Constant pointer
  2. Variable pointer
  3. Double pointer
  4. Null pointer
Show answer

Answer: (a) Constant pointer

Q424. What is the purpose of the statement char * myNamePtr = "Full Name";?

  1. It creates a char array named myName
  2. It initializes a char pointer with the address of "Full Name"
  3. It declares a constant pointer to a char array
  4. It defines a char array with the content "Full Name"
Show answer

Answer: (b) It initializes a char pointer with the address of "Full Name"

Q425. In the statement char myName[] = "Full Name";, what is myName?

  1. Constant pointer
  2. Variable pointer
  3. Char array
  4. Null character
Show answer

Answer: (c) Char array

Q426. What does the keyword 'const' do when used with pointers?

  1. Increases efficiency
  2. Allows changes to the pointer
  3. Makes the pointer read-only
  4. Terminates the loop
Show answer

Answer: (c) Makes the pointer read-only

Q427. What is the purpose of the dereferencing operator (*) in C programming?

  1. Multiplication
  2. Memory allocation
  3. Getting the value stored at a memory address
  4. Division
Show answer

Answer: (c) Getting the value stored at a memory address

Q428. What is the significance of initializing a pointer in C programming?

  1. Enhances program speed
  2. Avoids runtime errors
  3. Allows for dynamic memory allocation
  4. Enables proper referencing in expressions
Show answer

Answer: (b) Avoids runtime errors

Q429. How can a pointer be initialized in C?

  1. ptr = &x;
  2. ptr = 0;
  3. ptr = NULL;
  4. All of the above
Show answer

Answer: (d) All of the above

Q430. In C, what does a null pointer indicate?

  1. It points to an undefined memory location.
  2. It points to the beginning of the memory.
  3. It points to nothing.
  4. It points to the end of the memory.
Show answer

Answer: (c) It points to nothing.

Q431. Can the address operator (&) be used with an expression in C?

  1. Yes
  2. No
  3. Only with simple variables
  4. Only with pointers
Show answer

Answer: (b) No

Q432. What is the primary purpose of using pointers in C with function calls?

  1. Improve program speed
  2. Simulate call by reference
  3. Enable dynamic memory allocation
  4. Simplify function declarations
Show answer

Answer: (b) Simulate call by reference

Q433. Why does a function call to swap(x, y) in C not swap the values of x and y?

  1. Passing by value
  2. Incorrect function declaration
  3. Compiler error
  4. Logical error in the swap function
Show answer

Answer: (a) Passing by value

Q434. What is necessary for a function to perform call by reference in C?

  1. Using global variables
  2. Including header files
  3. Passing the address of variables
  4. Initializing pointers
Show answer

Answer: (c) Passing the address of variables

Q435. How does the bubble sort algorithm work in C?

  1. By swapping adjacent elements
  2. By randomly rearranging elements
  3. By multiplying array elements
  4. By sorting elements in descending order
Show answer

Answer: (a) By swapping adjacent elements

Q436. In the bubble sort example, what is the purpose of the swap function?

  1. To allocate memory
  2. To interchange array elements
  3. To initialize pointers
  4. To perform arithmetic operations
Show answer

Answer: (b) To interchange array elements

Q437. How are elements swapped in the bubble sort program using pointers?

  1. Using temporary variables
  2. Directly assigning values
  3. Using the arithmetic operator (+)
  4. Using the swap function with pointers
Show answer

Answer: (d) Using the swap function with pointers

Q438. In the bubble sort program, why is using pointers essential for swapping elements?

  1. Improves program speed
  2. Reduces memory usage
  3. Enables call by reference
  4. Simplifies function declarations
Show answer

Answer: (c) Enables call by reference

Q439. When is it optional to use braces in the else part?

  1. When there is a single statement inside the else part
  2. When the condition is false
  3. When there is a nested if statement
  4. Braces are always mandatory in the else part
Show answer

Answer: (a) When there is a single statement inside the else part

Q440. What is the recommended programming practice regarding the use of braces?

  1. Use braces only in the if code block
  2. Use braces only in the else code block
  3. Use braces all the time
  4. Use braces only for complex conditions
Show answer

Answer: (c) Use braces all the time

Q441. How do we handle complex conditions in an if statement?

  1. Use nested if statements
  2. Use braces in the else part
  3. Use logical connectives like && and ||
  4. Both a and c are correct
Show answer

Answer: (d) Both a and c are correct

Q442. Which loop variant is executed at least once before the condition is evaluated?

  1. While Loop
  2. Do-While Loop
  3. For Loop
  4. Nested Loop
Show answer

Answer: (b) Do-While Loop

Q443. When are braces mandatory in the while loop?

  1. When there is a single line inside the while code block
  2. When the condition is false
  3. When there are multiple lines of code inside the while code block
  4. Braces are never mandatory in the while loop
Show answer

Answer: (c) When there are multiple lines of code inside the while code block

Q444. What is the syntax for the do-while loop?

  1. while ( condition ) { // Do something }
  2. do { // Do something } while ( condition )
  3. for ( initialization; condition; increment ) { // Do something }
  4. do { // Do something } for ( condition )
Show answer

Answer: (b) do { // Do something } while ( condition )

Q445. How many times are the statements inside the while code block executed if the while condition is false from the beginning?

  1. 0 times
  2. 1 time
  3. n times
  4. Infinite times
Show answer

Answer: (a) 0 times

Q446. When are braces not mandatory in the for loop?

  1. When there is a single statement in the for code block
  2. When there is a complex condition
  3. When there is an else part
  4. Braces are always mandatory in the for loop
Show answer

Answer: (a) When there is a single statement in the for code block

Q447. What is the role of logical connectives like && and || in programming?

  1. They determine the syntax of the if statement
  2. They are used in do-while loops
  3. They handle complex conditions in if statements
  4. They replace the need for braces
Show answer

Answer: (c) They handle complex conditions in if statements

Q448. In a nested if-statement, when is the code inside the nested if block executed?

  1. Only when the condition of the outer if is true
  2. Always
  3. Only when the condition of the inner if is true
  4. Never
Show answer

Answer: (a) Only when the condition of the outer if is true

Q449. According to the programming practice mentioned, what is the major advantage of using structured flowcharting?

  1. It reduces the need for braces
  2. It improves program readability and logical soundness
  3. It simplifies complex conditions
  4. It eliminates the need for nested if statements
Show answer

Answer: (b) It improves program readability and logical soundness

Q450. What is the primary purpose of loops in programming?

  1. To execute code once
  2. To simplify complex conditions
  3. To handle decision structures
  4. To perform repetitive tasks
Show answer

Answer: (d) To perform repetitive tasks

Q451. How does the for loop terminate?

  1. When the condition is false
  2. When the condition is true
  3. When the loop reaches the exit symbol
  4. When the program encounters an error
Show answer

Answer: (a) When the condition is false

Q452. What is the purpose of the functions in the header file stdlib.h described in the given paragraph?

  1. To compare strings
  2. To manipulate strings
  3. To convert between different data types
  4. To concatenate strings
Show answer

Answer: (c) To convert between different data types

Q453. Which function is used to convert a string to a double in the stdlib.h library?

  1. atof
  2. atoi
  3. strtol
  4. strtod
Show answer

Answer: (a) atof

Q454. What does the function strcpy do?

  1. Compares two strings
  2. Copies a string into a character array
  3. Appends a string to another string
  4. Concatenates two strings
Show answer

Answer: (b) Copies a string into a character array

Q455. Which header file contains the string manipulation functions described in the paragraph?

  1. stdlib.h
  2. string.h
  3. stdio.h
  4. math.h
Show answer

Answer: (b) string.h

Q456. What is the purpose of the function strncmp?

  1. Concatenates two strings
  2. Compares two strings up to a specified number of characters
  3. Copies a string into a character array
  4. Determines the length of a string
Show answer

Answer: (b) Compares two strings up to a specified number of characters

Q457. What is the significance of the const keyword in the function prototype char *strcpy( char s1, const char s2 )?

  1. It prevents changes to the destination string (s1).
  2. It prevents changes to the source string (s2).
  3. It allows changes to both strings.
  4. It is not significant in this context.
Show answer

Answer: (b) It prevents changes to the source string (s2).

Q458. In the function prototype char *strcat( char s1, const char s2 ), what does s1 represent?

  1. Destination string
  2. Source string
  3. Number of characters to concatenate
  4. Size of the destination string
Show answer

Answer: (a) Destination string

Q459. How is the destination string represented in the function prototype char *strncpy( char s1, const char s2, size_t n )?

  1. s1
  2. s2
  3. n
  4. const
Show answer

Answer: (a) s1

Q460. Which function is used for converting a string to an integer in the given paragraph?

  1. atof
  2. atoi
  3. strtod
  4. strtol
Show answer

Answer: (b) atoi

Q461. What is the purpose of the endPtr parameter in the strtod function?

  1. It represents the source string.
  2. It prevents changes to the source string.
  3. It points to the end of the converted string.
  4. It is not significant in this context.
Show answer

Answer: (c) It points to the end of the converted string.

Q462. How are command line arguments passed to the program according to the given paragraph?

  1. As integers
  2. As floating-point numbers
  3. As character strings
  4. As boolean values
Show answer

Answer: (c) As character strings

Q463. What is the significance of the base parameter in the function prototype long strtol( const char *nPtr, char endPtr, int base )?

  1. It represents the source string.
  2. It prevents changes to the source string.
  3. It specifies the base for number conversion.
  4. It is not significant in this context.
Show answer

Answer: (c) It specifies the base for number conversion.

Q464. What is the primary use of the conversion functions described in the stdlib.h library according to the paragraph?

  1. String manipulation
  2. Number comparison
  3. Data type conversion
  4. Command line argument parsing
Show answer

Answer: (c) Data type conversion

Q465. In the function prototype int strcmp( const char s1, const char s2), what does it return?

  1. A negative number if s1 < s2
  2. Zero if s1 == s2
  3. A positive number if s1 > s2
  4. All of the above
Show answer

Answer: (d) All of the above

Q466. What does the function strtoul do?

  1. Converts a string to an unsigned long
  2. Compares two strings up to a specified number of characters
  3. Concatenates two strings
  4. Determines the length of a string
Show answer

Answer: (a) Converts a string to an unsigned long

Q467. What does the strcmp function return if the strings s1 and s2 are identical?

  1. A positive number
  2. A negative number
  3. Zero
  4. Null pointer
Show answer

Answer: (c) Zero

Q468. The strncmp function compares:

  1. Entire strings s1 and s2
  2. First character of s1 with the first character of s2
  3. First n characters of s1 with the first n characters of s2
  4. Last n characters of s1 with the last n characters of s2
Show answer

Answer: (c) First n characters of s1 with the first n characters of s2

Q469. What is the purpose of the strlen function?

  1. Compares two strings
  2. Determines the length of a character string
  3. Searches for a character in a string
  4. Breaks a string into tokens
Show answer

Answer: (b) Determines the length of a character string

Q470. Which of the following search functions locates the first occurrence of a character c in a string s?

  1. strcspn
  2. strspn
  3. strchr
  4. strpbrk
Show answer

Answer: (c) strchr

Q471. What does the strrchr function return if the character c is not found in string s?

  1. A positive number
  2. A negative number
  3. Null pointer
  4. Zero
Show answer

Answer: (c) Null pointer

Q472. Which function is used to locate the first occurrence of string s2 in string s1?

  1. strstr
  2. strpbrk
  3. strspn
  4. strcspn
Show answer

Answer: (a) strstr

Q473. What does the strtok function do?

  1. Compares two strings
  2. Determines the length of a character string
  3. Breaks a string into tokens
  4. Searches for a character in a string
Show answer

Answer: (c) Breaks a string into tokens

Q474. Which header file is used for file handling in C++?

  1. <iostream.h>
  2. <fstream.h>
  3. <filestream>
  4. <stdio.h>
Show answer

Answer: (b) <fstream.h>

Q475. What does the ifstream stream stand for in file handling?

  1. Input file stream
  2. Output file stream
  3. File stream
  4. Integer file stream
Show answer

Answer: (a) Input file stream

Q476. When using the ofstream stream in file handling, what is its purpose?

  1. Reading from a file
  2. Writing to a file
  3. Searching in a file
  4. Closing a file
Show answer

Answer: (b) Writing to a file

Q477. What type of files consist of readable English characters?

  1. Program files
  2. Binary files
  3. Text files
  4. Executable files
Show answer

Answer: (c) Text files

Q478. What information is stored in word processor files along with the text?

  1. Binary information
  2. Formatting information
  3. File properties
  4. Length of the file
Show answer

Answer: (b) Formatting information

Q479. In the context of file handling, what is the primary purpose of files in programs?

  1. To store volatile data
  2. To display information on the screen
  3. To execute programs
  4. To save data on a permanent basis
Show answer

Answer: (d) To save data on a permanent basis

Q480. Why might a payroll system use files?

  1. To execute programs
  2. To display information on the screen
  3. To store information permanently and reuse it
  4. To gather data before processing it
Show answer

Answer: (c) To store information permanently and reuse it

Q481. What is the purpose of the fstream stream in C++?

  1. Input file stream
  2. Output file stream
  3. File stream for both reading and writing
  4. Integer file stream
Show answer

Answer: (c) File stream for both reading and writing

Q482. In the context of file handling, what does volatile data refer to?

  1. Data stored permanently
  2. Data displayed on the screen
  3. Data in the computer memory that is not permanent
  4. Data in executable program files
Show answer

Answer: (c) Data in the computer memory that is not permanent

Q483. In strcmp, when does the function return zero?

  1. If s1 is less than s2
  2. If s1 and s2 are identical
  3. If s1 is greater than s2
  4. If s1 and s2 have spaces
Show answer

Answer: (b) If s1 and s2 are identical

Q484. What is the purpose of the strncmp function?

  1. Compare entire strings
  2. Find the length of a string
  3. Compare a specific number of characters in two strings
  4. Determine the length of a character string
Show answer

Answer: (c) Compare a specific number of characters in two strings

Q485. What does the strchr function do?

  1. Finds the first occurrence of a character in a string
  2. Determines the length of the initial segment of characters not in another string
  3. Returns the length of the initial segment consisting only of characters in another string
  4. Locates the last occurrence of a character in a string
Show answer

Answer: (a) Finds the first occurrence of a character in a string

Q486. What is the purpose of the strcspn function?

  1. Finds the first occurrence of a character in a string
  2. Determines the length of the initial segment of characters not in another string
  3. Returns the length of the initial segment consisting only of characters in another string
  4. Locates the last occurrence of a character in a string
Show answer

Answer: (b) Determines the length of the initial segment of characters not in another string

Q487. What does the strspn function return?

  1. Finds the first occurrence of a character in a string
  2. Determines the length of the initial segment of characters not in another string
  3. Returns the length of the initial segment consisting only of characters in another string
  4. Locates the last occurrence of a character in a string
Show answer

Answer: (c) Returns the length of the initial segment consisting only of characters in another string

Q488. What does the strtok function do?

  1. Determines the length of a character string
  2. Breaks a string into tokens based on specified delimiters
  3. Finds the first occurrence of a character in a string
  4. Locates the last occurrence of a character in a string
Show answer

Answer: (b) Breaks a string into tokens based on specified delimiters

Q489. What is the utility of files in programs mentioned in the paragraph?

  1. Files store only non-printable binary information
  2. Files contain volatile information in computer memory
  3. Files save program data on the disk for non-volatile storage
  4. Files display lists of files in Windows Explorer
Show answer

Answer: (c) Files save program data on the disk for non-volatile storage

Q490. Which category of data files is plain text files?

  1. Word processor files
  2. Program files
  3. Files created using Microsoft Word
  4. Files created using Windows Notepad
Show answer

Answer: (d) Files created using Windows Notepad

Q491. What is the primary difference between plain text files and word processor files?

  1. Plain text files have binary information along with text
  2. Word processor files have formatting information stored along with text
  3. Plain text files are created using Windows Explorer
  4. Word processor files run executable programs
Show answer

Answer: (b) Word processor files have formatting information stored along with text

Q492. What do executable program files primarily contain?

  1. Volatile information
  2. Non-printable binary information
  3. Plain text
  4. Formatted text
Show answer

Answer: (b) Non-printable binary information

Q493. How does the dir command work in the command prompt window?

  1. Lists files in a folder
  2. Finds the length of a file
  3. Breaks a string into tokens
  4. Determines the length of a character string
Show answer

Answer: (a) Lists files in a folder

Q494. What is the purpose of the seekg() and tellg() functions in C++?

  1. To read characters from a file
  2. To determine the length of a file
  3. To search for specific data in a file
  4. To insert data in the middle of a file
Show answer

Answer: (b) To determine the length of a file

Q495. How can seekg() and tellg() be used to find the actual data length of a file?

  1. By moving to the beginning of the file and using tellg()
  2. By moving to the end of the file and using tellg()
  3. By moving 10 bytes from the beginning and using seekg()
  4. By moving 0 bytes from the end and using seekg()
Show answer

Answer: (b) By moving to the end of the file and using tellg()

Q496. Why can the size of a file be greater than the actual data length of the file?

  1. Due to inefficient disk operations
  2. Because of electromagnetic devices
  3. File storage complexity
  4. Disk blocks allocation
Show answer

Answer: (d) Disk blocks allocation

Q497. What is the main drawback of the Merge Method for inserting data in the middle of a file?

  1. It requires a lot of computation
  2. It is wasteful in terms of time and space
  3. It cannot handle large-sized data
  4. It disturbs the file structure
Show answer

Answer: (b) It is wasteful in terms of time and space

Q498. What is the key element in resolving the issue of insertion in the middle of a file without disturbing the file structure?

  1. Serial numbers
  2. File sorting
  3. Constant record length
  4. Merge method
Show answer

Answer: (c) Constant record length

Q499. In C++, what function is used for output during the process of writing to a file?

  1. seekg()
  2. tellg()
  3. seekp()
  4. tellp()
Show answer

Answer: (c) seekp()

Q500. What happens when a file is opened with ifstream in C++?

  1. It can only be used for output
  2. It can only be used for input
  3. It can be used for both input and output
  4. It cannot be used for input or output
Show answer

Answer: (b) It can only be used for input

Q501. What does the ios::end flag represent in the context of file handling in C++?

  1. The beginning of the file
  2. The current file position
  3. The end of the file
  4. The size of the file
Show answer

Answer: (c) The end of the file

Q502. How can seekg() be used to move to a specific position in a file without loops or comparisons?

  1. By specifying the position directly
  2. By using tellg() to calculate the position
  3. By using brute force technique
  4. By using seekp() instead
Show answer

Answer: (a) By specifying the position directly

Q503. What does a constant record length in a file help to achieve?

  1. Efficient disk operations
  2. Quick random access
  3. Data compression
  4. Insertion in the middle of a file
Show answer

Answer: (b) Quick random access

Q504. What is the significance of a key in a file in the context of data updation?

  1. It helps in file sorting
  2. It ensures constant record length
  3. It is used to locate a specific record
  4. It prevents file corruption
Show answer

Answer: (c) It is used to locate a specific record

Q505. In what situation is the Merge Method used for inserting data into a file?

  1. When the data size is small
  2. When the file is not sorted
  3. When the data is in gigabytes
  4. When there are holes in student ids
Show answer

Answer: (a) When the data size is small

Q506. What is the algorithm of the Merge Method for inserting data in the middle of a sequential file?

  1. Open the data file and an empty file, read and copy data until the insertion point, insert new data, skip overwritten data, and copy remaining data.
  2. Use seekg() and tellg() to locate the insertion point, then directly insert new data.
  3. Sort the file, then directly insert new data.
  4. Perform a brute force search for the insertion point and then insert new data.
Show answer

Answer: (a) Open the data file and an empty file, read and copy data until the insertion point, insert new data, skip overwritten data, and copy remaining data.

Q507. Why are disks divided into logical blocks when storing files?

  1. To increase disk speed
  2. To simplify file storage
  3. To prevent data corruption
  4. To minimize wastage of disk space
Show answer

Answer: (d) To minimize wastage of disk space

Q508. Why is it suggested to save employee information in a file for a payroll system?

  1. To make the program execution faster
  2. To avoid the need for calculating salaries
  3. To have a permanent record for future use
  4. To eliminate the need for entering data
Show answer

Answer: (c) To have a permanent record for future use

Q509. What is the purpose of using files in the context of data storage?

  1. To speed up program execution
  2. To save data temporarily
  3. To store data permanently on disk
  4. To reduce memory usage
Show answer

Answer: (c) To store data permanently on disk

Q510. What are the three basic steps in file handling?

  1. Input, Process, Output
  2. Open, Read and write, Close
  3. Save, Load, Print
  4. Declare, Initialize, Use
Show answer

Answer: (b) Open, Read and write, Close

Q511. What are ifstream and ofstream in C++ file handling?

  1. Input and output functions
  2. File stream variables
  3. File open and close operations
  4. Predefined streams
Show answer

Answer: (b) File stream variables

Q512. Which function is used to open a file in C++ file handling?

  1. read()
  2. openFile()
  3. open()
  4. startFile()
Show answer

Answer: (c) open()

Q513. What is the argument for the open function when associating a file with a file stream variable?

  1. File type
  2. File size
  3. File path
  4. Filename
Show answer

Answer: (d) Filename

Q514. How can multiple words be read from a file at once in C++ file handling?

  1. myFile >> c;
  2. myFile >> c1 >> c2 >> c3;
  3. read(myFile, c);
  4. readWords(myFile, c1, c2, c3);
Show answer

Answer: (b) myFile >> c1 >> c2 >> c3;

Q515. What is the purpose of the close() function in C++ file handling?

  1. To save changes made to the file
  2. To terminate the program
  3. To release memory
  4. To close the associated file
Show answer

Answer: (d) To close the associated file

Q516. Which stream is used to handle errors while opening a file?

  1. cerr
  2. clog
  3. cin
  4. cout
Show answer

Answer: (a) cerr

Q517. What does the exit(1) statement do in C++ file handling error checking?

  1. Exits the program with an error code
  2. Closes the file
  3. Opens a new file
  4. Resumes program execution
Show answer

Answer: (a) Exits the program with an error code

Q518. What is the primary purpose of the ifstream and ofstream objects in C++ file handling?

  1. Display data on the screen
  2. Handle file stream operations
  3. Calculate salaries
  4. Execute input and output functions
Show answer

Answer: (b) Handle file stream operations

Q519. How can you read a word from a file in C++ file handling?

  1. read(myFile, word);
  2. myFile.readWord(word);
  3. myFile >> word;
  4. getWord(myFile, word);
Show answer

Answer: (c) myFile >> word;

Q520. Why is knowing the file structure important before reading it in C++ file handling?

  1. To speed up the reading process
  2. To avoid reading errors
  3. To reduce the size of the file
  4. To simplify file closing
Show answer

Answer: (b) To avoid reading errors

Q521. What is the purpose of the fstream.h header file in C++ file handling?

  1. It defines input and output functions
  2. It handles file operations
  3. It contains mathematical functions
  4. It manages memory allocation
Show answer

Answer: (b) It handles file operations

Q522. What does the dot (.) operator represent in the context of file stream objects in C++?

  1. File size
  2. Function call
  3. File path
  4. Member access
Show answer

Answer: (d) Member access

Q523. In C++ file handling, what does ifstream myFile; represent?

  1. Input file stream object
  2. Output file stream object
  3. Both input and output file stream objects
  4. Predefined file stream object
Show answer

Answer: (a) Input file stream object

Q524. What is the basic unit of memory?

  1. Kilobyte
  2. Megabyte
  3. Bit
  4. Byte
Show answer

Answer: (c) Bit

Q525. How many bits form a byte?

  1. 4
  2. 8
  3. 16
  4. 32
Show answer

Answer: (b) 8

Q526. What is the primary focus of bit manipulation?

  1. Manipulating characters
  2. Manipulating bytes
  3. Manipulating bits
  4. Manipulating integers
Show answer

Answer: (c) Manipulating bits

Q527. What does the bitwise AND operator (&) return when comparing two bits?

  1. 1 if both bits are 1
  2. 0 if both bits are 1
  3. 1 if any of the two bits is 0
  4. 0 if any of the two bits is 0
Show answer

Answer: (a) 1 if both bits are 1

Q528. In bit manipulation, what does a bit with 1 represent?

  1. Turned off
  2. On
  3. Cleared
  4. Unset
Show answer

Answer: (b) On

Q529. What does the bitwise OR operator (|) return if any one of the bits is 1?

  1. 1
  2. 0
  3. True
  4. False
Show answer

Answer: (a) 1

Q530. What is the result of exclusive OR (XOR) if both bits are the same?

  1. 0
  2. 1
  3. True
  4. False
Show answer

Answer: (a) 0

Q531. What does the NOT operator (~) do to a bit?

  1. Invert it
  2. Set it to 1
  3. Clear it to 0
  4. Turn it off
Show answer

Answer: (a) Invert it

Q532. In the context of bit manipulation, what is a bit field used for in operating systems?

  1. Arithmetic calculations
  2. File attributes
  3. Data encryption
  4. Memory allocation
Show answer

Answer: (b) File attributes

Q533. How can the Exclusive OR operator be utilized for password security?

  1. Encrypting the password
  2. Decrypting the password
  3. Setting a specific bit
  4. Clearing a bit
Show answer

Answer: (a) Encrypting the password

Q534. In the context of file attributes, what does a check mark indicate?

  1. Cleared bit
  2. Set bit
  3. Cleared byte
  4. Set byte
Show answer

Answer: (b) Set bit

Q535. What is the purpose of the ~ (NOT) operator?

  1. Bitwise AND
  2. Bitwise OR
  3. Bitwise inversion or NOT
  4. Unary increment
Show answer

Answer: (c) Bitwise inversion or NOT

Q536. What is the int data type used for?

  1. Real numbers
  2. Characters
  3. Whole numbers
  4. Non-negative numbers
Show answer

Answer: (c) Whole numbers

Q537. What is the size of the char data type in the paragraph's context?

  1. 2 bytes
  2. 4 bytes
  3. 1 byte
  4. 8 bytes
Show answer

Answer: (c) 1 byte

Q538. What is the modulus operator (%) used for in the paragraph?

  1. Division
  2. Multiplication
  3. Addition
  4. Remainder
Show answer

Answer: (d) Remainder

Q539. In the context of comparisons, what does the == operator represent?

  1. Equality
  2. Assignment
  3. Addition
  4. Modulus
Show answer

Answer: (a) Equality

Q540. What type of operators are bitwise AND, OR, and XOR?

  1. Unary operators
  2. Binary operators
  3. Ternary operators
  4. Logical operators
Show answer

Answer: (b) Binary operators

Q541. How is the bitwise NOT operator (~) described in the paragraph?

  1. Unary
  2. Binary
  3. Ternary
  4. Logical
Show answer

Answer: (a) Unary

Q542. Which construct is used for repetitive structures in programming?

  1. Sequential execution
  2. Decisions
  3. File I/O
  4. Loops
Show answer

Answer: (d) Loops

Q543. In the XOR-based data recovery technique, how is the lost data recovered?

  1. By shutting down the system
  2. By replicating data from other disks
  3. By taking XOR of remaining bits
  4. By using a temporary third variable
Show answer

Answer: (c) By taking XOR of remaining bits

Q544. What is the purpose of Hot Plug in the context of disk replacement?

  1. Swapping two numbers
  2. Shifting binary numbers
  3. Replacing a disk without system shutdown
  4. Multiplying binary numbers
Show answer

Answer: (c) Replacing a disk without system shutdown

Q545. In the XOR-based number swapping method, what is the sequence of statements to swap 'a' and 'b'?

  1. a = a ^ b; b = b ^ a; a = a ^ b;
  2. a = a ^ b; b = b ^ a;
  3. a = a ^ b; a = a ^ b;
  4. b = b ^ a; a = a ^ b;
Show answer

Answer: (a) a = a ^ b; b = b ^ a; a = a ^ b;
Note: Swapping with XOR needs three statements: a = a ^ b; b = b ^ a; a = a ^ b. The source key listed only two, which does not complete the swap.

Q546. How are unsigned integers declared explicitly in C?

  1. int i, j, k;
  2. unsigned int i, j, k;
  3. unsigned integers i, j, k;
  4. unsigned i, j, k;
Show answer

Answer: (b) unsigned int i, j, k;

Q547. What does left shifting do in binary numbers?

  1. Division by 2
  2. Multiplication by 2
  3. Exclusive OR
  4. Bitwise AND
Show answer

Answer: (b) Multiplication by 2

Q548. What is the primary advantage of shift operators over direct multiplication and division?

  1. Faster execution
  2. Smaller code size
  3. Easier syntax
  4. Improved precision
Show answer

Answer: (a) Faster execution

Q549. What does Hot Swap refer to in the context of disk replacement?

  1. Swapping two numbers without a third variable
  2. Replacing a disk without system shutdown
  3. Shifting binary numbers
  4. Encryption and decryption
Show answer

Answer: (b) Replacing a disk without system shutdown

Part 2: Subjective Questions

Q1. Suppose z is a variable of type int. What will be the result of x = 27/4;? (1 marks)

6. Both operands are integers, so C++ performs integer division and drops the fractional part (27/4 = 6.75, stored as 6).

Q2. What is the result of the expression x = 2 + 3 * 4 - 4 / 2? (1 marks)

Multiplication and division come first: 3*4 = 12 and 4/2 = 2. Then 2 + 12 - 2 = 12.

Q3. To which category of software do the compiler and the interpreter belong? (1 marks)

System software. They are programs that translate source code into machine code and help run other programs.

Q4. Which header file must be included while handling files? (1 marks)

fstream (written as <fstream.h> in older VU code). It provides ifstream, ofstream and fstream.

Q5. What is meant by the C++ statement: const int *ptr = &x; (1 marks)

ptr is a pointer to a constant int. It stores the address of x, but the value cannot be changed through ptr (so *ptr = 5; is an error). The pointer itself can be made to point somewhere else.

Q6. In program commenting, is commenting the code liberally useful? (1 marks)

Yes. Code should be self-contained and understandable, so comments should be placed liberally. Good comments explain the logic (why), not the mechanics (what each line does).

Q7. Debugger tools are helpful in tracing logical errors. (True/False) (1 marks)

True. A debugger lets you run the program step by step and watch variable values, which is the way to find logical errors (errors that compile but give wrong output).

Q8. Give the general syntax of the definition of a structure. (1 marks)

struct structure_name
{
    data_type member1;
    data_type member2;
    // ...
};      // note the semicolon

Q9. Which variable will be used in the inner code block if the same variable name is declared in both the outer and the inner block? (2 marks)

The inner block's variable. It hides (shadows) the outer variable of the same name for as long as the program is inside the inner block. When the inner block ends, the outer variable is visible again.

Q10. Which standard library is included when your program reads from, or writes to, files? (2 marks)

The fstream library (#include <fstream>, or <fstream.h> in old compilers). It provides ifstream (input), ofstream (output) and fstream (both).

Q11. What is the difference between the switch statement and the if statement? (2 marks)

  • switch selects among many alternatives by comparing one integer or character expression with constant case values. It is cleaner than a long chain of if-else.
  • if can test any condition (relational or logical, on several variables), but each if/else chooses between two paths unless statements are nested.
  • In a switch, execution continues into the next case unless break is used.

Q12. What is wrong with the following code, and why? (2 marks)

int x, y;
int *ptr1 = &x;
int *ptr2 = &y;
ptr1 + ptr2;

Two pointers cannot be added. Adding two addresses has no meaning, so the compiler gives an error. (A pointer can be added to or subtracted from an integer, and two pointers of the same type can be subtracted.) Storing the result in another variable, as some shared answers suggest, does not fix it.

Q13. Which bit of a number is used as the sign bit? (2 marks)

The most significant bit (the leftmost bit). 0 means positive and 1 means negative.

Q14. How can a program use a function? (2 marks)

By calling it. The calling program writes the function name followed by the arguments in brackets, for example area(5, 3);. The data types and return type are not written in the call; they appear only in the prototype and the definition.

Q15. Which function is used to read or write more than a single character or a line while handling files? (2 marks)

getline() reads a whole line (or a block up to a delimiter). For raw blocks of bytes, the stream functions read() and write() are used.

Q16. Suppose the pointer yptr points to the first element of the array y and the size of the array is 10. Can we increment yptr 12 times? What will happen? (2 marks)

The compiler will not stop us, because incrementing a pointer is legal. But after 10 increments yptr is past the last element, and after 12 it points to memory outside the array. Reading or writing through it is undefined behaviour (garbage values or a crash), so a pointer must be kept within the array bounds.

Q17. What is the difference between a for loop and a while loop? (2 marks)

  • for: initialization, condition and update are written together in the loop header. It is best when the number of iterations is known in advance.
  • while: only the condition is in the header; initialization and update are written separately. It is best when the number of iterations is not known.

Q18. Consider the structure struct Customer { int custnum; int salary; float commission; }; What line of code assigns 2000 to the member salary of the structure variable cust1? (2 marks)

Customer cust1;        // define the variable (struct Customer cust1; in C)
cust1.salary = 2000;

The dot operator is used to reach a member of a structure variable.

Q19. When a pointer is incremented, how many bytes does it move? (2 marks)

It moves by the size of the type it points to. For an int pointer on a system where int takes 4 bytes, yptr++ adds 4 bytes, so it points to the next integer in memory. A char pointer would move by 1 byte and a double pointer by 8.

Q20. What is a truth table? (2 marks)

A truth table lists all possible combinations of input values of a logical expression together with the result for each combination. It is used to check whether a complicated logical expression is true or false for every input.

ABA && BA || B
0000
0101
1001
1111

Q21. Why do we close a file after use? (2 marks)

Closing a file flushes the buffered data to the disk so nothing is lost, and releases the file handle and memory held by the stream. An unclosed output file can lose data or stay locked, and a program that opens many files without closing them can run out of file handles.

Q22. A two-dimensional array has 3 rows and 4 columns. Write the syntax to initialize the first element of all three rows with the value 2. (2 marks)

int matrix[3][4];
matrix[0][0] = 2;
matrix[1][0] = 2;
matrix[2][0] = 2;
// or, using a loop:
for (int r = 0; r < 3; r++)
    matrix[r][0] = 2;

Q23. Find the error in: seekg(-10L, ios::beg); (2 marks)

The offset is measured from the beginning of the file, so a negative offset with ios::beg would put the pointer before the start of the file, which is invalid. Use a positive offset with ios::beg (for example seekg(10L, ios::beg)), or use a negative offset only with ios::cur or ios::end.

Q24. Write the syntax for calling a string function that compares the first 5 characters of the array name with the string "asdf". (2 marks)

strncmp(name, "asdf", 5);   // returns 0 if the compared characters are equal

It needs #include <string.h>. Since "asdf" has only 4 characters, the comparison stops at its null character.

Q25. What will be the value of x after the following code? int x = 10; int y = 30; int *xptr = &x; x = *xptr + 10; (2 marks)

*xptr is the value of x (10). So x = 10 + 10 = 20.

Q26. Identify each function as a string conversion function or a string manipulation function: (1) double atof(const char *nptr), (2) char *strcpy(char *s1, const char *s2), (3) int atoi(const char *nptr) (2 marks)

  • atof: string conversion function (string to double, declared in stdlib.h).
  • strcpy: string manipulation function (copies a string, declared in string.h).
  • atoi: string conversion function (string to int, declared in stdlib.h).

Q27. How does a two-dimensional array relate to a matrix? (2 marks)

A 2-D array is the C++ form of a matrix: int m[r][c] has r rows and c columns, and the element in row i and column j is m[i][j] (indexes start at 0). It is stored in memory row by row in contiguous locations.

Q28. Can the assignment operator be used to copy one C-string (character array) into another? (2 marks)

No. An array name is a constant address, so s2 = s1; does not copy the characters (and does not compile for arrays). Use strcpy(s2, s1); from string.h, and make sure s2 is large enough. (A shared answer that said "yes" was wrong.)

Q29. What do 'int day[] = {1,2,3,4,5,6,7};' and 'int day[7] = {1,2,3,4,5,6,7};' declare? How many elements does day have in each case? (3 marks)

In both cases the array has 7 elements. When the size is left empty, the compiler counts the initial values.

Q30. Perform a left shift operation on the binary number 0101 and write the result in binary and decimal. (3 marks)

Shifting left by one bit moves every bit one place to the left and fills the right with 0: 0101 << 1 = 1010.

Decimal: 0101 = 5 and 1010 = 10. A left shift by one bit multiplies the number by 2.

Q31. What is the difference between a variable and a pointer? (3 marks)

  • A variable has a name, a type and a location in memory, and it stores a value (int x = 5;).
  • A pointer is a special variable that stores the memory address of another variable (int *p = &x;). The value is reached by dereferencing: *p.
  • A pointer takes the type of the variable it points to, and pointer arithmetic moves by the size of that type.

Q32. What is the difference between tellg() and tellp()? (3 marks)

  • tellg() returns the current position of the get pointer, which is the position for reading (input stream).
  • tellp() returns the current position of the put pointer, which is the position for writing (output stream).
  • Both return the position as a number of bytes from the beginning of the file.

Q33. If there are 2^n elements in an array, how many iterations are needed to search a number using binary search and linear search? (3 marks)

(The printed '2n' in the shared paper is taken as 2n, as the superscript was lost.)

  • Binary search halves the search range every iteration, so at most n iterations are needed (the array must be sorted).
  • Linear search checks the elements one by one, so in the worst case it needs 2n iterations.

Q34. Why is the binary search algorithm more efficient than the linear search algorithm? (5 marks)

Binary search works on a sorted array and uses divide and conquer: it compares the target with the middle element and discards half of the remaining elements each time. Linear search checks the elements one at a time.

Example: in an array of 1000 elements, linear search may need up to 1000 iterations, while binary search needs at most about 10 (210 = 1024).

Q35. How is learning to design programs like playing soccer? (3 marks)

A soccer player first learns the basic skills: trapping, dribbling, passing and shooting. Only after that can the player learn to play a position, use strategies, choose between strategies, and sometimes create a new variation. In the same way, a programmer first learns the basic building blocks (variables, loops, functions, arrays) and then learns to combine them into designs, pick between alternative designs and create new ones when none fits.

Q36. 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; (3 marks)

The loop stores 0, 1, 2, 3, 4, 5, 6 and adds them: 0+1+2+3+4+5+6 = 21.

Sum = 21

Q37. Write down the output: int A[5] = {1, 2, 3, 4}; int i; for (i = 0; i < 5; i++) { A[i] = 2*A[i]; cout << A[i] << " "; } (3 marks)

The fifth element is not given, so it is initialised to 0. Each element is doubled:

2 4 6 8 0

Q38. Write down the output of the following program (assume sizeof char = 1, int = 2, float = 4). union mytypes_t { char c; int i; float f; } mytypes; ... mytypes.c = 'H'; mytypes.i = 15; cout << sizeof(mytypes) << endl; mytypes.i = 15; mytypes.c = 'H'; cout << sizeof(mytypes) << endl; (5 marks)

All members of a union share the same memory, and the union is as big as its largest member (float = 4 bytes). The order of assignment does not change the size.

4
4

Q39. Explain the logic of the given program and determine its output. char name[10] = "Khagan"; char msg[20] = "Welcome!"; cout << strncat(msg, name, 3); (3 marks)

strncat(msg, name, 3) appends at most the first 3 characters of name ("Kha") to the end of msg and returns msg. The program prints:

Welcome!Kha

Q40. Declare an integer array longroutes and a pointer routePtr, then assign the address of the array to the pointer. (3 marks)

int longroutes[10];          // any size
int *routePtr;
routePtr = longroutes;       // the array name is the address of its first element
// equivalent: routePtr = &longroutes[0];

Q41. Given the array declaration 'int arr[] = {1,2,3,4,5,6,7,8,9}; int *arr_ptr = arr;' Find the value of: (1) *(arr_ptr + 4) (2) (*arr_ptr)++ (3) *(arr_ptr++) (3 marks)

  • *(arr_ptr + 4) = arr[4] = 5.
  • (*arr_ptr)++ gives the current value of arr[0], which is 1, and then increments that element, so arr[0] becomes 2.
  • *(arr_ptr++) gives the value that arr_ptr points to and then moves the pointer to the next element. On its own it gives 1. If the three are executed one after the other in the same program, it gives 2 because arr[0] has already been incremented.

Q42. If you are provided two methods for accessing a file, random and sequential, which will you prefer and why? (3 marks)

It depends on the job. I prefer random access when data must be read or updated at any position quickly, because seekg()/seekp() jump directly to the required record without reading everything before it. Sequential access is simpler and enough when the whole file is always processed from start to end (for example reading a text report).

Q43. An integer pointer xptr contains the memory address 0x22ff50. If the statement xptr += 4; is executed, how many bytes will xptr jump and what will its new address be? (int = 4 bytes)

The pointer moves 4 elements x 4 bytes = 16 bytes, so the new address is 0x22ff50 + 0x10 = 0x22ff60.

Q44. Which approach is better for reading data from a text file: reading character by character or reading multiple lines at a time? (3 marks)

Reading a line (or block) at a time with getline() is usually better: it needs far fewer function calls and disk accesses, so it is faster and the code is shorter. Character-by-character reading (get()) is only preferred when each character must be inspected individually.

Q45. Write a C/C++ program which defines an array of 10 elements, asks a number from the user and searches it in the array. If it exists, display its location, otherwise display "The number is not in the given array". (5 marks)

#include <iostream>
using namespace std;
int main()
{
    int arr[10], num, pos = -1;
    for (int i = 0; i < 10; i++)
    {
        cout << "Enter element " << i + 1 << ": ";
        cin >> arr[i];
    }
    cout << "Enter the number to search: ";
    cin >> num;
    for (int i = 0; i < 10; i++)
    {
        if (arr[i] == num)
        {
            pos = i;
            break;
        }
    }
    if (pos != -1)
        cout << "Number found at location " << pos + 1 << endl;   // index is pos
    else
        cout << "The number is not in the given array" << endl;
    return 0;
}

Q46. Write a program which stores the string "12players2teams" in an array and displays how many digits and alphabets it contains, using character handling functions. (5 marks)

#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
    char str[16] = "12players2teams";   // 15 characters + 1 for '\0'
    int digits = 0, letters = 0;
    for (int i = 0; str[i] != '\0'; i++)
    {
        if (isdigit(str[i]))      digits++;
        else if (isalpha(str[i])) letters++;
    }
    cout << "Digits = " << digits << endl;       // 3
    cout << "Alphabets = " << letters << endl;   // 12
    return 0;
}

The paper says an array of 15 elements, but a 15-character string needs 16 elements because of the null character.

Q47. What happens when we try to copy the array arr1 into arr2 using arr2 = arr1; in the following code? Justify. int arr1[3] = {2,3,5}; int arr2[3]; arr2 = arr1; (5 marks)

This gives a compile-time error. An array name is a constant address of the first element, so it cannot be assigned. An array cannot be copied in one statement. Each element has to be copied separately, using a loop:

for (int i = 0; i < 3; i++)
    arr2[i] = arr1[i];

Both arrays must also have the same size and data type.

Q48. Differentiate between a random access file and a sequential access file. (5 marks)

  • Sequential access file: data is written and read in order, from the beginning towards the end. To reach the 100th record, the 99 before it must be passed. Simple text files are an example.
  • Random access file: any position in the file can be reached directly, in any order, by moving the file pointer with seekg()/seekp() and finding the position with tellg()/tellp(). It is fast for updating or reading specific records.
  • Random access needs fixed-size records or known offsets; sequential access does not.

Q49. Write code which reads a string of not more than 20 characters from the keyboard, stores it in an array Name and displays it on the screen. (5 marks)

#include <iostream>
using namespace std;
int main()
{
    char Name[21];            // 20 characters + null
    cout << "Enter a string (max 20 characters): ";
    cin.getline(Name, 21);    // reads at most 20 characters and stops at the end of line
    cout << "You entered: " << Name << endl;
    return 0;
}

Q50. Write a program which defines an array of 15 elements and changes all uppercase letters to lowercase and all lowercase letters to uppercase using character handling functions. (5 marks)

#include <iostream>
#include <cctype>
using namespace std;
int main()
{
    char str[16];
    cout << "Enter 15 characters: ";
    cin.getline(str, 16);
    for (int i = 0; str[i] != '\0'; i++)
    {
        if (isupper(str[i]))      str[i] = tolower(str[i]);
        else if (islower(str[i])) str[i] = toupper(str[i]);
    }
    cout << str << endl;
    return 0;
}

Q51. What will be the output of the following code? void func(int [], int); main() { int arr[5] = {2, 3, 5, 6, 7}; func(arr, 5); for (int i = 0; i < 5; i++) cout << arr[i] << " "; } void func(int a[], int size) { for (int i = 0; i < size; i++) a[i] = 2*a[i]; } (5 marks)

The array is passed by address, so func doubles the original elements:

4 6 10 12 14

Q52. What is a random access file and how can data be read from and written into it? (5 marks)

A random access file lets the program move directly to any position and read or write there, instead of going through the data in sequence.

  • Open it with an fstream object (for both input and output) or with ifstream/ofstream.
  • Move the get pointer with seekg(offset, origin) for reading and the put pointer with seekp(offset, origin) for writing. The origin is ios::beg, ios::cur or ios::end.
  • Use tellg() / tellp() to know the current position.
  • Read with read() / get() / getline() and write with write() / put().
fstream f("data.dat", ios::in | ios::out | ios::binary);
f.seekp(20, ios::beg);              // go to byte 20
f.write("abc", 3);                  // write 3 bytes there
f.seekg(20, ios::beg);              // go back to byte 20
char buf[4];
f.read(buf, 3);                     // read them back
f.close();

Q53. What is the purpose of the default statement in a switch? (5 marks)

The default statement is optional. If the value of the switch expression does not match any case, the statements of default are executed. It is used to handle unexpected or invalid values (for example, printing an "invalid choice" message). It is usually written last.

switch (choice)
{
    case 1: cout << "One"; break;
    case 2: cout << "Two"; break;
    default: cout << "Invalid choice";
}

Q54. Write down the syntax of the switch statement.

switch (expression)       // integer or character expression
{
    case value1:
        statements;
        break;
    case value2:
        statements;
        break;
    default:                 // optional
        statements;
}

Q55. Give some examples of application software. (2 marks)

Application software helps the user solve end-user problems. Examples: MS Word (word processor), MS Excel (spreadsheet), a web browser, media player and accounting software.

Q56. Write a program which stores 10 elements in an array, sorts the array, and finds the minimum and maximum numbers. (5 marks)

#include <iostream>
using namespace std;
int main()
{
    int a[10];
    for (int i = 0; i < 10; i++) { cout << "Enter number: "; cin >> a[i]; }
    // bubble sort (ascending)
    for (int i = 0; i < 9; i++)
        for (int j = 0; j < 9 - i; j++)
            if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; }
    cout << "Sorted: ";
    for (int i = 0; i < 10; i++) cout << a[i] << " ";
    cout << endl << "Minimum = " << a[0] << endl;   // first after sorting
    cout << "Maximum = " << a[9] << endl;           // last after sorting
    return 0;
}

Q57. Find the errors in the program (if any) and, after correcting them, write the output. ofstream outfile; long position, long positon; char outfilename[] = "abc.txt"; outfile.open(outfilename); if (!outfile) cout << "Error Occured while opening a file"; outfile.write("This is a car", 12); position = outfile.tellp(); outfile.seekp(position-5); outfile.write("jar", 3); outfile.close(); return 0; (5 marks)

  • The header <fstream.h> (or <fstream> with using namespace std;) is missing.
  • long position, long positon; declares position twice with a misspelled name. It must be long position;.
  • Statements must end with semicolons (for example after seekp(position-5)), and the if statement needs correct brackets: if (!outfile).
#include <fstream>
using namespace std;
int main()
{
    ofstream outfile;
    long position;
    char outfilename[] = "abc.txt";
    outfile.open(outfilename);
    if (!outfile)
        cout << "Error Occured while opening a file";
    outfile.write("This is a car", 12);   // writes "This is a ca" (12 characters)
    position = outfile.tellp();           // 12
    outfile.seekp(position - 5);          // go back to byte 7
    outfile.write("jar", 3);              // overwrites bytes 7, 8, 9
    outfile.close();
    return 0;
}

File content after the program: This isjarca. Only 12 characters are written, so the 'r' is not written; "jar" replaces the space, 'a' and space at positions 7 to 9.

Q58. Write a program which declares and initializes an integer array of 10 elements and then, using a pointer, displays the array elements in reverse order. (5 marks)

#include <iostream>
using namespace std;
int main()
{
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int *ptr = arr + 9;                  // points to the last element
    for (int i = 0; i < 10; i++)
    {
        cout << *ptr << " ";
        ptr--;                           // move to the previous element
    }
    return 0;
}

Q59. Following are two programming statements. Write down the functionality of each. (1) int *const intPtr = &x; (2) const int *intPtr = &x; (5 marks)

  • int *const intPtr = &x;: intPtr is a constant pointer to an int. The address stored in it cannot be changed (it must be initialised and always points to x), but the value of x can be changed through it (*intPtr = 7; is allowed).
  • const int *intPtr = &x;: intPtr is a pointer to a constant int. The value cannot be changed through the pointer (*intPtr = 7; is an error), but the pointer can be made to point to another variable.

Q60. Write a program which takes a string from the user and searches for it within another string "This is my Pakistan". If the user enters "my", the program should display "String found", otherwise "String not found". (5 marks)

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char text[] = "This is my Pakistan";
    char word[30];
    cout << "Enter the string to search: ";
    cin.getline(word, 30);
    if (strstr(text, word) != NULL)
        cout << "String found" << endl;
    else
        cout << "String not found" << endl;
    return 0;
}

Q61. Detect and correct the compile-time errors in the following code, which should print the numbers from 1 to 100. void main() { int counter, float *ptr, for (counter = 1; counter <= 100; counter++) { ptr = counter, cout << ptr << ""; getch(), return 0; } } (5 marks)

  • Statements must end with semicolons, not commas (int counter;, ptr = counter;, getch();).
  • float *ptr; ptr = counter; is an error: an int cannot be assigned to a float pointer. A pointer is not needed at all, so use cout << counter.
  • void main() must not return 0;. Either remove the return statement or declare int main().
  • Headers iostream.h and conio.h are needed, and the braces must match.
#include <iostream.h>
#include <conio.h>
void main()
{
    int counter;
    for (counter = 1; counter <= 100; counter++)
        cout << counter << " ";
    getch();
}

Q62. Write a program with a user-defined function ConvertInSeconds that takes three integer arguments (hours, minutes and seconds) and returns the total number of seconds. Read the values in main, call the function and display the result. (1 hour = 60 minutes, 1 minute = 60 seconds) (10 marks)

#include <iostream>
using namespace std;

int ConvertInSeconds(int hours, int minutes, int seconds)
{
    return hours * 60 * 60 + minutes * 60 + seconds;
}

int main()
{
    int h, m, s;
    cout << "Enter hours, minutes and seconds: ";
    cin >> h >> m >> s;
    cout << "Total seconds = " << ConvertInSeconds(h, m, s) << endl;
    return 0;
}

Q63. Write a void function that takes integer numbers from the user and displays the sum of the odd and the even numbers entered. The program should terminate if the user enters a negative number. (10 marks)

#include <iostream>
using namespace std;

void function()
{
    int n, oddSum = 0, evenSum = 0;
    cout << "Enter numbers (negative number to stop):" << endl;
    cin >> n;
    while (n >= 0)
    {
        if (n % 2 == 0)
            evenSum += n;
        else
            oddSum += n;
        cin >> n;
    }
    cout << "Sum of odd numbers  = " << oddSum << endl;
    cout << "Sum of even numbers = " << evenSum << endl;
}

int main()
{
    function();
    return 0;
}

Q64. Write a C++ program that determines if a departmental store customer has exceeded the credit limit on a charge account. Input in five variables: account number, balance at the beginning of the month, total of all items charged, total of all credits, and the allowed credit limit. New balance = beginning balance + charges - credits. If the new balance exceeds the limit, display "Credit Limit exceeded." (10 marks)

#include <iostream>
using namespace std;
int main()
{
    int account;
    float beginBalance, charges, credits, creditLimit, newBalance;
    cout << "Enter account number: ";            cin >> account;
    cout << "Enter beginning balance: ";         cin >> beginBalance;
    cout << "Enter total charges: ";             cin >> charges;
    cout << "Enter total credits: ";             cin >> credits;
    cout << "Enter allowed credit limit: ";      cin >> creditLimit;
    newBalance = beginBalance + charges - credits;
    cout << "Account " << account << " new balance = " << newBalance << endl;
    if (newBalance > creditLimit)
        cout << "Credit Limit exceeded." << endl;
    return 0;
}

Q65. Write a function BatsmanAvg which calculates the average of a player (batsman). Call it from main. Take the total runs and the total number of matches played from the user in main. (10 marks)

#include <iostream>
using namespace std;

float BatsmanAvg(int totalRuns, int matches)
{
    return (float)totalRuns / matches;     // cast so the division keeps decimals
}

int main()
{
    int runs, matches;
    cout << "Enter total runs: ";     cin >> runs;
    cout << "Enter matches played: "; cin >> matches;
    if (matches > 0)
        cout << "Batting average = " << BatsmanAvg(runs, matches) << endl;
    else
        cout << "Matches played must be greater than 0" << endl;
    return 0;
}

Q66. What is a compiler? (3 marks)

A compiler is system software that translates the whole source program written in a high-level language (such as C++) into machine language (object code) and reports syntax errors. The result is then linked into an executable file that the computer can run. An interpreter, in contrast, translates and runs the program line by line.

Q67. What is the difference between a while loop and a for loop? (5 marks)

  • while: while (condition) { ... }. The condition is checked before each iteration. The counter must be initialised before the loop and updated inside it. Used when the number of repetitions is not known.
  • for: for (init; condition; update) { ... }. Initialization, condition and update are in one place, which makes it compact and less error-prone. Used when the number of repetitions is known.
  • Both can be converted into each other; the choice is about readability.

Q68. Write the code of the following arrays: (1) a float array of length 8, (2) a pointer to the float array of length 8. (3 marks)

float arr[8];          // float array of length 8
float *ptr = arr;      // pointer to it (points to arr[0])

Q69. Find the error in the following code. int number; if (number/2 == 0) cout << "The number is even"; else() cout << "The number is odd"; getch(); (3 marks)

  • The test for an even number must use the remainder: number % 2 == 0. number / 2 == 0 is true only for 0 and 1.
  • else() is wrong; else has no condition and no brackets: else.
  • number is never given a value (it holds garbage), so it must be read first (cin >> number;).
  • cout needs the insertion operator: cout << "The number is even";, and the closing brace must match.

Q70. Write code to find the product: product = number * 2^5, taking the input from the user and showing the output. (5 marks)

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int number;
    cout << "Enter a number: ";
    cin >> number;
    int product = number * (int)pow(2, 5);    // 2^5 = 32
    cout << "Product = " << product << endl;
    return 0;
}

Q71. What are the similarities and differences between structures and unions? (5 marks)

  • Similarity: both group variables of different types under one name, are declared with the same syntax, and their members are reached with the dot operator.
  • Structure: every member has its own memory, so its size is (at least) the sum of the members' sizes.
  • Union: all members share the same memory location, so only one member holds a valid value at a time, and the size equals the size of the largest member. Example: a union of an int (4 bytes) and a char (1 byte) takes 4 bytes.

Q72. Write the syntax of opening the file 'myFile.txt' in 'app' mode using an ofstream variable. (1 marks)

ofstream outfile;
outfile.open("myFile.txt", ios::app);
// or in one line: ofstream outfile("myFile.txt", ios::app);

Q73. Write a declaration statement for an array of 10 elements of type float, with the first four elements initialised to 1.0, 2.0, 3.0 and 4.0. (2 marks)

float arr[10] = {1.0, 2.0, 3.0, 4.0};   // the remaining 6 elements become 0

Q74. If int array[10]; is an integer array, write the statements which store values at the fifth and the ninth location of this array. (5 marks)

cout << "Enter fifth position: ";
cin >> array[4];        // fifth location has index 4
cout << "Enter ninth position: ";
cin >> array[8];        // ninth location has index 8

Q75. Identify the errors in the following code and give the reason. main() { int x = 10 const int *ptr = &x; *ptr = 5; } (3 marks)

  • int x = 10 is missing the ending semicolon.
  • *ptr = 5; is an error because ptr is a pointer to a constant int: the value being pointed to cannot be changed through ptr. Either remove const or change x directly (x = 5;).

Q76. What is programming, and why is learning to program useful? (3 marks)

Programming is writing a precise sequence of steps (a program) that tells the computer how to solve a particular problem. Learning it develops analytical and problem-solving skills, and it teaches you to analyse a problem, plan a solution, pay attention to detail and test the result.

Q77. What is the program design recipe? (3 marks)

  • Analyse the problem statement.
  • Express its essence abstractly, with examples.
  • Formulate statements and comments in a precise language.
  • Evaluate and revise the program with checks and tests.
  • Pay attention to detail, reusability and the user interface.

Q78. What is the role of the preprocessor in a C++ program? (3 marks)

The preprocessor runs before compilation and acts on directives that start with #. For example, #include <iostream.h> inserts the contents of a system file into the program, and #define replaces a symbolic name with its value. Its output is what the compiler actually compiles.

Q79. Why is main() special in a C/C++ program? (2 marks)

main() is the entry point: when the program is run, the system starts executing from main first. Every program must have exactly one main function; the other functions run only when main (directly or indirectly) calls them.

Q80. Why is the semicolon important at the end of a statement, and what happens if it is missing? (2 marks)

The semicolon marks the end of a statement. If it is missing, the compiler reports a syntax error and the program does not compile.

Q81. What is cout and what does cout << "Welcome to Virtual University of Pakistan"; do? (2 marks)

cout is the standard output stream connected to the screen. The statement sends the text between the double quotes to the screen using the insertion operator <<, so it prints: Welcome to Virtual University of Pakistan.

Q82. When is the double data type used? How does it differ from float? (2 marks)

double stores real numbers with a larger range and more precision than float. A float usually takes 4 bytes while a double takes 8 bytes (twice as much), so double is used when large values or more accurate results are needed.

Q83. How does the modulus operator (%) work and where can it be used? (2 marks)

x % y gives the remainder of the division of x by y. It works only with integer operands (not float or double). Example: 7 % 2 = 1, so n % 2 == 0 tests for an even number and n % 10 gives the last digit.

Q84. Explain the importance of parentheses in arithmetic expressions. (2 marks)

Parentheses force the order of evaluation: the expression inside them is evaluated first, and with nested parentheses the innermost goes first. Example: 10 + 10 * 5 = 60 but (10 + 10) * 5 = 100. They also make long expressions easier to read.

Q85. What are shorthand (compound) assignment operators? Explain %=. (2 marks)

They combine an arithmetic operation with assignment: +=, -=, *=, /=, %=. For example, x += 4; means x = x + 4;. x %= 2; means x = x % 2;, so with x = 7 the result is 1.

Q86. Explain the while loop. How does it differ from the do-while loop? (3 marks)

  • while: the condition is tested before the body, so the body may execute zero or more times.
  • do-while: the body executes first and the condition is tested at the end, so the body executes at least once. It is preferred when the statements must run once before the check (for example, reading a value and then validating it).
do {
    cin >> n;
} while (n < 0);   // semicolon is required

Q87. What does the continue statement do, and how does it behave in a while loop compared to a for loop? (3 marks)

continue skips the rest of the current iteration and goes to the next one. In a while loop, control goes straight back to the condition, so the update statement (if it is inside the body after continue) is skipped, which can cause an infinite loop. In a for loop, control goes to the update expression first (the counter is incremented) and then the condition is tested.

Q88. Why is the goto statement discouraged in structured programming? (2 marks)

goto makes the flow of control jump around, producing tangled, hard-to-follow, hard-to-debug code ("spaghetti code"). Structured programming uses sequence, decision and loops, with a single entry and a single exit for each module.

Q89. What is a function declaration (prototype)? (2 marks)

A function declaration (prototype) tells the compiler the function's return type, name and the types of its parameters, for example int add(int, int);. It lets the function be called before its definition appears. The definition contains the body of the function.

Q90. Explain call by value. (3 marks)

In call by value (the default in C/C++), a copy of each argument is passed to the function. Changes made to the parameter inside the function do not affect the original variable in the calling program.

void f(int x) { x = 20; }
int main() { int i = 10; f(i); cout << i; }   // prints 10

Q91. What is call by reference and how is it achieved with pointers? (3 marks)

In call by reference the function receives the address of the variable, so it can change the original value. In C it is simulated with pointers: pass &x and use *p inside the function. It is useful for returning more than one value and for avoiding copying large data.

void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
// call: swap(&x, &y);

Q92. What is the purpose of flow charts in program design? (2 marks)

A flow chart is a pictorial representation of the program's logic and sequence of steps, drawn with standard symbols: oval for start/end, rectangle for a process, diamond for a decision and arrows for the flow. It helps in understanding and checking the logic before writing code.

Q93. What is the role of relational operators in decision making? (2 marks)

Relational operators (>, <, >=, <=, ==, !=) compare two values and give true or false. The if statement uses that result to decide which statements to execute.

Q94. Explain how the if/else structure works. (2 marks)

The if statement tests a condition. If it is true, the statements in the if block run; otherwise the statements in the else block run. Exactly one of the two blocks runs. Braces should always be used to make blocks clear.

Q95. Explain the logical operators && and || with an example. (2 marks)

&& (AND) is true only when both conditions are true; || (OR) is true when at least one is true; ! (NOT) reverses a condition. Example: if (age >= 18 && age <= 60) is true only for ages from 18 to 60.

Q96. How can rand() be limited to a smaller range? Give an example. (2 marks)

Use the modulus operator. rand() % 6 gives values from 0 to 5; adding 1 gives 1 to 6, as for a die: x = 1 + rand() % 6;. (rand() is declared in stdlib.h.)

Q97. What does const int arraySize = 100; mean? (2 marks)

It declares an integer constant named arraySize with the value 100. The value cannot be changed afterwards, and it must be initialised when declared. Using it as the array size and in loop limits makes the program easy to change in one place.

Q98. Why is the null character '\0' important in character arrays? (2 marks)

A C string is a character array that ends with the null character ('\0', ASCII code 0). Functions such as cout and strlen use it to know where the string ends. The array must therefore be one element larger than the number of visible characters.

Q99. What is the purpose of swapping in sorting? Show how it is done. (3 marks)

Sorting rearranges elements by exchanging out-of-order neighbours. To swap two values, a third temporary variable is needed so that no value is lost:

int temp = a[j];
a[j]   = a[j + 1];
a[j + 1] = temp;

Q100. Explain the divide-and-conquer strategy of binary search. (3 marks)

Binary search works on a sorted array. It compares the target with the middle element: if equal, it is found; if smaller, the search continues in the left half; if larger, in the right half. Half of the remaining elements are discarded in each step, so an array of 2n elements needs at most n steps.

Q101. How are arrays passed to functions in C/C++, and why is the size also passed? (3 marks)

An array is passed by passing its name, which is the address of the first element, so the function works on the original array (not a copy). The function cannot know how many elements there are, so the size is passed as another parameter: void reverse(char[], int);.

Q102. What is the default way of passing values to a function in C/C++, and how are arrays different? (2 marks)

The default is call by value (a copy is sent). Arrays are the exception: the address of the first element is passed, so changes inside the function affect the original array.

Q103. What is device driver software? (2 marks)

A device driver is system software that lets the operating system and applications communicate with and control a hardware device such as a monitor, keyboard, mouse or printer.

Q104. What is utility software? Give examples. (2 marks)

Utility software performs specific tasks related to managing and maintaining the computer system, for example disk defragmentation, disk compression, backup and antivirus tools.

Q105. What is recursion? Write the recursive definition of x^n and of the factorial. (3 marks)

A function that calls itself is recursive. It must have a base case that stops the recursion.

  • Power: xn = x * xn-1, base case x0 = 1.
  • Factorial: n! = n * (n-1)!, base case 0! = 1! = 1.
long fact(long n)
{
    if (n <= 1) return 1;       // base case
    return n * fact(n - 1);     // recursive call
}

Recursion is elegant, but every call uses stack memory, so a loop is more efficient.

Q106. In matrix transposition, why do the diagonal elements stay unchanged, and why must only one triangle be swapped? (3 marks)

In the transpose, element [i][j] swaps with element [j][i]. On the diagonal i = j, so the element swaps with itself and does not change. If both triangles are swapped, every pair is swapped twice and the matrix returns to its original form, so only the upper (or lower) triangle should be swapped:

for (int i = 0; i < n; i++)
    for (int j = i + 1; j < n; j++)
    {
        int t = a[i][j];
        a[i][j] = a[j][i];
        a[j][i] = t;
    }

Q107. How is a pointer to an integer declared and given the address of a variable? How is a pointer initialised? (3 marks)

int x = 5;
int *ptr;        // pointer to int
ptr = &x;        // & gives the address of x
int *p2 = NULL;  // or 0: points to nothing

An uninitialised pointer holds a garbage address, so it should always be set to a valid address or NULL.

Q108. What is the difference between the array 'char myName[] = "Ali"' and the pointer 'char *myNamePtr = "Ali"'? (3 marks)

The array name myName is a constant pointer: it always points to the start of its array and cannot be made to point elsewhere (the characters can be changed). myNamePtr is an ordinary pointer variable: it can be assigned another address, but the string literal it points to should not be modified.

Q109. What happens when the array name multi of a two-dimensional array is incremented by 1? What is double dereferencing? (3 marks)

For a 2-D array, multi + 1 moves to the next row (not the next element). To get an element, dereference twice: **multi is multi[0][0] and *(*(multi + i) + j) is the same as multi[i][j].

Q110. What is an array of pointers? What is its advantage over a two-dimensional array? (3 marks)

char *myarray[10]; is an array of 10 pointers to char. Each pointer can point to a string of a different length, so it avoids the wasted space of a fixed-width 2-D char array.

Q111. What is the difference between yptr + 3 and yptr += 3 in the following code and what does (*yptr)++ do? (3 marks)

Assume int x; int *yptr = &x;. *yptr + 3 is only an expression and does not change x. *yptr += 3 adds 3 to x itself. (*yptr)++ increments the value that yptr points to (x); the parentheses are needed because *yptr++ would move the pointer instead.

Q112. Can two pointers be added? What is the purpose of subtracting pointers? (2 marks)

Adding two pointers is not allowed because the sum of two addresses has no meaning. Subtracting two pointers into the same array is allowed and gives the number of elements between them.

Q113. Why is the size of a file (in blocks) often greater than its actual data length? (3 marks)

Disks store files in fixed-size logical blocks, so the last block is usually only partly used. The space occupied by the file is therefore a multiple of the block size and is larger than or equal to the actual number of data bytes.

Q114. How can the actual data length of a file be found with seekg() and tellg()? (3 marks)

ifstream f("data.txt", ios::in);
f.seekg(0, ios::end);          // go to the end of the file
long length = f.tellg();       // position = number of bytes

Q115. What are the roles of seekg() and seekp()? How do they differ? (3 marks)

seekg() moves the get (read) pointer of an input stream, and seekp() moves the put (write) pointer of an output stream. Both take an offset and an origin (ios::beg, ios::cur or ios::end) and are the key to random access in a file.

Q116. Why is it hard to insert data in the middle of a sequential file? What is the merge method? (3 marks)

Overwriting at a position in the middle would destroy the data that follows it. In the merge method the program opens the old file and a new empty file, copies the data up to the insertion point, writes the new data, then copies the rest. It is correct but wasteful in time and space for big files. With constant-length records and seekp(), a record can be updated in place.

Q117. What does isdigit() do and how is it used? (2 marks)

isdigit(c) (in ctype.h) returns true (non-zero) if the character c is a decimal digit '0' to '9', otherwise 0. Example: if (isdigit(ch)) count++;.

Q118. How are characters represented inside the computer? (2 marks)

Each character is stored as a number according to the ASCII code (American Standard Code for Information Interchange), for example 'A' = 65 and 'a' = 97. A char variable takes one byte.

Q119. What caution is needed with read() and write(), and why is sizeof used with them? (3 marks)

read() and write() transfer raw bytes, so you must give the correct number of bytes and make sure the buffer is large enough. sizeof gives the correct byte count for the data type, for example f.write((char*)&n, sizeof(n)); works for an int on any system.

Q120. What is the difference between get() and the >> operator when reading from a file? (3 marks)

>> skips white space (spaces, tabs, newlines) and reads a word. get() reads one character at a time including spaces and newlines, so it is used when every character matters.

Q121. What is getline() used for? Give its syntax. (3 marks)

getline() reads a whole line (up to a delimiter) into a character array in one call, which is faster than reading character by character.

char line[100];
inFile.getline(line, 100);    // reads up to 99 characters or until '\n'

Q122. What are the file opening modes for output files? Give an example of ios::app. (3 marks)

  • ios::out: write; an existing file is overwritten.
  • ios::app: append; data is added at the end of the file.
  • ios::in: read; modes are combined with the bitwise OR operator (|).
ofstream out;
out.open("myFile.txt", ios::app);

Q123. How is the end of a file checked while reading in a loop, and how is a failed open detected? (3 marks)

ifstream in("data.txt");
if (!in)                       // failed to open
{
    cerr << "Cannot open file";
    exit(1);
}
while (in >> x)                // loop stops at end of file
    cout << x << endl;
in.close();

Q124. How can a structure be assigned, initialised and passed to a function? (3 marks)

  • Two variables of the same structure type can be assigned directly: s2 = s1;.
  • Initialisation uses braces: student s1 = {"Ali", "CS201", 19};.
  • A structure can be passed by value (a copy is made) or by reference/pointer (more economical for big structures).

Q125. What is a union and how does its memory allocation work? (3 marks)

A union is declared like a structure, but all members share the same memory. Its size is that of its largest member, and only one member can hold a valid value at a time. For union { int i; char c; } with a 4-byte int, the size is 4 bytes.

Q126. How can XOR be used to swap two numbers without a temporary variable? (3 marks)

a = a ^ b;
b = b ^ a;     // b now holds the old a
a = a ^ b;     // a now holds the old b

Q127. What do the left shift (<<) and right shift (>>) operators do? (3 marks)

<< moves the bits to the left and fills with zeros; each shift multiplies by 2 (5 << 1 = 10). >> moves the bits to the right; each shift divides by 2 (10 >> 1 = 5). Shifting is faster than multiplying or dividing.

Q128. What is a memory leak? What is a dangling pointer? (3 marks)

  • Memory leak: memory taken from the heap (new or malloc) is never released, so it can no longer be used and heap space slowly runs out.
  • Dangling pointer: a pointer that still holds the address of memory that has been freed. Using it gives undefined behaviour, so set it to NULL after freeing.

Q129. What is the purpose of strcmp, strncmp and strlen? (3 marks)

  • strcmp(s1, s2) compares two strings and returns 0 if they are equal, a negative number if s1 < s2 and a positive number if s1 > s2.
  • strncmp(s1, s2, n) compares only the first n characters.
  • strlen(s) returns the number of characters before the null character.

Q130. What does strchr() do? (2 marks)

strchr(s, c) searches the string s for the first occurrence of the character c and returns a pointer to it, or NULL if it is not found.

Short Notes (Key Terms)

#include
A preprocessor directive that inserts the contents of a file into the source file. A system header is written in angle brackets (<iostream.h>) and a user file in double quotes.
Allocation
The process of giving memory space to a variable or object.
Argument
The actual value passed to a function when it is called. It is matched with the function's parameter.
Array
An ordered collection of elements of the same type stored in contiguous memory and accessed by an index that starts from 0.
Assignment
Giving a value to an already existing variable, using the = operator.
Bit
The smallest unit of memory, with the value 0 or 1.
Bool
The C++ keyword used to declare a Boolean variable that holds true or false.
Break
A statement that immediately leaves a loop or a switch statement.
Byte
A group of 8 bits. It is the unit in which memory is usually addressed, and a char takes one byte.
Call by reference
Passing the address of a variable to a function, so the function can change the original value.
Call by value
Passing a copy of a value to a function, so the original variable stays unchanged. It is the default in C/C++.
Case
A label inside a switch statement followed by a constant. The statements after the matching case are executed.
Char
A data type that stores one character, one byte in size.
Comments
Explanatory text in the source code that the compiler ignores, written as // for one line or /* ... */ for many lines.
Compiler
System software that translates the whole source program into machine code and reports errors.
Const
A keyword that makes a variable read-only after it is initialised.
Continue
A statement that skips the rest of the current loop iteration and moves on to the next one.
cout
The standard output stream, used with << to display information on the screen.
Data structure
A way of organising data in memory, such as an array or a structure.
Debugger
A tool that lets a programmer run a program step by step and look at variable values to find errors.
Declaration
A statement that introduces a name and its type to the compiler, such as a variable declaration or a function prototype.
Definition
A declaration that also creates the thing: it reserves memory for a variable or gives the body of a function.
Delete operator
The C++ operator that releases memory obtained with new.
Double
A data type for real numbers with more range and precision than float, usually 8 bytes.
Dynamic memory allocation
Getting memory from the heap while the program is running, using new (or malloc), and releasing it with delete (or free).
Expression statement
A statement made of an expression followed by a semicolon, for example x = 5; or i++;
Global variable
A variable declared outside every function, visible to all functions in the file after its declaration.
Header file
A file with declarations (function prototypes, constants, types) that is included with #include.
Memory leak
Memory that was allocated but never released, so it cannot be reused.
New operator
The C++ operator that allocates memory on the heap and returns its address.
Null pointer
A pointer holding the value NULL (0), meaning it points to nothing.
Reserved word
A word with a fixed meaning in the language (such as int, if, while) that cannot be used as an identifier.
Return value
The value a function sends back to its caller with the return statement.

No comments:

Post a Comment

Please give us your feedback & help us to improve this site.

CS201 Mid Term Papers