Getting ready for the midterm of CS201 (Introduction to Programming)? Here is everything in one place: solved MCQs, subjective questions with answers and short notes and key terms, gathered from past papers and files shared by students. No duplicates and all the answers are checked and verified. Use the tabs above to switch between Objective, Subjective and Short Notes & Key Terms, and tap Show answer only after you have tried the question yourself. Best of luck with your exam!
Part 1: Objective (MCQs)
Q1. How many dimensions does an n-dimensional array have?
- n dimensions
- 2n dimensions
- (n+1) dimensions
- (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 *);?
- func(int &num);
- func(&num);
- func(*num);
- func(num);
Show answer
Answer: (b) func(&num);
Handout reference: Lecture 10, p. 95
Q3. The operators ++ and -- are used to increment or decrement the value of a variable by ______.
- 3
- 2
- 1
- 4
Show answer
Answer: (c) 1
Handout reference: Lecture 7, p. 62
Q4. The loop which is most suitable to be used when the number of iterations is known is called ______.
- for
- while
- do-while
- all looping processes require that the iterations be known
Show answer
Answer: (a) for
Handout reference: Lecture 7, p. 58
Q5. In C/C++, a string constant is enclosed in ______.
- curly braces {}
- parentheses ()
- single quotes ' '
- double quotes " "
Show answer
Answer: (d) double quotes " "
Handout reference: Lecture 3, p. 15
Q6. In order to get the right-most digit of a number, we divide the number by 10 and take ______.
- Its remainder
- Its quotient
- Its divisor
- The number
Show answer
Answer: (a) Its remainder
Handout reference: Lecture 3, p. 21
Q7. What is the correct syntax to declare an array of size 10 of int data type?
- int [10] name;
- name[10] int;
- int name[10];
- int name[];
Show answer
Answer: (c) int name[10];
Handout reference: Lecture 11, p. 99
Q8. How many bytes of memory are occupied by the array 'str'? char str[] = "programming";
- 10
- 11
- 12
- 13
Show answer
Answer: (c) 12
Why: 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.
Handout reference: Lecture 12, p. 112
Q9. When an if statement consists of more than one statement, enclosing these statements in curly braces is ______.
- Not required
- Good programming
- Relevant
- 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?
- 0x22f231
- 0x22f234
- 0x22f226
- 0x22f238
Show answer
Answer: (b) 0x22f234
Why: 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?
- Recursive call
- Base case
- Function parameters
- Local variables
Show answer
Answer: (b) Base case
Why: 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.
Handout reference: Lecture 10, p. 96
Q12. Whenever we use a library function or a predefined object or macro, we need to use a ______.
- source file
- object file
- header file
- exe file
Show answer
Answer: (c) header file
Handout reference: Lecture 9, p. 87
Q13. A switch statement deals with ______ type of data.
- Integer
- Float
- Character
- Both Integer and Character
Show answer
Answer: (d) Both Integer and Character
Handout reference: Lecture 8, p. 67
Q14. Both the compiler and the ______ are used to translate a program into machine language code.
- debugger
- linker
- loader
- interpreter
Show answer
Answer: (d) interpreter
Handout reference: Lecture 2, p. 10
Q15. TWAIN stands for ______.
- Technology With An Interesting Name
- Technology Without An Informative Name
- Technology Without An Interesting Name
- Technology With An Informative Name
Show answer
Answer: (c) Technology Without An Interesting Name
Q16. The parameter passed to the isdigit() function is ______.
- a character variable
- a boolean variable
- an integer variable
- a character string
Show answer
Answer: (a) a character variable
Handout reference: Lecture 17, p. 187
Q17. C++ views each file as a sequential stream of ______.
- Bits
- Bytes
- Numbers
- Words
Show answer
Answer: (b) Bytes
Handout reference: Lecture 19, p. 218
Q18. A structure is a collection of ______ under a single name.
- only functions
- only variables
- both functions and variables
- only data types
Show answer
Answer: (b) only variables
Why: As taught in this course, a structure groups variables (of possibly different types) under one name.
Handout reference: Lecture 20, p. 228
Q19. The default mode for writing into a file using an ofstream object is ______.
- out
- bin
- app
- ate
Show answer
Answer: (a) out
Handout reference: Lecture 19, p. 211
Q20. The memory address of the first element of an array is called ______.
- floor address
- foundation address
- first address
- 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?
- Pointers
- Array index
- Both pointers and array index are better
- 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.
- multiple-if
- switch
- if-else
- else-if
Show answer
Answer: (b) switch
Handout reference: Lecture 8, p. 66
Q23. Which of the following is not a reserved word in C/C++?
- int
- float
- double
- sum
Show answer
Answer: (d) sum
Q24. To access rand(), which library (header file) is required to be included in the program?
- conio.h
- stdio.h
- stdlib.h
- iostream.h
Show answer
Answer: (c) stdlib.h
Handout reference: Lecture 16, p. 178
Q25. What is the highest legal index for the following array? int arr[4];
- 4
- 3
- 2
- 1
Show answer
Answer: (b) 3
Handout reference: Lecture 11, p. 100
Q26. When an array element is passed to a function, it is passed by ______.
- reference
- data type
- value
- data
Show answer
Answer: (c) value
Why: 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).
Handout reference: Lecture 10, p. 92
Q27. While programming, it is good to provide an easy-to-understand and easy-to-use interface; this property is called ______.
- scalability
- usability
- reliability
- sustainability
Show answer
Answer: (b) usability
Q28. A word processor is a type of ______.
- operating system
- application software
- device driver
- utility software
Show answer
Answer: (b) application software
Q29. A 'while' loop may execute ______ or more times.
- three
- zero
- two
- one
Show answer
Answer: (b) zero
Q30. The keyword ______ is used to get some value back from a function.
- return
- break
- continue
- goto
Show answer
Answer: (a) return
Q31. Identify the correct option which is used for calling the function float area(int).
- area(&num);
- area(num);
- area(int num);
- area(*num);
Show answer
Answer: (b) area(num);
Why: 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.
- switch
- break
- continue
- goto
Show answer
Answer: (a) switch
Q33. C is widely known as the development language of the ______ operating system.
- Windows
- Unix
- Mac OS
- Linux
Show answer
Answer: (b) Unix
Handout reference: Lecture 2, p. 11
Q34. The syntax of a union is identical to that of a ______.
- structure
- class
- function
- loop
Show answer
Answer: (a) structure
Handout reference: Lecture 20, p. 241
Q35. The function write() takes ______ as parameter(s).
- String of pointer type
- String of variable lengths, no. of bytes to be read and flags
- Pointer array of characters and a delimiter
- String and no. of bytes to be written
Show answer
Answer: (d) String and no. of bytes to be written
Handout reference: Lecture 19, p. 220
Q36. When the logical operator AND (&&) combines two expressions exp1 and exp2, the result is true:
- When both exp1 and exp2 are true
- When both exp1 and exp2 are false
- When exp1 is true and exp2 is false
- When exp1 is false and exp2 is true
Show answer
Answer: (a) When both exp1 and exp2 are true
Handout reference: Lecture 5, p. 39
Q37. The null character is used to indicate the ______ of a string.
- Start
- End
- Begin
- Middle
Show answer
Answer: (b) End
Handout reference: Lecture 12, p. 112
Q38. Which one of the symbols is used to represent a decision in a flow chart?
- Circle
- Diamond
- Rectangle
- Rounded rectangle (terminator)
Show answer
Answer: (b) Diamond
Why: Shapes are shown as pictures in the source: circle, diamond, rectangle, rounded rectangle.
Handout reference: Lecture 6, p. 50
Q39. In a flow chart, the flow of control is represented by ______.
- Rectangle
- Circle
- Diamond
- Arrow
Show answer
Answer: (d) Arrow
Handout reference: Lecture 5, p. 34
Q40. There can be ______ 'default' statement(s) in any switch structure.
- 1
- 2
- 3
- n
Show answer
Answer: (a) 1
Why: 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) ______.
- Constant Expression
- Boolean Expression
- Primary Expression
- Arithmetic Expression
Show answer
Answer: (b) Boolean Expression
Q42. How many nested loops would be required to manipulate an n-dimensional array?
- n
- n + 1
- n - 1
- 2n
Show answer
Answer: (a) n
Why: 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?
- 0
- -32
- 65531
- -4.0
Show answer
Answer: (d) -4.0
Handout reference: Lecture 3, p. 19
Q44. We should use ______ for clarity and to force the order of evaluation in an expression.
- Brackets []
- parentheses ()
- curly braces {}
- quotation marks " "
Show answer
Answer: (b) parentheses ()
Handout reference: Lecture 3, p. 21
Q45. Which of the following is the starting index of an array in C++?
- 0
- 1
- -1
- 2
Show answer
Answer: (a) 0
Handout reference: Lecture 11, p. 100
Q46. An array is a data structure that stores ______.
- Memory addresses
- Variables
- Data type
- Data
Show answer
Answer: (b) Variables
Why: 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 ______.
- function declaration
- function call
- function definition
- function prototype
Show answer
Answer: (b) function call
Q48. The compiler of the C language is written in ______ language.
- JAVA
- BASIC
- FORTRON
- C
Show answer
Answer: (d) C
Handout reference: Lecture 2, p. 11
Q49. Which one of the following functions is not included in the ctype.h header file?
- isdigit(int c)
- isxdigit(int c)
- tolower(int c)
- getdigit(int c)
Show answer
Answer: (d) getdigit(int c)
Why: 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?
- strchr()
- strstr()
- strtok()
- strlen()
Show answer
Answer: (a) strchr()
Why: 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.
Handout reference: Lecture 17, p. 194
Q51. ______ is the pointer which determines the position in a file from where the next read operation will occur.
- put
- seek
- get
- tell
Show answer
Answer: (c) get
Why: 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?
- * operator
- -> operator
- && operator
- & operator
Show answer
Answer: (a) * operator
Why: The source key marked '&' (the address-of operator). The dereference operator * gives the value a pointer points to.
Handout reference: Lecture 15, p. 159
Q53. In case of single dereferencing, the value of the ______ is the address of the ______.
- pointer, variable
- pointer, constant
- variable, pointer
- constant, pointer
Show answer
Answer: (a) pointer, variable
Handout reference: Lecture 16, p. 174
Q54. The remainder (%) operator is a ______ operator.
- Logical
- Arithmetic
- Relational
- Conditional
Show answer
Answer: (b) Arithmetic
Handout reference: Lecture 3, p. 20
Q55. What will be the output of the following code? int x = 10; cout << "x =" << x;
- 10
- "x=10"
- x=10
- 10=x
Show answer
Answer: (c) x=10
Q56. The purpose of using cout<< is to ______.
- Display information on the screen
- Read the data from keyboard
- Read the data from a file
- Write into a file
Show answer
Answer: (a) Display information on the screen
Handout reference: Lecture 2, p. 14
Q57. ______ executes all the lines before an error and stops at the line which contains the error.
- Interpreter
- Compiler
- Linker
- Debugger
Show answer
Answer: (a) Interpreter
Handout reference: Lecture 2, p. 12
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?
- ptr[0]
- *(ptr+1)
- ptr[1]
- *ptr[0]
Show answer
Answer: (a) ptr[0]
Why: Only ptr[0] reads the first element; *(ptr+1) and ptr[1] give the second element, and *ptr[0] is invalid.
Handout reference: Lecture 15, p. 159
Q59. C is a/an ______ language.
- low level
- object based
- object oriented
- function oriented
Show answer
Answer: (d) function oriented
Handout reference: Lecture 11, p. 99
Q60. The ______ of a function is also known as the signature of the function.
- Definition
- Declaration
- Calling
- Invoking
Show answer
Answer: (b) Declaration
Q61. ______ are very good tools for code reuse.
- operators
- loops
- functions
- variables
Show answer
Answer: (c) functions
Handout reference: Lecture 9, p. 85
Q62. If a break statement is missed in a switch statement then ______.
- compiler will give error
- this may cause a logical error
- no effect on program
- program stops its execution
Show answer
Answer: (b) this may cause a logical error
Handout reference: Lecture 8, p. 68
Q63. A 2D array multi[5][10] can be accessed using the array name as **multi; this technique is called ______.
- Single referencing
- Single dereferencing
- Double referencing
- Double dereferencing
Show answer
Answer: (d) Double dereferencing
Handout reference: Lecture 16, p. 174
Q64. In C/C++, the default command line arguments passed to the main function are ______.
- float argc, char **argv
- int argc, char **argv
- int *argc, char *argv
- int argc, float **argv
Show answer
Answer: (b) int argc, char **argv
Handout reference: Lecture 16, p. 177
Q65. A record is a group of related ______.
- Files
- Bytes
- Fields
- Data
Show answer
Answer: (c) Fields
Why: 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 ______.
- Adding the value of x to the value of y and storing the result in x
- Adding the value of y to the value of x; store the result in y
- Adding the value of x to the value of x; store the result in x
- 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
Why: 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.
Handout reference: Lecture 7, p. 62
Q67. The function seekg() takes ______ parameter(s).
- 0
- 1
- 2
- 3
Show answer
Answer: (c) 2
Q68. In order to get 256 from the number 2568 we divide this number by 10 and take,
- Its remainder
- The number
- Its quotient
- Its divisor
Show answer
Answer: (c) Its quotient
Q69. The correct syntax of do-while loop is,
- (condition ) while; do { statements; };
- { statements; } do-while ();
- while(condition); do { statements; };
- 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?
- double atof(const char *nptr)
- int atoi(const char *nptr)
- char *strcpy ( char *s1, const char *s2)
- 1 and 2 only
Show answer
Answer: (d) 1 and 2 only
Q71. The data type before a function name represents its,
- Return Type
- Function data
- Function arguments
- Function name
Show answer
Answer: (a) Return Type
Q72. Member function tellg() returns the current location of the _ pointer.
- tellptr()
- write()
- seekg()
- get()
Show answer
Answer: (d) get()
Q73. What does 5 | 6 , evaluate to in decimal where ‘|’ is bitwise OR operator?
- 3
- 4
- 5
- 7
Show answer
Answer: (d) 7
Q74. What will be the result of arithmetic expression 6+27/3*3?
- 33
- 45
- 9
- 30
Show answer
Answer: (a) 33
Why: The source key marked 9, but multiplication and division are evaluated left to right: 27/3 = 9, 9*3 = 27, and 6 + 27 = 33.
Q75. What will be the correct syntax for initialization of pointer ptr with string "programming"?
- char ptr = ’programming’ ;
- char *ptr = “programming” ;
- char *ptr = ‘programming’ ;
- *ptr = “programming” ;
Show answer
Answer: (b) char *ptr = “programming” ;
Q76. What will be the result of expression x%= 2, if x = 7?
- x = 1
- x = 3
- x = 7
- x = 2
Show answer
Answer: (a) x = 1
Q77. UNIX has been developed in language.
- JAVA
- B
- C
- FORTRAN
Show answer
Answer: (c) C
Q78. Declaring structures does not mean that memory is allocated.
- True
- False
Show answer
Answer: (a) True
Q79. What is the output of the following statement? int i = 2.5; do { cout i * 2; } while (i > 3 && i < 10);
- 510
- 5
- 48
- error
Show answer
Answer: (d) error
Why: As printed, 'cout i * 2' has no << operator, so the code does not compile.
Q80. The condition in while loop may contain logical expression but not relational expression.
- True
- False
Show answer
Answer: (b) False
Q81. Searching is easier when an array is already sorted
- True
- False
Show answer
Answer: (a) True
Q82. If an array has 100 elements, what is allowable range of subscripts?
- 0 - 99
- 1 - 99
- 0 - 100
- 1 - 100
Show answer
Answer: (a) 0 - 99
Q83. What will be the value of ‘a’ and ‘b’ after executing the following statements? a = 3; b = a++;
- 3, 4
- 4, 4
- 3, 3
- 4, 3
Show answer
Answer: (d) 4, 3
Why: b = a++ first copies the old value of a (3) into b and then increments a, so a = 4 and b = 3.
Q84. Which of the following function returns the size of a string variable?
- strlength()
- stringlen()
- strlen()
- strLength()
Show answer
Answer: (c) strlen()
Q85. What will be the range of numbers generated by function rand () % 9?
- 0 to 9
- 1 to 9
- 0 to 8
- 1 to 8
Show answer
Answer: (c) 0 to 8
Q86. Computer can understand only machine language code.
- True
- False
Show answer
Answer: (a) True
Q87. Which of the following header file include string conversion functions?
- string.h
- stdlib.h
- ctype.h
- sconvert.h
Show answer
Answer: (b) stdlib.h
Q88. A precise sequence of steps to solve a problem is called
- Statement
- Program
- Utility
- Routine
Show answer
Answer: (b) Program
Q89. The Compiler of C language is written in
- Java Language
- UNIX
- FORTRON Language
- C Language
Show answer
Answer: (d) C Language
Q90. Initialization of variable at the time of definition is,
- Must
- Necessary
- Good Programming
- None of the given options
Show answer
Answer: (c) Good Programming
Q91. In if structure the block of statements is executed only,
- When the condition is false
- When it contain arithmetic operators
- When it contain logical operators
- When the condition is true
Show answer
Answer: (d) When the condition is true
Q92. Dealing with structures and functions passing by reference is the most economical method
- True
- False
Show answer
Answer: (a) True
Q93. Pointer is a variable which store,
- Data
- Memory Address
- Data Type
- Values
Show answer
Answer: (b) Memory Address
Q94. Preprocessor program perform its function before phase takes place.
- Editing
- Linking
- Compiling
- Loading
Show answer
Answer: (c) Compiling
Q95. Which of the following can not be a variable name?
- area
- _area
- 10area
- area2
Show answer
Answer: (c) 10area
Q96. Which character is inserted at the end of string to indicate the end of string?
- new line
- tab
- null
- carriage return
Show answer
Answer: (c) null
Q97. Which of the following header file defines the rand() function?
- iostream.h
- conio.h
- stdlib.h
- stdio.h
Show answer
Answer: (c) stdlib.h
Handout reference: Lecture 11, p. 108
Q98. Commenting the code
- Makes a program easy to understand for others.
- Make programs heavy, i.e. more space is needed for executable.
- Makes it difficult to compile
- All of the given options.
Show answer
Answer: (a) Makes a program easy to understand for others.
Q99. What's wrong with this for loop? for (int k = 2, k <=12, k++)
- the increment should always be ++k
- the variable must always be the letter i when using a for loop
- there should be a semicolon at the end of the statement
- the commas should be semicolons
Show answer
Answer: (d) the commas should be semicolons
Q100. For which array, the size of the array should be one more than the number of elements in an array?
- int
- double
- float
- char
Show answer
Answer: (d) char
Q101. The function of cin is
- To display message
- To read data from keyboard
- To display output on the screen
- To send data to printer
Show answer
Answer: (b) To read data from keyboard
Q102. In C/C++ language the header file which is used to perform useful task and manipulation of character data is
- cplext.h
- ctype.h
- stdio.h
- delay.h
Show answer
Answer: (b) ctype.h
Q103. How many parameter(s) function getline() takes?
- 0
- 1
- 2
- 3
Show answer
Answer: (d) 3
Q104. 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; }
- any number other than 1 or 2
- only 0
- only 1
- only 2
Show answer
Answer: (a) any number other than 1 or 2
Why: 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.
Q105. Each pass through a loop is called a/an
- enumeration
- Iteration
- culmination
- pass through
Show answer
Answer: (b) Iteration
Q106. A continue statement causes execution to skip to
- the return 0; statement
- the first statement after the loop
- the statements following the continue statement
- the next iteration of the loop
Show answer
Answer: (d) the next iteration of the loop
Q107. Consider the following code segment. What will the following code segment display? int main(){ int age[10] = {0}; cout << age ; }
- Values of all elements of array
- Value of first element of array
- Starting address of array
- Address of last array element
Show answer
Answer: (c) Starting address of array
Why: 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.
Q108. How many bytes will the pointer intPtr of type int move in the following statement? intPtr += 3 ;
- 3 bytes
- 6 bytes
- 12 bytes
- 24 bytes
Show answer
Answer: (c) 12 bytes
Q109. The statement interrupts the flow of control.
- switch
- continue
- goto
- break
Show answer
Answer: (d) break
Q110. Analysis is the --------------- step in designing a program
- Last
- Middle
- Post Design
- First
Show answer
Answer: (d) First
Q111. Paying attention to detail in designing a program is
- Time consuming
- Redundant
- Necessary
- Somewhat Good
Show answer
Answer: (c) Necessary
Q112. There are mainly ------------------ types of software
- Two
- Three
- Four
- Five
Show answer
Answer: (a) Two
Q113. In C/C++ the #include is called,
- Header file
- Preprocessor Directive
- Statement
- Function
Show answer
Answer: (b) Preprocessor Directive
Q114. && is ------------------operator.
- An arithmetic
- Logical
- Relational
- Unary
Show answer
Answer: (b) Logical
Q115. In flow chart, the symbol used for decision making is,
- Rectangle
- Circle
- Arrow
- Diamond
Show answer
Answer: (d) Diamond
Q116. If the elements of an array are already sorted then the useful search algorithm is,
- Linear search
- Binary search
- Quick search
- Random search
Show answer
Answer: (b) Binary search
Q117. The address operator (&) can be used with,
- Statement
- Expression
- Variable
- Constant
Show answer
Answer: (c) Variable
Q118. When a pointer is incremented, it actually jumps the number of memory addresses
- According to data type
- 1 byte exactly
- 1 bit exactly
- A pointer variable can not be incremented
Show answer
Answer: (a) According to data type
Q119. 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.
- (i) and (ii) only
- (i) and (iii) only
- (ii) and (iii) only
- (ii) and (iv) only
Show answer
Answer: (b) (i) and (iii) only
Q120. The return type of a function that do not return any value must be
- int
- void
- double
- float
Show answer
Answer: (b) void
Q121. Which of the following is an extension of header file?
- .exe
- .txt
- .h
- .c
Show answer
Answer: (c) .h
Q122. When we declare a multidimensional array the compiler store the elements of multidimensional array in the form of,
- Columns
- Rows
- Contiguous memory location
- Matrix
Show answer
Answer: (c) Contiguous memory location
Q123. In C/C++ the string constant is enclosed
- In curly braces
- In small braces
- In single quotes
- In double quotes
Show answer
Answer: (d) In double quotes
Q124. The size of int data type is
- 1 bytes
- 2 bytes
- 3 bytes
- 4 bytes
Show answer
Answer: (d) 4 bytes
Q125. In Flow chart process is represented by
- Rectangle
- Arrow symbol
- Oval
- Circle
Show answer
Answer: (a) Rectangle
Q126. When we are using const keyword with a variable x then initializing it at the time of declaration is,
- Must
- Optional
- Not necessary
- A syntax error
Show answer
Answer: (a) Must
Q127. 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?
- m[2][3] = 5 ;
- m[3][2] = 5 ;
- m[1][2] = 5 ;
- m[2][3] = ‘5’;
Show answer
Answer: (c) m[1][2] = 5 ;
Why: 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.
Handout reference: Lecture 12, p. 121
Q128. How many total elements must be in two-dimensional array of 3 rows and 2 columns?
- 4
- 5
- 6
- 7
Show answer
Answer: (c) 6
Q129. Which of the following is the correct statement for the following declaration? const int *ptr.
- ptr is a constant pointer
- ptr is constant integer pointer
- ptr is a constant pointer to int
- ptr is a pointer to const int
Show answer
Answer: (d) ptr is a pointer to const int
Q130. 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) ;
- 3
- 9
- 12
- 2
Show answer
Answer: (a) 3
Why: ptr2 - ptr1 counts elements between the pointers: index 4 minus index 1 = 3. The source key said 2.
Q131. What will be the correct syntax to assign an array named arr of 5 elements to a pointer ptr?
- *ptr = arr ;
- ptr = arr ;
- *ptr = arr[5] ;
- ptr = arr[5] ;
Show answer
Answer: (b) ptr = arr ;
Q132. The variables having a name, type and size are just like empty boxes.
- False
- True
Show answer
Answer: (b) True
Q133. Most efficient method of dealing with structure variables is to define the structure globally
- True
- False
Show answer
Answer: (a) True
Q134. Compiler is a ______.
- System software
- Application software
- Driver
- Editor
Show answer
Answer: (a) System software
Q135. If Num is an integer variable then Num++ means ______.
- Add 1 two times with Num
- Add 1 with Num
- Add 2 with Num
- Subtract 2 from Num
Show answer
Answer: (b) Add 1 with Num
Q136. For one byte there are ______ combinations of values that can be stored in a computer.
- 2^6
- 2^7
- 2^8
- 2^4
Show answer
Answer: (c) 2^8
Why: One byte = 8 bits, and n bits can hold 2^n different values, so 2^8 = 256.
Q137. The default case in a switch statement is ______.
- Must
- Optional
- Syntax error
- Necessary
Show answer
Answer: (b) Optional
Q138. When the break statement is encountered in a switch statement, it ______.
- Stops the entire program
- Stops the execution of the current statement
- Exits from the switch statement
- None of the given options
Show answer
Answer: (c) Exits from the switch statement
Q139. What will be the correct syntax to access the value of the fourth element of an array using pointer ptr?
- ptr[3]
- (ptr+3)
- *(ptr+3)
- Both 1 and 3
Show answer
Answer: (d) Both 1 and 3
Why: ptr[3] and *(ptr+3) are equivalent. (ptr+3) without * is only an address.
Q140. Which values does C++ use to represent true and false?
- 1 and 0
- 1 and -1
- 11 and 00
- Any numerical value
Show answer
Answer: (a) 1 and 0
Q141. If a variable is passed by value to a function and the function changes that variable, then it ______.
- Does not affect the original variable
- Affects the original variable
- Causes a syntax error
- None of the given options
Show answer
Answer: (a) Does not affect the original variable
Q142. Loops are ______ structures.
- Decision
- Repetition
- Sequential
- Hierarchical
Show answer
Answer: (b) Repetition
Q143. Switch statement deals with ______.
- Integer data only
- float data only
- character data only
- Integer and character data
Show answer
Answer: (d) Integer and character data
Handout reference: Lecture 8, p. 67
Q144. If it is required to copy an array to another array, then ______.
- Both arrays must be of the same size and data type
- Both arrays may be of different size
- Both arrays may be of different data type
- Both arrays may be of different size and type
Show answer
Answer: (a) Both arrays must be of the same size and data type
Q145. The precedence of * (dereference) is higher than the dot operator.
- True
- False
Show answer
Answer: (b) False
Why: The dot (member access) operator has higher precedence than the unary * operator.
Q146. Pointers work by pointing to a data type, which can be of the form ______.
- Integer only
- double only
- character only
- All of the given options
Show answer
Answer: (d) All of the given options
Q147. Which looping process checks the test condition at the end of the loop?
- for
- while
- do while
- no looping process checks the test condition at the end
Show answer
Answer: (c) do while
Q148. What is the correct syntax for the statement: ptr is a constant pointer to integer?
- const int *ptr;
- const *int ptr;
- int const *ptr;
- int *const ptr;
Show answer
Answer: (d) int *const ptr;
Why: int *const ptr means the pointer itself is constant. const int *ptr (or int const *ptr) is a pointer to a constant int.
Q149. A function must always return a value.
- True
- False
Show answer
Answer: (b) False
Why: A function with return type void returns nothing.
Q150. The assignment operator is used for ______.
- calculation
- reading
- assigning values to variables
- None of the given options.
Show answer
Answer: (c) assigning values to variables
Q151. Which of the following functions are included in the ctype.h header file?
- isdigit(int c)
- isxdigit(int c)
- tolower(int c)
- All of the above
Show answer
Answer: (d) All of the above
Q152. Both the compiler and the interpreter are used to translate a program into machine language code.
- True
- False
Show answer
Answer: (a) True
Q153. A missing semicolon ';' at the end of a C++ statement is a ______.
- Logical error
- Syntax error
- Runtime error
- None of the given options
Show answer
Answer: (b) Syntax error
Q154. A switch statement is an alternative to the ______ statement.
- multiple if
- continue
- break
- goto
Show answer
Answer: (a) multiple if
Q155. An array is passed by value to a function by default.
- True
- False
Show answer
Answer: (b) False
Why: Arrays are passed by reference: the function receives the address of the first element.
Q156. Which of the following is the correct function call for an array named student of 10 elements as a parameter?
- addRecord(student[]);
- addRecord(student);
- addRecord(student[10]);
- addRecord(*student);
Show answer
Answer: (b) addRecord(student);
Q157. What will be the output of the following code? main(){ int x = 5; { int x = 4; cout << x; } cout << x; }
- 5, 5
- 4, 4
- 4, 5
- 5, 4
Show answer
Answer: (c) 4, 5
Why: The inner block's own x (4) is printed first, then the outer x (5). The source code omits the << operator and semicolons.
Q158. The object ______ may be used for both file input and file output.
- fstream
- ifstream
- ofstream
- none of the given options
Show answer
Answer: (a) fstream
Q159. union intorDouble { int ival; double charvar; }; What is the value of size = sizeof(VAZ) if int occupies 4 bytes and double occupies 8 bytes?
- 2
- 4
- 8
- 12
Show answer
Answer: (c) 8
Why: A union is as large as its largest member, so sizeof is 8.
Q160. C language was developed by ______.
- Bill Gates
- Robert Lafore
- Dennis Ritchie
- Deitel & Deitel
Show answer
Answer: (c) Dennis Ritchie
Q161. The name of an array represents the address of the first element of the array.
- True
- False
Show answer
Answer: (a) True
Q162. When an identifier is declared with the keyword const then ______.
- Its value can be changed during execution
- Its value cannot be changed
- Its value can be changed with an arithmetic operator
- Its value can be overwritten
Show answer
Answer: (b) Its value cannot be changed
Q163. In C/C++ if we define an array of size eight, int Arr[8]; then the last element is stored at ______.
- Arr[0]
- Arr[8]
- Arr[7]
- Arr[-1]
Show answer
Answer: (c) Arr[7]
Q164. A do-while loop executes at least ______.
- Zero times
- One time
- Two times
- N times
Show answer
Answer: (b) One time
Q165. +=, *=, /=, etc. are called ______.
- Assignment operators
- Logical operators
- Compound assignment operators
- Unary operators
Show answer
Answer: (c) Compound assignment operators
Why: Both 'Assignment operators' and 'Compound assignment operators' describe them loosely; the course term for these is compound assignment operators.
Q166. Compilers and interpreters also belong to the System Software category.
- True
- False
Show answer
Answer: (a) True
Q167. Editors are used to compile the code.
- True
- False
Show answer
Answer: (b) False
Why: Compilers compile source code; editors are only used to write it.
Q168. Application Softwares are use to
- Type letters
- Control computer hardware
- Solve end user problems
- Develop Graphics
Show answer
Answer: (c) Solve end user problems
Q169. Computer can do,
- More than what we tell it
- Less then what we tell it
- Like human being
- Exactly what we tell it
Show answer
Answer: (d) Exactly what we tell it
Q170. we can control our program while it is running by using
- Debugger
- Linker
- Loader
- Editor
Show answer
Answer: (a) Debugger
Q171. The remainder (%) operator is,
- An arithmetic operator
- A logical operator
- A relational operator
- A division operator
Show answer
Answer: (a) An arithmetic operator
Q172. int x = 2 * 3 + 4 * 5; What value will x contain in the sample code above?
- 22
- 26
- 46
- 50
Show answer
Answer: (b) 26
Q173. What is the correct value to return to the operating system upon the successful completion of a program?
- -1
- 1
- 0
- Programs do not return a value.
Show answer
Answer: (c) 0
Q174. What is the only function all C++ programs must contain?
- start()
- system()
- main()
- program()
Show answer
Answer: (c) main()
Q175. What punctuation ends most lines of C++ code?
- (dot)
- (semi-colon)
- (colon)
- (single quote)
Show answer
Answer: (b) (semi-colon)
Q176. Which of the following is a correct comment?
- */ Comments */
- ** Comment **
- /* Comment */
- { Comment }
Show answer
Answer: (c) /* Comment */
Q177. Which of the following is not a correct variable type?
- float
- real
- int
- double
Show answer
Answer: (b) real
Q178. Which of the following is the correct operator to compare two variables?
- :=
- =
- equal
- ==
Show answer
Answer: (d) ==
Q179. Identify the correct statement
- Programmer can use comments to include short explanations within the source code itself.
- All lines beginning with two slash signs are considered comments.
- Comments very important effect on the behavior of the program
- both
Show answer
Answer: (d) both
Why: Both statements are true, so 'both' is correct. The source key marked only the second statement.
Q180. There is a unique function in C++ program by where all C++ programs start their execution
- Start()
- Begin()
- Main()
- Output()
Show answer
Answer: (c) Main()
Q181. Every statement in C++ program should end with
- A full stop (.)
- A Comma (,)
- A Semicolon (;)
- A colon (:)
Show answer
Answer: (c) A Semicolon (;)
Q182. A variable is/are
- String that varies during program execution
- A portion of memory to store a value
- Those numbers that are frequently required in programs
- None of these
Show answer
Answer: (b) A portion of memory to store a value
Why: The source key marked 'numbers frequently required in programs' (that describes constants). A variable is a named portion of memory that stores a value.
Q183. The value of 2*15/3*7+3*2 is
- 146
- 76
- 8
- 70
Show answer
Answer: (b) 76
Q184. The size of a double variable is
- 2 bytes
- 4 bytes
- 8 bytes
- 10 bytes
Show answer
Answer: (c) 8 bytes
Q185. Which of the following can not be used as identifiers?
- Letters
- Digits
- Underscores
- Spaces
Show answer
Answer: (d) Spaces
Q186. Is the result of 'number = number / 10;' equal to the result of 'number = number % 10;'?
- True
- False
Show answer
Answer: (b) False
Q187. int x,y =10; cout << x << endl; The value of the x will be in the above code
- 0
- 10
- unknown Value
- -1
Show answer
Answer: (c) unknown Value
Q188. Which of the following is the boolean operator for logical-and?
- &
- &&
- |
- |&
Show answer
Answer: (b) &&
Q189. Evaluate !(1 && !(0 || 1)).
- TRUE
- FALSE
- Unevaluatable
- None Of The Above
Show answer
Answer: (a) TRUE
Q190. Which one of the following operators is a unary operator?
- OR ( || )
- AND ( && )
- XOR ( ^ )
- Logical NOT ( ! )
Show answer
Answer: (d) Logical NOT ( ! )
Q191. Which of the following shows the correct syntax for an if statement?
- if expression
- if{ expression
- if( expression)
- expression if
Show answer
Answer: (c) if( expression)
Q192. Loader transfers the executable code from main memory to hard disk.
- TRUE
- FALSE
Show answer
Answer: (b) FALSE
Q193. What is the final value of x when the code int x; for(x=0; x < 10; x++) {} is run?
- 10
- 9
- 0
- 8
Show answer
Answer: (a) 10
Q194. When does the code block following while(x< 100) execute?
- When x is less than one hundred
- When x is greater than one hundred
- When x is equal to one hundred
- While it wishes
Show answer
Answer: (a) When x is less than one hundred
Why: The source key said 'greater than one hundred'. while(x<100) runs the block while x is less than 100.
Q195. Which is not a loop structure?
- For
- Do while
- While
- Repeat Until
Show answer
Answer: (d) Repeat Until
Q196. for (int n=10; n >0; n++) { cout << n << ", "; } How many Time Loop will run
- 100
- Infinite Time
- 1000
- 10000000
Show answer
Answer: (b) Infinite Time
Q197. How many times is a do while loop guaranteed to loop?
- 0
- Variable
- Infinitely
- 1
Show answer
Answer: (d) 1
Q198. x = x + 4 ; Is Equal to
- x += 4 ;
- x =+ 4 ;
- x == 4 ;
- x =! 4 ;
Show answer
Answer: (a) x += 4 ;
Q199. The first expression in a for loop is
- The test expression.
- The step value of the loop.
- The first value of our counter variable.
- None of the above.
Show answer
Answer: (c) The first value of our counter variable.
Q200. What is the continue statement used for ?
- To continue to the next line of code.
- To stop the current iteration and begin the next iteration from the beginning.
- As an alternative to the else statement.
- None of the above.
Show answer
Answer: (b) To stop the current iteration and begin the next iteration from the beginning.
Q201. What is required to avoid falling through from one case to the next?
- end;
- break;
- Stop;
- A semicolon.
Show answer
Answer: (b) break;
Q202. What keyword covers unhandled possibilities in switch case?
- all
- contingency
- default
- other
Show answer
Answer: (c) default
Q203. 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"; }
- One
- Zero
- Hello World
- ZeroHello World
Show answer
Answer: (d) ZeroHello World
Q204. Which of the following is true?
- 1
- -1
- 0.1
- All of the above
Show answer
Answer: (d) All of the above
Why: All of the values 1, -1 and 0.1 are non-zero, so each is treated as true. The source key marked only '1'.
Q205. Every function in C++ are followed by
- Parameters
- Parenthesis
- Curly braces
- None of these
Show answer
Answer: (b) Parenthesis
Q206. Which is not a proper prototype?
- int funct(char x, char y);
- double funct(char x)
- void funct();
- char x();
Show answer
Answer: (b) double funct(char x)
Q207. What is the return type of the function with prototype: " int func(char x, float v, double t); "
- char
- int
- float
- double
Show answer
Answer: (b) int
Q208. Which of the following is a valid function call (assuming the function exists)?
- funct;
- funct x, y;
- funct();
- int funct();
Show answer
Answer: (c) funct();
Q209. Which of the following is a complete function?
- int funct();
- int funct(int x) {return x=x+1;}
- void funct(int) {cout&tl; < "Hello"}
- void funct(x) {cout << "Hello"}
Show answer
Answer: (b) int funct(int x) {return x=x+1;}
Q210. A function prototypes are useful
- Because they tell the compiler that a function is declared later.
- Because they make the program more readable.
- Because they allow the programmer to see a quick list of functions in the program along with the arguments for each function.
- All of the above.
Show answer
Answer: (d) All of the above.
Q211. A function that calls itself is known as
- Iterative function
- Inline function
- Recursive function
- main ()
Show answer
Answer: (c) Recursive function
Q212. A preprocessor directive is identified by symbol
- #
- {
- (
- ~
Show answer
Answer: (a) #
Q213. When a call to function statement is encountered,
- The control is transfer to its Prototype
- The control is transfer to its definition
- The compiler stop execution of whole program
- The program hangs
Show answer
Answer: (b) The control is transfer to its definition
Why: A call transfers control to the function's definition (its body), not to its prototype. The source key was wrong.
Q214. The directives for the preprocessors begin with
- Less than symbol (< )
- Ampersand symbol (&)
- Two Slashes (//)
- Number Sign (#)
Show answer
Answer: (d) Number Sign (#)
Why: Preprocessor directives begin with the number sign (#). Two slashes start a comment. The source key was wrong.
Q215. The file iostream includes
- The declarations of the basic standard input-output library.
- The streams of includes and outputs of program effect.
- Both of these
- None of these
Show answer
Answer: (a) The declarations of the basic standard input-output library.
Q216. Which of the following is false?
- Cout represents the standard output stream in c++.
- Cout is declared in the iostream standard file
- Cout is declared within the std namespace
- None of above
Show answer
Answer: (d) None of above
Q217. If the statements int j,k; j = 123; k= 234; int* q, * r; cout<< *q<< ' '<< *r; are executed, what will be displayed?
- The addresses of q and r
- The addresses of j and k
- 132 , 234
- garbage values
Show answer
Answer: (d) garbage values
Q218. Which of the following correctly declares an array?
- int anarray[10];
- int anarray;
- anarray{10};
- array anarray[10];
Show answer
Answer: (a) int anarray[10];
Q219. Which of the following correctly accesses the seventh element stored in foo, an array with 100 elements?
- foo[6];
- foo[7];
- foo(7);
- foo;
Show answer
Answer: (a) foo[6];
Why: Indexing starts at 0, so the seventh element is foo[6]. The source key said foo[7].
Q220. Consider the following statement: int age [ ] = { 0, 2, 1, 3, 4, 5, 6, 7, 8, 9 }; Array Length is
- 10
- 11
- 9
- 0
Show answer
Answer: (a) 10
Q221. c[ 3 ] = 33; by this Code we are assigning the value to
- 3rd element
- 4th element
- 1st element
- None of the Given
Show answer
Answer: (b) 4th element
Q222. for (i = 0; i < 10 ; i ++) { b[i] = a[i]; } by given loop we are
- Deleting the two Arrays
- Comparing the two Arrays
- Copying the two arrays
- Doing Nothing
Show answer
Answer: (c) Copying the two arrays
Q223. 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
- 6 Time
- 5 Time
- 4 Time
- 0 Time
Show answer
Answer: (a) 6 Time
Q224. Given that #define sum(a,b) a+b what is the value of: sum(3+1,2);
- 18
- 6
- 30
- 5*6
Show answer
Answer: (b) 6
Q225. Because of variable scope
- Variables created in a function cannot be used another function.
- Variables created in a function can be used in another function.
- Variables created in a function can only be used in the main function
- None of the above.
Show answer
Answer: (a) Variables created in a function cannot be used another function.
Q226. void allocateme(int* p){ p = new int; *p = 2; } int main(){ int i = 1; allocateme(&i); std::cout<< i; return 0; } What is displayed?
- Outputs '1'
- Outputs '2'
- Outputs some rubbish value
- Will not compile
Show answer
Answer: (a) Outputs '1'
Q227. 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?
- 3
- 5
- 7
- 4
Show answer
Answer: (d) 4
Q228. An array is also called
- an array variable
- array declaration
- struct
- constant pointer
Show answer
Answer: (d) constant pointer
Q229. Which of the following is the proper declaration of a pointer?
- int x;
- int &x;
- ptr x;
- int *x;
Show answer
Answer: (d) int *x;
Q230. Which of the following gives the memory address of integer variable a (int a;)?
- &a;
- *a;
- address(a);
- a;
Show answer
Answer: (a) &a;
Q231. Which of the following is the proper Operator to allocate memory?
- new
- malloc
- create
- value
Show answer
Answer: (a) new
Q232. Which of the following is the proper keyword to deallocate memory?
- free
- delete
- clear
- remove
Show answer
Answer: (b) delete
Q233. When we are calling function i.e. swap(&x, &y); then it is a call by
- Reference
- Value
- Name
- Nick Name
Show answer
Answer: (a) Reference
Q234. Which symbol is used to declare a pointer ?
- &
- @
- *
- $
Show answer
Answer: (c) *
Q235. In the given code int y[10]; int *x ; x= y; y is giving
- Address
- Whole Array Address
- Address of the first element of the array
- Error
Show answer
Answer: (c) Address of the first element of the array
Q236. Adding to a pointer that points to an array will
- Cause an error.
- Increase the value of the element that the pointer is pointing to.
- Cause the pointer to point to the next element in the array.
- None of the above.
Show answer
Answer: (c) Cause the pointer to point to the next element in the array.
Q237. Which one of the following operators is a unary operator?
- OR ( || )
- AND ( &&)
- XOR ( ^ )
- Complement operator ( ~ )
Show answer
Answer: (d) Complement operator ( ~ )
Q238. The statement i++; is equivalent to
- i = i + i;
- i = i + 1;
- i = i - 1;
- i --;
Show answer
Answer: (b) i = i + 1;
Q239. A variable which is defined inside a function is called
- Automatic variable
- Global variable
- Functional variable
- None of the given option
Show answer
Answer: (a) Automatic variable
Why: A variable defined inside a function is a local (automatic) variable. Global variables are defined outside every function. The source key was wrong.
Q240. Which of the following is a two-dimensional array?
- array anarray[20][20];
- int anarray[20][20];
- int array[20, 20];
- char array[20];
Show answer
Answer: (b) int anarray[20][20];
Q241. An array of pointers is the same as .
- pointers to pointers.
- pointers to Arrray
- null
- None of the Given
Show answer
Answer: (a) pointers to pointers.
Q242. Pointers may be like any other data type.
- char
- arrayed (stored in an array)
- int
- float
Show answer
Answer: (b) arrayed (stored in an array)
Q243. In C/C++ language when an array is passed to a function then by default its passing Mechanism is,
- Call by value
- It depends on type of array
- Call by Reference
- It depends on the return type of function.
Show answer
Answer: (c) Call by Reference
Q244. int isdigit( int c ) Returns true if c is a
- char
- int
- digit
- None of the Given
Show answer
Answer: (c) digit
Q245. int isupper( int c ) Returns true if c is a
- uppercase letter
- lowercase letter
- int
- float
Show answer
Answer: (a) uppercase letter
Q246. double atof( const char *nPtr ) Converts the string nPtr to
- double.
- int
- char
- float
Show answer
Answer: (a) double.
Q247. The basic steps of file handling are:
- Open the file, Read and write, Close the file
- Read, Close the file, Open the file
- Open the file, Close the file, write
- Non of the Given
Show answer
Answer: (a) Open the file, Read and write, Close the file
Q248. ofstream outFile; char outputFileName[] = "myFileOut.txt"; char ouputText[100] = "Welcome to VU"; outFile.open(outputFileName); at the end of the code
- file is opened for Writing
- file is opened for reading
- file is not opened
- file is closed
Show answer
Answer: (a) file is opened for Writing
Q249. If we open a file stream myfile for reading, what will give us the current position of the file pointer?
- tellg()
- tellp()
- seekg()
- seekp()
Show answer
Answer: (a) tellg()
Q250. Which of the following classes handlers file input?
- ofstream
- ifstream
- instream
- inputfile
Show answer
Answer: (b) ifstream
Q251. By writing: aFile. seekg (10L, ios::beg) We are asking to move 10 bytes
- back from the End
- forward from the begining
- forward from the Currant Position
- None of the above.
Show answer
Answer: (b) forward from the begining
Q252. we will call tellg () to give the current position in number. This number is the actual data bytes inside the file.
- int
- short
- long
- double
Show answer
Answer: (c) long
Q253. will return the number of bytes reserved for a variable or data type.
- sizeof operator
- free operator
- void pointer
- new operator
Show answer
Answer: (a) sizeof operator
Q254. A member is a
- Variable in a structure.
- Structure's datatype.
- Pointer to a structure.
- None of the above.
Show answer
Answer: (a) Variable in a structure.
Q255. Which of the following is a properly defined struct?
- struct {int a;}
- struct a_struct {int a;}
- struct a_struct int a;
- struct a_struct {int a;};
Show answer
Answer: (d) struct a_struct {int a;};
Q256. Using structures we can declare:
- Simple variables, Pointers and Arrays of structure
- Simple variables
- Pointers and Arrays of structure
- Nothing
Show answer
Answer: (a) Simple variables, Pointers and Arrays of structure
Q257. During compilation compiler looks for the and process it first
- source code
- object code
- built in functions
- preprocessor directives
Show answer
Answer: (d) preprocessor directives
Q258. 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?
- array[2][3] = 6;
- array[3][4] = 6;
- array[2][4] = 6;
- array[4][3] = 6;
Show answer
Answer: (a) array[2][3] = 6;
Why: 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.
Q259. What is the purpose of the preprocessor directive #include <iostream.h> in the first C program?
- To define the main function
- To include a library for input-output streams
- To declare variables
- To link object code with libraries
Show answer
Answer: (b) To include a library for input-output streams
Q260. Why is the name "main" considered special in a C program?
- It is the only function allowed in a C program
- It is the last function executed in a C program
- It is the first function run when the program is used
- It is a reserved keyword
Show answer
Answer: (c) It is the first function run when the program is used
Q261. In C programming, what does the "cout" represent?
- Input stream
- Output stream
- Data type
- Main function
Show answer
Answer: (b) Output stream
Q262. What is the primary purpose of the "int" data type in C?
- To store whole numbers (integers)
- To store decimal numbers
- To store character values
- To declare variables
Show answer
Answer: (a) To store whole numbers (integers)
Q263. What does the statement "X = X + 1" achieve in C language?
- Subtraction operation
- Multiplication operation
- Division operation
- Incrementing the value of the variable by one
Show answer
Answer: (d) Incrementing the value of the variable by one
Q264. What is the purpose of the "iostream.h" file in C++?
- To declare variables
- To define the main function
- To include a library for input-output streams
- To link object code with libraries
Show answer
Answer: (c) To include a library for input-output streams
Q265. What does the curly bracket ({ }) signify in C programming?
- A syntax error
- The end of the program
- The beginning and end of a block of code
- A comment
Show answer
Answer: (c) The beginning and end of a block of code
Q266. Why is it recommended to avoid starting a variable name with an underscore (_) in C?
- Underscores are reserved keywords in C
- It may cause a syntax error
- It conflicts with library variable names
- Variables starting with underscores cannot be used in assignments
Show answer
Answer: (c) It conflicts with library variable names
Q267. What is the role of the linker in the compilation process?
- To process the code
- To create object code
- To link object code with libraries
- To put the program in memory
Show answer
Answer: (c) To link object code with libraries
Q268. Which part of the program is run first when a C program is executed?
- Linker
- Main function
- Preprocessor
- Compiler
Show answer
Answer: (b) Main function
Q269. What does the statement "cout << "Welcome to Virtual University of Pakistan";" do?
- Declares a variable named cout
- Prints the message to the screen using the cout stream
- Initializes the variable cout with a value
- Compares cout with a string
Show answer
Answer: (b) Prints the message to the screen using the cout stream
Q270. Why is it necessary to use the semicolon (;) at the end of C statements?
- It indicates the end of the program
- It is a syntax error if omitted
- It separates different blocks of code
- It increases the execution speed of the program
Show answer
Answer: (b) It is a syntax error if omitted
Q271. What is the function of the loader in C programming?
- To process the code
- To create object code
- To link object code with libraries
- To put the program in memory
Show answer
Answer: (d) To put the program in memory
Q272. What is the purpose of the "include" keyword in C programming?
- To define the main function
- To include external files or libraries
- To declare variables
- To link object code with libraries
Show answer
Answer: (b) To include external files or libraries
Q273. What is the purpose of the semicolon (;) in C programming?
- Signify the beginning of a statement
- Indicate the end of a statement
- Separate variables in a declaration
- Represent a mathematical operation
Show answer
Answer: (b) Indicate the end of a statement
Q274. What does the statement "z = x + y;" do in C programming?
- Assigns the value of x to z
- Adds the values of x and y and assigns the result to z
- Multiplies the values of x and y and assigns the result to z
- 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
Q275. What is the purpose of the "short" data type in C?
- To store large whole numbers
- To store real numbers
- To store small whole numbers
- To store characters
Show answer
Answer: (c) To store small whole numbers
Q276. How many bytes does the "short" data type occupy in memory?
- 1 byte
- 2 bytes
- 4 bytes
- 8 bytes
Show answer
Answer: (b) 2 bytes
Q277. When dealing with very large whole numbers in C, which data type is recommended?
- int
- short
- long
- double
Show answer
Answer: (c) long
Q278. What does the modulus operator (%) do in C arithmetic operations?
- Adds two numbers
- Multiplies two numbers
- Returns the remainder after division
- Divides two numbers and returns the quotient
Show answer
Answer: (c) Returns the remainder after division
Q279. How is the result of 10 + 10 * 5 evaluated in C?
- 60
- 100
- 50
- 25
Show answer
Answer: (a) 60
Q280. What is the purpose of using parentheses in C arithmetic expressions?
- They are used for multiplication
- They force the evaluation order
- They indicate the end of a statement
- They are used for addition
Show answer
Answer: (b) They force the evaluation order
Q281. Why is float data type recommended for correct results in division?
- It uses less memory
- It can store larger values
- It avoids truncating the result in integer division
- It is faster in computation
Show answer
Answer: (c) It avoids truncating the result in integer division
Q282. How many bytes does the float data type use in C to store a real number?
- 1 byte
- 2 bytes
- 4 bytes
- 8 bytes
Show answer
Answer: (c) 4 bytes
Q283. What is the role of the cout statement when displaying a character in C?
- Displays the character name
- Displays the character value
- Prints the ASCII code of the character
- Converts the character to an integer before display
Show answer
Answer: (b) Displays the character value
Q284. In C programming, what happens if there are nested parentheses in an expression?
- The innermost parentheses are ignored
- The outermost parentheses are evaluated first
- The expression is invalid
- The innermost parentheses are evaluated first
Show answer
Answer: (d) The innermost parentheses are evaluated first
Q285. What does the modulus operator (%) return in C?
- Sum of two numbers
- Product of two numbers
- Quotient after division
- Remainder after division
Show answer
Answer: (d) Remainder after division
Q286. What should be used to force the evaluation order in C arithmetic expressions?
- Semicolon (;)
- Parentheses ( )
- Comma (,)
- Quotation marks (" ")
Show answer
Answer: (b) Parentheses ( )
Q287. What is mentioned as a disadvantage of using multiple if statements in a program?
- Increased readability
- Improved efficiency
- Computationally expensive
- Simplicity in code structure
Show answer
Answer: (c) Computationally expensive
Q288. What is the alternative to using multiple if statements to handle multi-way decisions efficiently?
- Nested loops
- Switch statement
- Compound conditions
- Function calls
Show answer
Answer: (b) Switch statement
Q289. Why is the use of nested if/else statements considered more efficient than using multiple if statements?
- It requires fewer lines of code
- It reduces the need for indentation
- It avoids unnecessary computation
- It allows compound conditions
Show answer
Answer: (c) It avoids unnecessary computation
Q290. In the switch statement, what is required for the variable or expression inside the parentheses?
- It must be a float
- It must be a char or int
- It must be a string
- It must be a double
Show answer
Answer: (b) It must be a char or int
Q291. How does the switch statement handle cases when there is no match with any of the specified constants?
- It executes the default statements
- It terminates the program
- It throws an error
- It continues to the next case
Show answer
Answer: (a) It executes the default statements
Q292. What is the purpose of the default statement in a switch structure?
- To provide a fallback option
- To handle unexpected errors
- To terminate the program
- To improve code efficiency
Show answer
Answer: (a) To provide a fallback option
Q293. What happens when a true case is found in a switch statement without using the break statement?
- It executes all statements below the true case
- It terminates the switch statement
- It ignores the true case and moves to the next one
- It throws an error
Show answer
Answer: (a) It executes all statements below the true case
Q294. How does the break statement affect the flow of control in a switch structure?
- It continues to the next case
- It jumps out of the switch statement
- It starts executing statements from the beginning
- It skips the current case and moves to the next
Show answer
Answer: (b) It jumps out of the switch statement
Q295. In the context of loops, where can the break statement be used to terminate the loop?
- Before the loop condition
- After the loop condition
- Inside the loop body
- Outside the loop body
Show answer
Answer: (c) Inside the loop body
Q296. How does the switch statement handle non-integer constants in case statements?
- It converts them to integers
- It throws an error
- It ignores them
- It treats them as strings
Show answer
Answer: (b) It throws an error
Q297. What is the key advantage of using the switch structure over multiple if statements?
- Improved readability
- Enhanced flexibility
- Increased computational cost
- Better efficiency
Show answer
Answer: (d) Better efficiency
Q298. In the switch statement, what does the default case handle?
- Error handling
- Program termination
- Execution when no case matches
- Common statements for all cases
Show answer
Answer: (c) Execution when no case matches
Q299. What is the primary drawback mentioned when using 'if statements' extensively in a program?
- Decreased computational cost
- Enhanced program performance
- Increased code efficiency
- Computationally expensive
Show answer
Answer: (d) Computationally expensive
Q300. What is the purpose of using braces { } in an if statement in C programming?
- To separate conditions
- To indicate the end of the if statement
- To create a block of statements to be executed if the condition is true
- To increase indentation for better style
Show answer
Answer: (c) To create a block of statements to be executed if the condition is true
Q301. What is the significance of indentation in C programming?
- It affects the logic of the program
- It is mandatory for correct syntax
- It improves program execution speed
- 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
Q302. In C programming, what is the purpose of the '==' operator?
- Assignment
- Greater than or equal to
- Equal to
- Less than or equal to
Show answer
Answer: (c) Equal to
Q303. What is the primary role of flow charts in program design?
- Execute program instructions
- Visual representation of program logic
- Identify syntax errors
- Declare variables
Show answer
Answer: (b) Visual representation of program logic
Q304. What is the purpose of initializing variables in C programming?
- To declare the type of the variable
- To assign a value to a variable
- To improve program performance
- To create logical errors
Show answer
Answer: (b) To assign a value to a variable
Q305. In the given C programming example, what does the condition 'if ( AmerAge > AmaraAge)' check?
- Whether Amer's age is less than Amara's
- Whether Amer's age is equal to Amara's
- Whether Amer's age is greater than Amara's
- Whether Amer's age is not equal to Amara's
Show answer
Answer: (c) Whether Amer's age is greater than Amara's
Q306. What is the role of the assignment operator '=' in C programming?
- Comparison of values
- Declaration of variables
- Execution of statements
- Assigning a value to a variable
Show answer
Answer: (d) Assigning a value to a variable
Q307. What is the purpose of relational operators in C programming?
- To perform arithmetic operations
- To compare values and make decisions
- To declare variables
- To create logical errors
Show answer
Answer: (b) To compare values and make decisions
Q308. What does the flow chart symbolize in program design?
- Actual code execution
- Visual representation of a program's sequence
- Debugging process
- Compilation process
Show answer
Answer: (b) Visual representation of a program's sequence
Q309. Why is the indentation of lines in C programming considered a matter of style and not affecting program logic?
- It improves program performance
- It indicates syntax errors
- It is a matter of compiler preference
- It only affects code readability, not logic
Show answer
Answer: (d) It only affects code readability, not logic
Q310. What is the primary purpose of using comments in a C program?
- Improve program execution speed
- Explain the purpose of code blocks
- Declare variables
- Identify syntax errors
Show answer
Answer: (b) Explain the purpose of code blocks
Q311. What is the role of the '!=' operator in C programming?
- Comparison of values
- Logical NOT operation
- Equality check
- Not equal to check
Show answer
Answer: (d) Not equal to check
Q312. Why is it important to use relational operators while making decisions in C programming?
- They improve program performance
- They eliminate logical errors
- They are mandatory for correct syntax
- They allow the program to compare values and make decisions
Show answer
Answer: (d) They allow the program to compare values and make decisions
Q313. What is the consequence of writing 'if ( x = 2 )' in C programming?
- Syntax error
- Logical error
- No error
- Compiler warning
Show answer
Answer: (b) Logical error
Q314. What is the purpose of the if/else structure in programming?
- To execute a block of statements when a condition is true
- To execute a block of statements when a condition is false
- To execute different blocks of statements based on whether a condition is true or false
- 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
Q315. According to the logical operators section, what does the && operator do?
- Combines conditions with OR
- Combines conditions with AND
- Negates a condition
- Reverses the meaning of a condition
Show answer
Answer: (b) Combines conditions with AND
Q316. How are logical operators AND (&&) and OR (||) used in programming?
- They are unary operators
- They are binary operators
- They work with numeric values
- They are used for looping
Show answer
Answer: (b) They are binary operators
Q317. In the truth table for the && operator, what is the result when both Expression 1 and Expression 2 are true?
- False
- True
- True only if Expression 1 is true
- False only if Expression 1 is false
Show answer
Answer: (b) True
Q318. What is the purpose of the logical negation operator (!)?
- To combine conditions with AND
- To reverse the meaning of a condition
- To create a truth table
- To check for equality
Show answer
Answer: (b) To reverse the meaning of a condition
Q319. What is the purpose of the else part in the if/else structure?
- To execute when the condition in the if statement is true
- To execute when the condition in the if statement is false
- To combine conditions with AND
- To create a truth table
Show answer
Answer: (b) To execute when the condition in the if statement is false
Q320. How are logical operators used in decision-making in programming?
- They are used to declare variables
- They are used to calculate values
- They are used to combine conditions for decision-making
- They are used to create loops
Show answer
Answer: (c) They are used to combine conditions for decision-making
Q321. How does the logical negation operator (!) affect a false condition?
- It remains false
- It becomes true
- It is not affected
- It depends on the other conditions in the expression
Show answer
Answer: (b) It becomes true
Q322. What is the definition of programming?
- A set of random activities
- A sequence of steps to solve a particular problem
- A creative expression of abstract ideas
- A mechanism for computer communication
Show answer
Answer: (b) A sequence of steps to solve a particular problem
Q323. According to Alan Perlis, what is his sarcastic statement about modern education?
- Programming is a boring activity
- Modern education teaches critical skills effectively
- Making plans and organizing thoughts are unnecessary skills
- Programming develops essential skills for everyone
Show answer
Answer: (c) Making plans and organizing thoughts are unnecessary skills
Q324. How does Mr. Steve Summit define programming at its most basic level?
- A complex set of instructions
- Telling the computer what to do
- Creating artificial mechanisms
- Solving a problem with natural language
Show answer
Answer: (b) Telling the computer what to do
Q325. Why does Matthias Felleisen argue that learning to program is important?
- To automate tasks effectively
- To use application software efficiently
- Develops analytical and problem-solving abilities
- Traditional programming is useful for everyone
Show answer
Answer: (c) Develops analytical and problem-solving abilities
Q326. Why is commenting code liberally recommended in programming?
- It improves program performance
- It adds unnecessary complexity
- Comments help explain the code without affecting performance
- Comments take up valuable memory space
Show answer
Answer: (c) Comments help explain the code without affecting performance
Q327. What is the comparison made between learning to design programs and playing soccer?
- Both involve physical activity
- Learning soccer is more complex
- Designing programs is not a creative process
- Both require learning basic skills before creativity
Show answer
Answer: (d) Both require learning basic skills before creativity
Q328. What is the emphasis on testing and checking in program evaluation?
- It is unnecessary
- It should be done only once
- It is crucial to refining the program
- It is only for large programs
Show answer
Answer: (c) It is crucial to refining the program
Q329. What is the problem statement in the sample program?
- Calculate the total age of ten students
- Sort out the ages of ten students
- Calculate the average age of a class of ten students
- Prompt the user to enter the age of each student
Show answer
Answer: (c) Calculate the average age of a class of ten students
Q330. Which data type is used for the variables "age1, age2, ..., age10"?
- double
- float
- int
- char
Show answer
Answer: (c) int
Q331. Why is the data type of "AverageAge" declared as int?
- To store only whole numbers
- To store real numbers with decimal points
- To allow the use of expressions in calculations
- To ensure accurate calculations
Show answer
Answer: (a) To store only whole numbers
Q332. What is the purpose of the "cin" statement in the program?
- Display the average age
- Take input from the user
- Sort the ages of students
- Calculate the total age
Show answer
Answer: (b) Take input from the user
Q333. What is the significance of the statement "TotalAge = age1 + age2 + ... + age10;"?
- Calculate the average age
- Display the total age
- Sort the ages of students
- Calculate the sum of ages
Show answer
Answer: (d) Calculate the sum of ages
Q334. What is the purpose of the "cout" statement at the end of the program?
- Display the average age
- Display the total age
- Sort the ages of students
- Prompt the user to enter the age of each student
Show answer
Answer: (a) Display the average age
Q335. What is the purpose of parentheses in expressions in C?
- They are optional and can be omitted
- They force the order of evaluation
- They are used for multiplication
- They indicate the power operator
Show answer
Answer: (b) They force the order of evaluation
Q336. What does the expression "x = a * (x + b * (y + c * z * z))" represent?
- Quadratic equation
- Cubic equation
- Nested expression
- Linear equation
Show answer
Answer: (c) Nested expression
Q337. What is the significance of the "main()" function in the program?
- It displays the average age
- It sorts the ages of students
- It calculates the total age
- It is the starting point of the program
Show answer
Answer: (d) It is the starting point of the program
Q338. Why is the "cout" statement used in the program?
- To take input from the user
- To declare variables
- To display output to the user
- To calculate the average age
Show answer
Answer: (c) To display output to the user
Q339. How many students' ages are taken as input in the program?
- 5
- 8
- 10
- 12
Show answer
Answer: (c) 10
Q340. What is the purpose of the "TotalAge" variable in the program?
- To store the average age
- To store the total age
- To display the result
- To prompt the user
Show answer
Answer: (b) To store the total age
Q341. What are the basic constructs of programming mentioned in the paragraph?
- Functions
- Sequence, decision making, and loops
- Declaration and Definition
- Tips
Show answer
Answer: (b) Sequence, decision making, and loops
Q342. What is the concept of functional design or top-down designing based on?
- Divide and conquer
- Decision making
- Sequence
- Loops
Show answer
Answer: (a) Divide and conquer
Q343. In top-down designing, what do we do when breaking up a task into smaller subtasks?
- Keep refining until the task becomes complex
- Stop at a reasonable level
- Use a goto statement
- Minimize the use of break and continue statements
Show answer
Answer: (b) Stop at a reasonable level
Q344. What is the specific function-calling methodology mentioned in the paragraph?
- Functions are called randomly
- Functions are invoked through a calling program
- Functions are called only by main ( )
- Functions are called by using a goto statement
Show answer
Answer: (b) Functions are invoked through a calling program
Q345. How many categories of functions are mentioned in the paragraph?
- Three
- One
- Two
- Four
Show answer
Answer: (c) Two
Q346. What is the return value type of a function that does not return any value?
- int
- float
- void
- char
Show answer
Answer: (c) void
Q347. What keyword is used to return some value from a function?
- return-value-type
- data type
- keyword
- return
Show answer
Answer: (d) return
Q348. What does the argument-list of a function contain?
- Information passed to the function
- Declarations and statements
- Valid data types like int number, double radius
- Body of the function
Show answer
Answer: (a) Information passed to the function
Q349. What is the default return_value_type if not mentioned for a function?
- float
- int
- void
- char
Show answer
Answer: (b) int
Q350. What is the body of the function composed of?
- Return-value-type
- Function-name
- Declarations and statements
- Argument-list
Show answer
Answer: (c) Declarations and statements
Q351. What is the keyword of the 'C' language for functions that do not return any value?
- return
- void
- data type
- function
Show answer
Answer: (b) void
Q352. How is the structure of a function declared in terms of syntax?
- function-name return-value-type ( argument-list )
- return-value-type function-name { declarations and statements }
- argument-list return-value-type function-name { declarations and statements }
- return-value-type function-name
Show answer
Answer: (b) return-value-type function-name { declarations and statements }
Q353. What does the top-down designing mechanism rely on?
- Sequence
- Decision making
- Loops
- Divide and conquer
Show answer
Answer: (d) Divide and conquer
Q354. What does the return statement in a function do?
- Exits from the program
- Exits from the function
- Returns some value to the calling program and exits from the function
- Minimizes the use of break and continue statements
Show answer
Answer: (c) Returns some value to the calling program and exits from the function
Q355. What is the recommended practice regarding reusing variable names at different scopes?
- Encouraged for better understanding
- Discouraged due to potential confusion
- Only allowed for global variables
- Mandatory for nested functions
Show answer
Answer: (b) Discouraged due to potential confusion
Q356. What does the term 'file scope variable' or 'global variable' refer to?
- A variable accessible only within a function
- A variable accessible within a single code block
- A variable accessible throughout the entire file
- A variable accessible across multiple files
Show answer
Answer: (c) A variable accessible throughout the entire file
Q357. What is the downside of using global variables, according to the paragraph?
- Limited accessibility
- Increased program logic
- Potential unintentional changes
- Improved encapsulation
Show answer
Answer: (c) Potential unintentional changes
Q358. What is the keyword used to declare a global variable in C?
- local
- global
- file
- extern
Show answer
Answer: (d) extern
Q359. What does the 'void' keyword indicate in a function declaration?
- No parameters
- No return value
- Both a and b
- A function prototype
Show answer
Answer: (c) Both a and b
Q360. What is the default function calling mechanism in C, according to the paragraph?
- Call by Name
- Call by Value
- Call by Reference
- Call by Pointer
Show answer
Answer: (b) Call by Value
Q361. What analogy is used to explain 'Call by Value' in the paragraph?
- Copying a letter for rectification
- Making corrections in the original letter
- Deputing somebody to make corrections
- None of the above
Show answer
Answer: (a) Copying a letter for rectification
Q362. When is 'Call by Reference' used in C?
- By default in all functions
- When we want to pass a copy of variables
- When we want the actual variable to be changed by the function
- Only in main() function
Show answer
Answer: (c) When we want the actual variable to be changed by the function
Q363. What does the transpose of a matrix involve?
- Swapping rows and columns.
- Reversing the matrix order.
- Interchanging odd and even elements.
- Doubling each element in the matrix.
Show answer
Answer: (a) Swapping rows and columns.
Q364. Why is a swapping mechanism needed when interchanging values in the transpose process?
- To speed up the program.
- To avoid losing information.
- To reverse the matrix.
- To perform diagonal swaps.
Show answer
Answer: (b) To avoid losing information.
Q365. What happens to the diagonal elements during matrix transposition?
- They are multiplied.
- They remain unchanged.
- They are swapped twice.
- They become zeros.
Show answer
Answer: (b) They remain unchanged.
Q366. What is the role of the temp variable in the transposeMatrix function?
- Stores the transposed matrix.
- Holds the original matrix values during swapping.
- Multiplies elements during transposition.
- Controls the loop iterations.
Show answer
Answer: (b) Holds the original matrix values during swapping.
Q367. What is the significance of the diagonal elements in matrix transposition?
- They are ignored.
- They are multiplied.
- They are swapped twice.
- They remain unchanged.
Show answer
Answer: (d) They remain unchanged.
Q368. Why are arrays considered a possible solution to the problem of storing the ages of multiple students?
- They occupy less memory.
- They require fewer variables.
- They allow storing data of the same type.
- They automatically calculate averages.
Show answer
Answer: (c) They allow storing data of the same type.
Q369. In C language, what does the index of an array start from?
- 1
- 2
- 0
- The size of the array
Show answer
Answer: (c) 0
Q370. What does the size of an array in C represent?
- Memory occupied by the array
- Number of elements in the array
- Total number of arrays
- Size of each element in the array
Show answer
Answer: (b) Number of elements in the array
Q371. In the memory image of an array, what does "C[6]" represent?
- The seventh element
- The sixth element
- The fifth element
- The eighth element
Show answer
Answer: (a) The seventh element
Q372. What is the significance of the value inside the square brackets when accessing an array element?
- Element's address
- Element's value
- Element's index
- Element's size
Show answer
Answer: (c) Element's index
Q373. How is the index of the last element of an array related to the size of the array?
- Equal to the size of the array
- One more than the size of the array
- One less than the size of the array
- Double the size of the array
Show answer
Answer: (c) One less than the size of the array
Q374. How is the total age calculated using a 'for loop'?
- Subtracting each element from the totalAge
- Multiplying each element with the totalAge
- Adding each element to the totalAge
- Dividing each element by the totalAge
Show answer
Answer: (c) Adding each element to the totalAge
Q375. Why is it advised not to use the default initialization of arrays?
- It leads to a compilation error.
- It may assign random values to the array.
- It increases memory consumption.
- It prevents the array from being accessed.
Show answer
Answer: (b) It may assign random values to the array.
Q376. In the given example, what does "age[5]" represent?
- The sixth element of the array
- The fifth element of the array
- The fourth element of the array
- The second element of the array
Show answer
Answer: (a) The sixth element of the array
Why: Indexes start at 0, so age[5] is the sixth element. The source key said fifth.
Q377. What is the maximum value returned by the rand() function?
- 32767
- 32768
- 65535
- 65536
Show answer
Answer: (a) 32767
Why: RAND_MAX is 32767 on the compiler used in the course (compiler-dependent).
Q378. How can we limit the generated random number in a smaller range, such as between 1 and 6 inclusive?
- x = rand() % 6
- x = 1 + rand() % 6
- x = rand() % 5
- x = 1 + rand() % 5
Show answer
Answer: (b) x = 1 + rand() % 6
Q379. What is the result of the statement rand() % 6?
- Between 0 and 5
- Between 1 and 6
- Between 0 and 6
- Between 1 and 5
Show answer
Answer: (a) Between 0 and 5
Q380. What does the keyword 'const' do in the statement "const int arraySize = 100;"?
- Declares an array named arraySize
- Declares a constant integer named arraySize
- Initializes an array with size 100
- Generates a random number with value 100
Show answer
Answer: (b) Declares a constant integer named arraySize
Q381. What is the ASCII code of the null character in C language?
- 0
- 1
- 32
- 127
Show answer
Answer: (a) 0
Q382. What does the statement "cin >> name;" do?
- Reads a single character
- Reads a string until the space
- Reads a string until the enter key is pressed
- Reads a number from the user
Show answer
Answer: (b) Reads a string until the space
Why: cin >> reads only up to the first whitespace; to read a whole line use cin.getline(). The source key said 'until the enter key'.
Q383. What is the size of the declared character array "char name[100];"?
- 50
- 100
- 101
- 99
Show answer
Answer: (b) 100
Q384. Why is 'Call by Reference' used in C?
- To avoid side-effects
- To change the value of the original variable
- To simplify function calls
- To speed up program execution
Show answer
Answer: (b) To change the value of the original variable
Q385. What does the '&' operator in C language do when applied to a variable?
- Multiplies the variable by itself
- Gets the value of the variable
- Returns the address of the variable
- Divides the variable by itself
Show answer
Answer: (c) Returns the address of the variable
Q386. In the provided square(double*) function, what does *x represent?
- The square of x
- The address of x
- Whatever x points to
- The memory location of x
Show answer
Answer: (c) Whatever x points to
Q387. What is the risk associated with using recursive functions in C?
- Increased efficiency
- Memory overhead
- Faster execution
- Limited functionality
Show answer
Answer: (b) Memory overhead
Q388. What is the significance of the #include <iostream.h> statement in the provided code?
- It defines the main function
- It includes the input/output stream library
- It declares constants
- It is irrelevant to the program
Show answer
Answer: (b) It includes the input/output stream library
Q389. Why is 'Call by Reference' considered risky in C?
- It causes syntax errors
- It slows down program execution
- It may lead to side-effects
- It is not supported in C
Show answer
Answer: (c) It may lead to side-effects
Q390. In the statement (*yptr) ++, what does it do?
- Increments the pointer yptr
- Increments the value where yptr points
- Decrements the pointer yptr
- Decrements the value where yptr points
Show answer
Answer: (b) Increments the value where yptr points
Q391. What happens when yptr is incremented by 1?
- It increments the pointer to the next element in the memory
- It increments the value where the pointer points
- It decrements the pointer to the previous element in the memory
- It decrements the value where the pointer points
Show answer
Answer: (a) It increments the pointer to the next element in the memory
Q392. How is the memory address changed when a pointer to an integer is incremented?
- By one byte
- By two bytes
- By four bytes
- By eight bytes
Show answer
Answer: (c) By four bytes
Q393. What is the result of subtracting two pointers pointing to the same memory address?
- Zero
- One
- The difference in bytes between the two addresses
- The sum of the two addresses
Show answer
Answer: (a) Zero
Q394. What information can be obtained by subtracting two pointers?
- The sum of the two addresses
- The difference in bytes between the two addresses
- The product of the two addresses
- The quotient of the two addresses
Show answer
Answer: (b) The difference in bytes between the two addresses
Q395. What is the result of comparing *yptr1 and *yptr2?
- It compares the addresses of yptr1 and yptr2
- It compares the values pointed to by yptr1 and yptr2
- It compares the sizes of yptr1 and yptr2
- It compares the types of yptr1 and yptr2
Show answer
Answer: (b) It compares the values pointed to by yptr1 and yptr2
Q396. What does the statement (*yptr) --; do?
- Decrements the pointer yptr
- Decrements the value where yptr points
- Increments the pointer yptr
- Increments the value where yptr points
Show answer
Answer: (b) Decrements the value where yptr points
Q397. How is pointer arithmetic affected by the data type it points to?
- It is not affected by the data type
- It changes the address by the number of bytes occupied by the data type
- It changes the address by a fixed amount regardless of the data type
- 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
Q398. How is pointer subtraction useful, according to the paragraph?
- It allows us to find the sum of two addresses
- It allows us to find the difference in bytes between two addresses
- It allows us to find the product of two addresses
- 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
Q399. What does the statement *yptr += 3; do?
- Increments the pointer yptr by 3
- Decrements the pointer yptr by 3
- Increments the value where yptr points by 3
- Decrements the value where yptr points by 3
Show answer
Answer: (c) Increments the value where yptr points by 3
Q400. What problem does the Linear Search example aim to solve?
- Calculating the average of an array
- Finding a specific number in an array
- Sorting the elements of an array
- Reversing the order of an array
Show answer
Answer: (b) Finding a specific number in an array
Q401. What is the purpose of the flag variable in the Linear Search example?
- To indicate the end of the loop
- To determine the size of the array
- To check if the number has been found
- To control the loop iterations
Show answer
Answer: (c) To check if the number has been found
Q402. Why is a loop used in the array copying example instead of individual assignment statements?
- To demonstrate the use of loops
- To simplify the code for larger arrays
- To prevent copying of array elements
- To introduce a delay in the execution
Show answer
Answer: (b) To simplify the code for larger arrays
Q403. What information does a function accepting a two-dimensional array as an argument need to know?
- Only the number of rows
- Only the number of columns
- Both the number of rows and columns
- The size of the array
Show answer
Answer: (b) Only the number of columns
Q404. What is the purpose of using an array of pointers for storing variable- length character strings?
- To waste space
- To allocate fixed space for rows
- To minimize space wastage and accommodate variable lengths
- To simplify array manipulation
Show answer
Answer: (c) To minimize space wastage and accommodate variable lengths
Q405. What are the four basic data types mentioned in the paragraph?
- char, int, float, string
- char, int, float, double
- string, int, float, double
- char, integer, float, double
Show answer
Answer: (b) char, int, float, double
Q406. Why is a character array used to store a word or name like "Amir"?
- char variables can store multiple characters
- char variables can store only one character
- char variables automatically append null character
- char variables support escape characters
Show answer
Answer: (b) char variables can store only one character
Q407. What is the benefit of having a null character at the end of a string?
- It increases the size of the array
- It indicates the end of the string
- It allows using multiple characters in single quotes
- It prevents syntax errors
Show answer
Answer: (b) It indicates the end of the string
Q408. Why is the null character important when using cout to print a character array?
- It increases the efficiency of printing
- It is a syntax requirement
- cout uses it as the string terminating point
- It avoids using escape characters
Show answer
Answer: (c) cout uses it as the string terminating point
Q409. Why is the null character explicitly assigned to the destination array in the array copying program?
- To increase the size of the destination array
- To terminate the loop condition
- To indicate the end of the string in the destination array
- To avoid syntax errors
Show answer
Answer: (c) To indicate the end of the string in the destination array
Q410. What is the prototype of the myStringCopy function?
- void myStringCopy (char *source, const char *destination);
- void myStringCopy (const char *destination, char *source);
- void myStringCopy (char *destination, const char *source);
- void myStringCopy (int *destination, const int *source);
Show answer
Answer: (c) void myStringCopy (char *destination, const char *source);
Q411. Why is the keyword 'const' used with the second argument of the myStringCopy function?
- To make the function read-only
- To allow changes to the source array
- To indicate constant size
- To increase efficiency
Show answer
Answer: (a) To make the function read-only
Q412. What does the myStringCopy function do?
- Copies integers from one array to another
- Copies characters from one array to another
- Increments the array pointer
- Prints the address and value of a character pointer
Show answer
Answer: (b) Copies characters from one array to another
Q413. What is automatically passed when arrays are used as function arguments?
- Copies of the array elements
- Reference to the original array
- A null character
- Size of the array
Show answer
Answer: (b) Reference to the original array
Q414. What does the array name become when an array is created?
- Constant pointer
- Variable pointer
- Double pointer
- Null pointer
Show answer
Answer: (a) Constant pointer
Q415. What is the purpose of the statement char * myNamePtr = "Full Name";?
- It creates a char array named myName
- It initializes a char pointer with the address of "Full Name"
- It declares a constant pointer to a char array
- 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"
Q416. In the statement char myName[] = "Full Name";, what is myName?
- Constant pointer
- Variable pointer
- Char array
- Null character
Show answer
Answer: (c) Char array
Q417. What does the keyword 'const' do when used with pointers?
- Increases efficiency
- Allows changes to the pointer
- Makes the pointer read-only
- Terminates the loop
Show answer
Answer: (c) Makes the pointer read-only
Q418. What is the purpose of the dereferencing operator (*) in C programming?
- Multiplication
- Memory allocation
- Getting the value stored at a memory address
- Division
Show answer
Answer: (c) Getting the value stored at a memory address
Q419. What is the significance of initializing a pointer in C programming?
- Enhances program speed
- Avoids runtime errors
- Allows for dynamic memory allocation
- Enables proper referencing in expressions
Show answer
Answer: (b) Avoids runtime errors
Q420. How can a pointer be initialized in C?
- ptr = &x;
- ptr = 0;
- ptr = NULL;
- All of the above
Show answer
Answer: (d) All of the above
Q421. In C, what does a null pointer indicate?
- It points to an undefined memory location.
- It points to the beginning of the memory.
- It points to nothing.
- It points to the end of the memory.
Show answer
Answer: (c) It points to nothing.
Q422. Can the address operator (&) be used with an expression in C?
- Yes
- No
- Only with simple variables
- Only with pointers
Show answer
Answer: (b) No
Q423. What is the primary purpose of using pointers in C with function calls?
- Improve program speed
- Simulate call by reference
- Enable dynamic memory allocation
- Simplify function declarations
Show answer
Answer: (b) Simulate call by reference
Q424. Why does a function call to swap(x, y) in C not swap the values of x and y?
- Passing by value
- Incorrect function declaration
- Compiler error
- Logical error in the swap function
Show answer
Answer: (a) Passing by value
Q425. What is necessary for a function to perform call by reference in C?
- Using global variables
- Including header files
- Passing the address of variables
- Initializing pointers
Show answer
Answer: (c) Passing the address of variables
Q426. How does the bubble sort algorithm work in C?
- By swapping adjacent elements
- By randomly rearranging elements
- By multiplying array elements
- By sorting elements in descending order
Show answer
Answer: (a) By swapping adjacent elements
Q427. In the bubble sort example, what is the purpose of the swap function?
- To allocate memory
- To interchange array elements
- To initialize pointers
- To perform arithmetic operations
Show answer
Answer: (b) To interchange array elements
Q428. How are elements swapped in the bubble sort program using pointers?
- Using temporary variables
- Directly assigning values
- Using the arithmetic operator (+)
- Using the swap function with pointers
Show answer
Answer: (d) Using the swap function with pointers
Q429. In the bubble sort program, why is using pointers essential for swapping elements?
- Improves program speed
- Reduces memory usage
- Enables call by reference
- Simplifies function declarations
Show answer
Answer: (c) Enables call by reference
Q430. When is it optional to use braces in the else part?
- When there is a single statement inside the else part
- When the condition is false
- When there is a nested if statement
- Braces are always mandatory in the else part
Show answer
Answer: (a) When there is a single statement inside the else part
Q431. What is the recommended programming practice regarding the use of braces?
- Use braces only in the if code block
- Use braces only in the else code block
- Use braces all the time
- Use braces only for complex conditions
Show answer
Answer: (c) Use braces all the time
Q432. How do we handle complex conditions in an if statement?
- Use nested if statements
- Use braces in the else part
- Use logical connectives like && and ||
- Both a and c are correct
Show answer
Answer: (d) Both a and c are correct
Q433. Which loop variant is executed at least once before the condition is evaluated?
- While Loop
- Do-While Loop
- For Loop
- Nested Loop
Show answer
Answer: (b) Do-While Loop
Q434. When are braces mandatory in the while loop?
- When there is a single line inside the while code block
- When the condition is false
- When there are multiple lines of code inside the while code block
- Braces are never mandatory in the while loop
Show answer
Answer: (c) When there are multiple lines of code inside the while code block
Q435. What is the syntax for the do-while loop?
- while ( condition ) { // Do something }
- do { // Do something } while ( condition )
- for ( initialization; condition; increment ) { // Do something }
- do { // Do something } for ( condition )
Show answer
Answer: (b) do { // Do something } while ( condition )
Q436. How many times are the statements inside the while code block executed if the while condition is false from the beginning?
- 0 times
- 1 time
- n times
- Infinite times
Show answer
Answer: (a) 0 times
Q437. When are braces not mandatory in the for loop?
- When there is a single statement in the for code block
- When there is a complex condition
- When there is an else part
- Braces are always mandatory in the for loop
Show answer
Answer: (a) When there is a single statement in the for code block
Q438. What is the role of logical connectives like && and || in programming?
- They determine the syntax of the if statement
- They are used in do-while loops
- They handle complex conditions in if statements
- They replace the need for braces
Show answer
Answer: (c) They handle complex conditions in if statements
Q439. In a nested if-statement, when is the code inside the nested if block executed?
- Only when the condition of the outer if is true
- Always
- Only when the condition of the inner if is true
- Never
Show answer
Answer: (a) Only when the condition of the outer if is true
Q440. According to the programming practice mentioned, what is the major advantage of using structured flowcharting?
- It reduces the need for braces
- It improves program readability and logical soundness
- It simplifies complex conditions
- It eliminates the need for nested if statements
Show answer
Answer: (b) It improves program readability and logical soundness
Q441. What is the primary purpose of loops in programming?
- To execute code once
- To simplify complex conditions
- To handle decision structures
- To perform repetitive tasks
Show answer
Answer: (d) To perform repetitive tasks
Q442. How does the for loop terminate?
- When the condition is false
- When the condition is true
- When the loop reaches the exit symbol
- When the program encounters an error
Show answer
Answer: (a) When the condition is false
Q443. What is the purpose of the functions in the header file stdlib.h described in the given paragraph?
- To compare strings
- To manipulate strings
- To convert between different data types
- To concatenate strings
Show answer
Answer: (c) To convert between different data types
Q444. Which function is used to convert a string to a double in the stdlib.h library?
- atof
- atoi
- strtol
- strtod
Show answer
Answer: (a) atof
Q445. What does the function strcpy do?
- Compares two strings
- Copies a string into a character array
- Appends a string to another string
- Concatenates two strings
Show answer
Answer: (b) Copies a string into a character array
Q446. Which header file contains the string manipulation functions described in the paragraph?
- stdlib.h
- string.h
- stdio.h
- math.h
Show answer
Answer: (b) string.h
Q447. What is the purpose of the function strncmp?
- Concatenates two strings
- Compares two strings up to a specified number of characters
- Copies a string into a character array
- Determines the length of a string
Show answer
Answer: (b) Compares two strings up to a specified number of characters
Q448. What is the significance of the const keyword in the function prototype char *strcpy( char s1, const char s2 )?
- It prevents changes to the destination string (s1).
- It prevents changes to the source string (s2).
- It allows changes to both strings.
- It is not significant in this context.
Show answer
Answer: (b) It prevents changes to the source string (s2).
Q449. In the function prototype char *strcat( char s1, const char s2 ), what does s1 represent?
- Destination string
- Source string
- Number of characters to concatenate
- Size of the destination string
Show answer
Answer: (a) Destination string
Q450. How is the destination string represented in the function prototype char *strncpy( char s1, const char s2, size_t n )?
- s1
- s2
- n
- const
Show answer
Answer: (a) s1
Q451. Which function is used for converting a string to an integer in the given paragraph?
- atof
- atoi
- strtod
- strtol
Show answer
Answer: (b) atoi
Q452. What is the purpose of the endPtr parameter in the strtod function?
- It represents the source string.
- It prevents changes to the source string.
- It points to the end of the converted string.
- It is not significant in this context.
Show answer
Answer: (c) It points to the end of the converted string.
Q453. How are command line arguments passed to the program according to the given paragraph?
- As integers
- As floating-point numbers
- As character strings
- As boolean values
Show answer
Answer: (c) As character strings
Q454. What is the significance of the base parameter in the function prototype long strtol( const char *nPtr, char endPtr, int base )?
- It represents the source string.
- It prevents changes to the source string.
- It specifies the base for number conversion.
- It is not significant in this context.
Show answer
Answer: (c) It specifies the base for number conversion.
Q455. What is the primary use of the conversion functions described in the stdlib.h library according to the paragraph?
- String manipulation
- Number comparison
- Data type conversion
- Command line argument parsing
Show answer
Answer: (c) Data type conversion
Q456. In the function prototype int strcmp( const char s1, const char s2), what does it return?
- A negative number if s1 < s2
- Zero if s1 == s2
- A positive number if s1 > s2
- All of the above
Show answer
Answer: (d) All of the above
Q457. What does the function strtoul do?
- Converts a string to an unsigned long
- Compares two strings up to a specified number of characters
- Concatenates two strings
- Determines the length of a string
Show answer
Answer: (a) Converts a string to an unsigned long
Q458. What does the strcmp function return if the strings s1 and s2 are identical?
- A positive number
- A negative number
- Zero
- Null pointer
Show answer
Answer: (c) Zero
Q459. The strncmp function compares:
- Entire strings s1 and s2
- First character of s1 with the first character of s2
- First n characters of s1 with the first n characters of s2
- 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
Q460. What is the purpose of the strlen function?
- Compares two strings
- Determines the length of a character string
- Searches for a character in a string
- Breaks a string into tokens
Show answer
Answer: (b) Determines the length of a character string
Q461. Which of the following search functions locates the first occurrence of a character c in a string s?
- strcspn
- strspn
- strchr
- strpbrk
Show answer
Answer: (c) strchr
Q462. What does the strrchr function return if the character c is not found in string s?
- A positive number
- A negative number
- Null pointer
- Zero
Show answer
Answer: (c) Null pointer
Q463. Which function is used to locate the first occurrence of string s2 in string s1?
- strstr
- strpbrk
- strspn
- strcspn
Show answer
Answer: (a) strstr
Q464. What does the strtok function do?
- Compares two strings
- Determines the length of a character string
- Breaks a string into tokens
- Searches for a character in a string
Show answer
Answer: (c) Breaks a string into tokens
Q465. Which header file is used for file handling in C++?
- <iostream.h>
- <fstream.h>
- <filestream>
- <stdio.h>
Show answer
Answer: (b) <fstream.h>
Q466. What does the ifstream stream stand for in file handling?
- Input file stream
- Output file stream
- File stream
- Integer file stream
Show answer
Answer: (a) Input file stream
Q467. When using the ofstream stream in file handling, what is its purpose?
- Reading from a file
- Writing to a file
- Searching in a file
- Closing a file
Show answer
Answer: (b) Writing to a file
Q468. What type of files consist of readable English characters?
- Program files
- Binary files
- Text files
- Executable files
Show answer
Answer: (c) Text files
Q469. What information is stored in word processor files along with the text?
- Binary information
- Formatting information
- File properties
- Length of the file
Show answer
Answer: (b) Formatting information
Q470. In the context of file handling, what is the primary purpose of files in programs?
- To store volatile data
- To display information on the screen
- To execute programs
- To save data on a permanent basis
Show answer
Answer: (d) To save data on a permanent basis
Q471. Why might a payroll system use files?
- To execute programs
- To display information on the screen
- To store information permanently and reuse it
- To gather data before processing it
Show answer
Answer: (c) To store information permanently and reuse it
Q472. What is the purpose of the fstream stream in C++?
- Input file stream
- Output file stream
- File stream for both reading and writing
- Integer file stream
Show answer
Answer: (c) File stream for both reading and writing
Q473. In the context of file handling, what does volatile data refer to?
- Data stored permanently
- Data displayed on the screen
- Data in the computer memory that is not permanent
- Data in executable program files
Show answer
Answer: (c) Data in the computer memory that is not permanent
Q474. In strcmp, when does the function return zero?
- If s1 is less than s2
- If s1 and s2 are identical
- If s1 is greater than s2
- If s1 and s2 have spaces
Show answer
Answer: (b) If s1 and s2 are identical
Q475. What is the purpose of the strncmp function?
- Compare entire strings
- Find the length of a string
- Compare a specific number of characters in two strings
- Determine the length of a character string
Show answer
Answer: (c) Compare a specific number of characters in two strings
Q476. What does the strchr function do?
- Finds the first occurrence of a character in a string
- Determines the length of the initial segment of characters not in another string
- Returns the length of the initial segment consisting only of characters in another string
- Locates the last occurrence of a character in a string
Show answer
Answer: (a) Finds the first occurrence of a character in a string
Q477. What is the purpose of the strcspn function?
- Finds the first occurrence of a character in a string
- Determines the length of the initial segment of characters not in another string
- Returns the length of the initial segment consisting only of characters in another string
- 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
Q478. What does the strspn function return?
- Finds the first occurrence of a character in a string
- Determines the length of the initial segment of characters not in another string
- Returns the length of the initial segment consisting only of characters in another string
- 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
Q479. What does the strtok function do?
- Determines the length of a character string
- Breaks a string into tokens based on specified delimiters
- Finds the first occurrence of a character in a string
- Locates the last occurrence of a character in a string
Show answer
Answer: (b) Breaks a string into tokens based on specified delimiters
Q480. What is the utility of files in programs mentioned in the paragraph?
- Files store only non-printable binary information
- Files contain volatile information in computer memory
- Files save program data on the disk for non-volatile storage
- Files display lists of files in Windows Explorer
Show answer
Answer: (c) Files save program data on the disk for non-volatile storage
Q481. Which category of data files is plain text files?
- Word processor files
- Program files
- Files created using Microsoft Word
- Files created using Windows Notepad
Show answer
Answer: (d) Files created using Windows Notepad
Q482. What is the primary difference between plain text files and word processor files?
- Plain text files have binary information along with text
- Word processor files have formatting information stored along with text
- Plain text files are created using Windows Explorer
- Word processor files run executable programs
Show answer
Answer: (b) Word processor files have formatting information stored along with text
Q483. What do executable program files primarily contain?
- Volatile information
- Non-printable binary information
- Plain text
- Formatted text
Show answer
Answer: (b) Non-printable binary information
Q484. How does the dir command work in the command prompt window?
- Lists files in a folder
- Finds the length of a file
- Breaks a string into tokens
- Determines the length of a character string
Show answer
Answer: (a) Lists files in a folder
Q485. What is the purpose of the seekg() and tellg() functions in C++?
- To read characters from a file
- To determine the length of a file
- To search for specific data in a file
- To insert data in the middle of a file
Show answer
Answer: (b) To determine the length of a file
Q486. How can seekg() and tellg() be used to find the actual data length of a file?
- By moving to the beginning of the file and using tellg()
- By moving to the end of the file and using tellg()
- By moving 10 bytes from the beginning and using seekg()
- 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()
Q487. Why can the size of a file be greater than the actual data length of the file?
- Due to inefficient disk operations
- Because of electromagnetic devices
- File storage complexity
- Disk blocks allocation
Show answer
Answer: (d) Disk blocks allocation
Q488. What is the main drawback of the Merge Method for inserting data in the middle of a file?
- It requires a lot of computation
- It is wasteful in terms of time and space
- It cannot handle large-sized data
- It disturbs the file structure
Show answer
Answer: (b) It is wasteful in terms of time and space
Q489. What is the key element in resolving the issue of insertion in the middle of a file without disturbing the file structure?
- Serial numbers
- File sorting
- Constant record length
- Merge method
Show answer
Answer: (c) Constant record length
Q490. In C++, what function is used for output during the process of writing to a file?
- seekg()
- tellg()
- seekp()
- tellp()
Show answer
Answer: (c) seekp()
Q491. What happens when a file is opened with ifstream in C++?
- It can only be used for output
- It can only be used for input
- It can be used for both input and output
- It cannot be used for input or output
Show answer
Answer: (b) It can only be used for input
Q492. What does the ios::end flag represent in the context of file handling in C++?
- The beginning of the file
- The current file position
- The end of the file
- The size of the file
Show answer
Answer: (c) The end of the file
Q493. How can seekg() be used to move to a specific position in a file without loops or comparisons?
- By specifying the position directly
- By using tellg() to calculate the position
- By using brute force technique
- By using seekp() instead
Show answer
Answer: (a) By specifying the position directly
Q494. What does a constant record length in a file help to achieve?
- Efficient disk operations
- Quick random access
- Data compression
- Insertion in the middle of a file
Show answer
Answer: (b) Quick random access
Q495. What is the significance of a key in a file in the context of data updation?
- It helps in file sorting
- It ensures constant record length
- It is used to locate a specific record
- It prevents file corruption
Show answer
Answer: (c) It is used to locate a specific record
Q496. In what situation is the Merge Method used for inserting data into a file?
- When the data size is small
- When the file is not sorted
- When the data is in gigabytes
- When there are holes in student ids
Show answer
Answer: (a) When the data size is small
Q497. What is the algorithm of the Merge Method for inserting data in the middle of a sequential file?
- 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.
- Use seekg() and tellg() to locate the insertion point, then directly insert new data.
- Sort the file, then directly insert new data.
- 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.
Q498. Why are disks divided into logical blocks when storing files?
- To increase disk speed
- To simplify file storage
- To prevent data corruption
- To minimize wastage of disk space
Show answer
Answer: (d) To minimize wastage of disk space
Q499. Why is it suggested to save employee information in a file for a payroll system?
- To make the program execution faster
- To avoid the need for calculating salaries
- To have a permanent record for future use
- To eliminate the need for entering data
Show answer
Answer: (c) To have a permanent record for future use
Q500. What is the purpose of using files in the context of data storage?
- To speed up program execution
- To save data temporarily
- To store data permanently on disk
- To reduce memory usage
Show answer
Answer: (c) To store data permanently on disk
Q501. What are the three basic steps in file handling?
- Input, Process, Output
- Open, Read and write, Close
- Save, Load, Print
- Declare, Initialize, Use
Show answer
Answer: (b) Open, Read and write, Close
Q502. What are ifstream and ofstream in C++ file handling?
- Input and output functions
- File stream variables
- File open and close operations
- Predefined streams
Show answer
Answer: (b) File stream variables
Q503. Which function is used to open a file in C++ file handling?
- read()
- openFile()
- open()
- startFile()
Show answer
Answer: (c) open()
Q504. What is the argument for the open function when associating a file with a file stream variable?
- File type
- File size
- File path
- Filename
Show answer
Answer: (d) Filename
Q505. How can multiple words be read from a file at once in C++ file handling?
- myFile >> c;
- myFile >> c1 >> c2 >> c3;
- read(myFile, c);
- readWords(myFile, c1, c2, c3);
Show answer
Answer: (b) myFile >> c1 >> c2 >> c3;
Q506. What is the purpose of the close() function in C++ file handling?
- To save changes made to the file
- To terminate the program
- To release memory
- To close the associated file
Show answer
Answer: (d) To close the associated file
Q507. Which stream is used to handle errors while opening a file?
- cerr
- clog
- cin
- cout
Show answer
Answer: (a) cerr
Q508. What does the exit(1) statement do in C++ file handling error checking?
- Exits the program with an error code
- Closes the file
- Opens a new file
- Resumes program execution
Show answer
Answer: (a) Exits the program with an error code
Q509. What is the primary purpose of the ifstream and ofstream objects in C++ file handling?
- Display data on the screen
- Handle file stream operations
- Calculate salaries
- Execute input and output functions
Show answer
Answer: (b) Handle file stream operations
Q510. How can you read a word from a file in C++ file handling?
- read(myFile, word);
- myFile.readWord(word);
- myFile >> word;
- getWord(myFile, word);
Show answer
Answer: (c) myFile >> word;
Q511. Why is knowing the file structure important before reading it in C++ file handling?
- To speed up the reading process
- To avoid reading errors
- To reduce the size of the file
- To simplify file closing
Show answer
Answer: (b) To avoid reading errors
Q512. What is the purpose of the fstream.h header file in C++ file handling?
- It defines input and output functions
- It handles file operations
- It contains mathematical functions
- It manages memory allocation
Show answer
Answer: (b) It handles file operations
Q513. What does the dot (.) operator represent in the context of file stream objects in C++?
- File size
- Function call
- File path
- Member access
Show answer
Answer: (d) Member access
Q514. In C++ file handling, what does ifstream myFile; represent?
- Input file stream object
- Output file stream object
- Both input and output file stream objects
- Predefined file stream object
Show answer
Answer: (a) Input file stream object
Q515. What is the basic unit of memory?
- Kilobyte
- Megabyte
- Bit
- Byte
Show answer
Answer: (c) Bit
Q516. How many bits form a byte?
- 4
- 8
- 16
- 32
Show answer
Answer: (b) 8
Q517. What is the primary focus of bit manipulation?
- Manipulating characters
- Manipulating bytes
- Manipulating bits
- Manipulating integers
Show answer
Answer: (c) Manipulating bits
Q518. What does the bitwise AND operator (&) return when comparing two bits?
- 1 if both bits are 1
- 0 if both bits are 1
- 1 if any of the two bits is 0
- 0 if any of the two bits is 0
Show answer
Answer: (a) 1 if both bits are 1
Q519. In bit manipulation, what does a bit with 1 represent?
- Turned off
- On
- Cleared
- Unset
Show answer
Answer: (b) On
Q520. What does the bitwise OR operator (|) return if any one of the bits is 1?
- 1
- 0
- True
- False
Show answer
Answer: (a) 1
Q521. What is the result of exclusive OR (XOR) if both bits are the same?
- 0
- 1
- True
- False
Show answer
Answer: (a) 0
Q522. What does the NOT operator (~) do to a bit?
- Invert it
- Set it to 1
- Clear it to 0
- Turn it off
Show answer
Answer: (a) Invert it
Q523. In the context of bit manipulation, what is a bit field used for in operating systems?
- Arithmetic calculations
- File attributes
- Data encryption
- Memory allocation
Show answer
Answer: (b) File attributes
Q524. How can the Exclusive OR operator be utilized for password security?
- Encrypting the password
- Decrypting the password
- Setting a specific bit
- Clearing a bit
Show answer
Answer: (a) Encrypting the password
Q525. In the context of file attributes, what does a check mark indicate?
- Cleared bit
- Set bit
- Cleared byte
- Set byte
Show answer
Answer: (b) Set bit
Q526. What is the purpose of the ~ (NOT) operator?
- Bitwise AND
- Bitwise OR
- Bitwise inversion or NOT
- Unary increment
Show answer
Answer: (c) Bitwise inversion or NOT
Q527. What is the int data type used for?
- Real numbers
- Characters
- Whole numbers
- Non-negative numbers
Show answer
Answer: (c) Whole numbers
Q528. What is the size of the char data type in the paragraph's context?
- 2 bytes
- 4 bytes
- 1 byte
- 8 bytes
Show answer
Answer: (c) 1 byte
Q529. What is the modulus operator (%) used for in the paragraph?
- Division
- Multiplication
- Addition
- Remainder
Show answer
Answer: (d) Remainder
Q530. In the context of comparisons, what does the == operator represent?
- Equality
- Assignment
- Addition
- Modulus
Show answer
Answer: (a) Equality
Q531. What type of operators are bitwise AND, OR, and XOR?
- Unary operators
- Binary operators
- Ternary operators
- Logical operators
Show answer
Answer: (b) Binary operators
Q532. How is the bitwise NOT operator (~) described in the paragraph?
- Unary
- Binary
- Ternary
- Logical
Show answer
Answer: (a) Unary
Q533. Which construct is used for repetitive structures in programming?
- Sequential execution
- Decisions
- File I/O
- Loops
Show answer
Answer: (d) Loops
Q534. In the XOR-based data recovery technique, how is the lost data recovered?
- By shutting down the system
- By replicating data from other disks
- By taking XOR of remaining bits
- By using a temporary third variable
Show answer
Answer: (c) By taking XOR of remaining bits
Q535. What is the purpose of Hot Plug in the context of disk replacement?
- Swapping two numbers
- Shifting binary numbers
- Replacing a disk without system shutdown
- Multiplying binary numbers
Show answer
Answer: (c) Replacing a disk without system shutdown
Q536. In the XOR-based number swapping method, what is the sequence of statements to swap 'a' and 'b'?
- a = a ^ b; b = b ^ a; a = a ^ b;
- a = a ^ b; b = b ^ a;
- a = a ^ b; a = a ^ b;
- b = b ^ a; a = a ^ b;
Show answer
Answer: (a) a = a ^ b; b = b ^ a; a = a ^ b;
Why: 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.
Q537. How are unsigned integers declared explicitly in C?
- int i, j, k;
- unsigned int i, j, k;
- unsigned integers i, j, k;
- unsigned i, j, k;
Show answer
Answer: (b) unsigned int i, j, k;
Q538. What does left shifting do in binary numbers?
- Division by 2
- Multiplication by 2
- Exclusive OR
- Bitwise AND
Show answer
Answer: (b) Multiplication by 2
Q539. What is the primary advantage of shift operators over direct multiplication and division?
- Faster execution
- Smaller code size
- Easier syntax
- Improved precision
Show answer
Answer: (a) Faster execution
Q540. What does Hot Swap refer to in the context of disk replacement?
- Swapping two numbers without a third variable
- Replacing a disk without system shutdown
- Shifting binary numbers
- Encryption and decryption
Show answer
Answer: (b) Replacing a disk without system shutdown
Q541. Determine the output of the following while loop. int counter = 0; while (counter < 5) cout << counter << " "; counter++;
- 54321
- Infinite loop
- 1234
- 12345
Show answer
Answer: (b) Infinite loop
Why: The body of the loop is only the cout statement (there are no braces), so counter++ is never reached and the loop never ends. If braces were present the output would be 01234, which is not among the options.
Q542. In programming, commenting the code liberally is ______.
- Useful
- Time consuming
- Not necessary
- Difficult
Show answer
Answer: (a) Useful
Q543. Arrays are the best data structures ______.
- they take least space in memory
- for the size of the structure and the data in the structure are constantly changing
- for relatively permanent collections of data
- they take much space in memory
Show answer
Answer: (c) for relatively permanent collections of data
Q544. A convenient way to implement random access files is by using only ______.
- Fixed-length Records
- Variant-length Records
- Variant-length Files
- Fixed-length Files
Show answer
Answer: (a) Fixed-length Records
Q545. What will be the output of the following code? int addValue(int *a) { int b = (*a) + 2; return b; } main() { int x = 6; cout << x << ","; cout << addValue(&x) << ","; cout << x; }
- 6,8,6
- 6,6,8
- 6,8,8
- 6,6,6
Show answer
Answer: (a) 6,8,6
Why: x is only read through the pointer, so it stays 6: the output is 6,8,6.
Q546. A matrix is defined as a ______.
- Single dimensional array
- Multi-dimensional array
- Vector product
- Scalar product
Show answer
Answer: (b) Multi-dimensional array
Q547. Operating system is a type of ______.
- application software
- system software
- computer language
- interpreter
Show answer
Answer: (b) system software
Q548. Choose the option which is true for the given code. for (int i = 1; i > 0; i++) { /* loop code */ }
- the logical operator && cannot be used in a test condition
- the while loop is an exit-condition loop
- the test condition is always false
- the test condition is always true
Show answer
Answer: (d) the test condition is always true
Why: The scanned code is damaged; it is read as for (int i = 1; i > 0; i++), whose condition is always true.
Q549. Which one of the given options is not a mode for reading/writing data from a file?
- ios::in
- ios::out
- ios::trunc
- get
Show answer
Answer: (d) get
Q550. ______ mode allows us to add data or change data anywhere in the file.
- ios::ate
- ios::app
- ios::binary
- ios::edit
Show answer
Answer: (a) ios::ate
Why: ios::ate opens the file with the position at the end but still lets you write anywhere; ios::app can only append at the end.
Q551. In C/C++, ______ are the doors through which data can enter and come out of a program.
- Streams
- Fields
- Variables
- Header files
Show answer
Answer: (a) Streams
Q552. All structure elements are ______ by default.
- Public
- Protected
- Private
- Public and Private
Show answer
Answer: (a) Public
Why: The shared key marked Private, but in a structure all members are public by default (in a class they are private).
Q553. Base address is the memory address of the ______ element of an array.
- 1st
- 2nd
- 3rd
- 4th
Show answer
Answer: (a) 1st
Q554. In a while loop, the loop counter must be initialized ______.
- Within the loop
- Before entering the loop
- At the end of the loop
- after the loop execution is ended
Show answer
Answer: (b) Before entering the loop
Q555. Determine the output of the following code. for (int i = 0; i < 10; i++) cout << i % 2;
- 0123456789
- 0 2 4 6 8 10 12 14 16 18
- 0101010101
- 1010101010
Show answer
Answer: (c) 0101010101
Why: i % 2 alternates 0, 1, 0, 1 ... for i = 0 to 9.
Q556. The ______ structure is used to execute one action when a condition is true and another action when that condition is false.
- if-else
- else
- else-if
- if
Show answer
Answer: (a) if-else
Q557. The value of x after evaluating the expression x = 10 + 3 * 4 / 2 - 1 will be:
- 10
- 8
- 15
- 20
Show answer
Answer: (c) 15
Why: Left to right for * and /: 3*4 = 12, 12/2 = 6, so x = 10 + 6 - 1 = 15.
Q558. What is the range of the random number generator function rand()?
- 0 - 32768
- 1 - 32768
- 0 - 32767
- 1 - 32767
Show answer
Answer: (c) 0 - 32767
Why: RAND_MAX is 32767 on the usual compilers used in the course; it can differ on other compilers.
Q559. Using a segment of source code again, with slight or no modification, is termed ______.
- code efficiency
- code reusability
- code modification
- code compatibility
Show answer
Answer: (b) code reusability
Q560. A variable declared inside a code block becomes a ______ variable for that block.
- global
- static
- local
- inner
Show answer
Answer: (c) local
Q561. The file-open mode ______ is used to open a file for output and move to the end of the file.
- ios::out
- ios::app
- ios::trunc
- ios::binary
Show answer
Answer: (b) ios::app
Q562. To access the data members of a structure, the ______ is used.
- dot operator
- dereference operator
- logical operator
- address operator
Show answer
Answer: (a) dot operator
Q563. ______ is the most often used structure to perform repetition tasks for a known number of repetitions.
- 'for' loop
- 'while' loop
- 'do-while loop'
- 'if-else'
Show answer
Answer: (a) 'for' loop
Q564. A reference is a restricted type of ______.
- Array
- Pointer
- Matrix
- Function
Show answer
Answer: (b) Pointer
Q565. If x = 10 and y = 5, then the value of x after evaluating the expression x %= y*3 is
- 10
- 4
- 3
- 30
Show answer
Answer: (a) 10
Why: x %= y*3 means x = x % 15 = 10 % 15 = 10.
Q566. In the year ______, C was approved as a standard language worldwide.
- 1988
- 1967
- 1989
- 1986
Show answer
Answer: (c) 1989
Why: C was standardized by ANSI in 1989 (ISO adopted it in 1990).
Q567. The C language evolved from the language(s) ______.
- BASIC
- C++
- B and BCPL
- FORTRAN
Show answer
Answer: (c) B and BCPL
Q568. Which function of the file streams is called to detach the file handler from the opened file?
- open()
- del()
- detach()
- close()
Show answer
Answer: (d) close()
Q569. To access the address of a variable, the ______ operator is used.
- * operator
- -> operator
- && operator
- & operator
Show answer
Answer: (d) & operator
Q570. The default mechanism of function calling in case of an array is ______ and in case of a variable is ______.
- call by referene, call by reference
- call by reference, call by value
- call by value, call by value
- call by value, call by reference
Show answer
Answer: (b) call by reference, call by value
Q571. ______ transfers the executable code from the hard disk to main memory.
- Linker
- Loader
- Editor
- Interpreter
Show answer
Answer: (b) Loader
Q572. The C language was developed in the late 60s and early 70s in ______.
- Richards Laboratories
- Microsot Laboratories
- Bell Laboratories
- IBM Laboratories
Show answer
Answer: (c) Bell Laboratories
Q573. ______ access is the simplest method of accessing data in a file.
- Binary
- Sequential
- Random
- Fields
Show answer
Answer: (b) Sequential
Q574. In the case of ______, the default mechanism of function calling is call by reference.
- Variable
- Array
- List
- Heap
Show answer
Answer: (b) Array
Q575. When a break statement is encountered in a loop body, it ______.
- transfers the control outside the current loop
- transfers the control outside the current program
- enforces the next iteration of the loop
- generates a compile time error
Show answer
Answer: (a) transfers the control outside the current loop
Q576. Which of the following is the correct way to input two values from the keyboard?
- cin >> var1 , cin >> var2;
- cin >> var1 >> var2;
- cin >> var1 , var2;
- cin >> var1 << var2;
Show answer
Answer: (b) cin >> var1 >> var2;
Q577. When a value is referred to by a normal variable, it is known as ______.
- Direct Reference
- Indirect Reference
- Proper Reference
- Partial Reference
Show answer
Answer: (a) Direct Reference
Q578. When a variable is defined within a function then ______.
- it can be accessed anywhere in the program in which this function has been defined.
- it can be accessed only within this function.
- it can be accessed anywhere below its declaration.
- it can not be accessed.
Show answer
Answer: (b) it can be accessed only within this function.
Q579. ______ provide a communication channel between files and a program.
- Strings
- Streams
- Function seekg()
- Function tellg()
Show answer
Answer: (b) Streams
Q580. Which step is not performed during proper program design?
- Analyze a problem statement, typically expressed as a word problem
- Formulate statements and comments in a precise language
- Write details about the performance of program
- Pay attention to detail
Show answer
Answer: (c) Write details about the performance of program
Why: Judgment call: the program design steps are to analyze the problem, formulate statements and comments precisely and pay attention to detail; 'writing details about the performance' is not one of them.
Q581. How many elements are stored in the following? int matrix[4][5];
- 9
- 20
- 25
- 10
Show answer
Answer: (b) 20
Why: 4 x 5 = 20 elements.
Q582. Which of the following is not a valid variable name in C++?
- NameOfStudent
- nameOfStudent
- _studentName
- @studentName
Show answer
Answer: (d) @studentName
Why: An identifier may contain only letters, digits and underscore, so a name cannot start with @.
Q583. What does (x < 3) mean in C++?
- x is less than 3
- x is greater than or equal to 3
- x is greater than 3
- x is equal to 3
Show answer
Answer: (a) x is less than 3
Q584. The data in the memory is ______.
- volatile
- non-volatile
- both
- none
Show answer
Answer: (a) volatile
Q585. Each array declaration must provide information about all of these except ______.
- Name of the array
- Type of data stored in the array
- The location of the first element to be stored
- Number of elements of the array
Show answer
Answer: (c) The location of the first element to be stored
Q586. What will be the output of the program if x = 10? if (x != 0 && x <= 10) { cout << "Condition 1 is true."; } if (x >= 10 && x <= 20) { cout << "Condition 2 is true."; }
- Condition 1 is true
- Condition 2 is true
- Both conditions are false
- Condition 1 is true. Condition 2 is true.
Show answer
Answer: (d) Condition 1 is true. Condition 2 is true.
Why: With x = 10 both conditions are true, so both messages are printed.
Q587. A repetition statement specifies that an action is to be continued while some ______ remains true.
- Condition
- Control
- Operator
- Assignment
Show answer
Answer: (a) Condition
Q588. A function prototype is written ______.
- Within main function
- After the return statement in main
- Before the return statement in main
- Before call of that function
Show answer
Answer: (d) Before call of that function
Q589. The ______ statement is an unconditional branch of execution.
- Switch statement
- Continue statement
- Goto statement
- Default statement
Show answer
Answer: (c) Goto statement
Q590. How many times will the following loop execute? int i = 3; while (i > 0) { cout << "Statements" << endl; i -= 2; }
- 0
- 1
- 2
- 3
Show answer
Answer: (c) 2
Why: i = 3 prints, i = 1 prints, i = -1 stops: the body runs 2 times.
Q591. How many bytes will an integer-type pointer intPtr jump in memory if the statement intPtr += 2; is executed? (int = 4 bytes)
- 2
- 4
- 8
- 12
Show answer
Answer: (c) 8
Why: intPtr += 2 moves 2 elements; with a 4-byte int that is 8 bytes.
Q592. Using a word processor for writing the code of a program is not good because:
- It has less features for writing code of a program
- It is not good for memory
- It has no compiler
- None of the above
Show answer
Answer: (d) None of the above
Why: Judgment call: a word processor saves extra formatting information with the text, which is not wanted in source code; none of the first three reasons is correct.
Q593. The data contained in a structure is defined within ______.
- curly braces
- parenthesis
- inverted commas
- none
Show answer
Answer: (a) curly braces
Q594. What is the use of the ios::trunc mode?
- To open a file in input mode
- To open a file in output mode
- To truncate an existing file to half
- To truncate an existing file to zero
Show answer
Answer: (d) To truncate an existing file to zero
Q595. What is the usual type of an unsuffixed decimal integer literal that fits in int?
- short
- float
- int
- double
Show answer
Answer: (c) int
Q596. In case of multiple statements, body of the loop must be enclosed within ______.
- parentheses ()
- braces { }
- brackets [ ]
- arrows < >
Show answer
Answer: (b) braces { }
Q597. Which bitwise operator returns 0 when both input bits are 1?
- AND
- XOR
- NOT
- OR
Show answer
Answer: (b) XOR
Why: XOR gives 1 only when the two bits differ, so 1 ^ 1 = 0. AND gives 1 for 1 & 1 and OR gives 1 for 1 | 1.
Q598. Which of the given file handling modes are similar in their functionality?
- ios::out, ios::trunc
- ios::trunc, ios::ate
- ios::trunc, ios::nocreate
- ios::out, ios::ate
Show answer
Answer: (a) ios::out, ios::trunc
Why: Opening with ios::out already truncates (empties) an existing file, which is exactly what ios::trunc does.
Q599. <, <=, >, >= are called ________ operators.
- Arithmetic
- Logical
- Relational
- Conditional
Show answer
Answer: (c) Relational
Q600. If a ________ finds an error, it stops translating without generating any executable code.
- Linker
- Loader
- Compiler
- Interpreter
Show answer
Answer: (c) Compiler
Q601. In two-dimensional array, we use ________ for loop(s) to populate the array.
- 1
- 2
- 3
- 4
Show answer
Answer: (b) 2
Why: One loop for the rows and one nested loop for the columns.
Q602. eof is used to check for the ________ of file when a file is being read.
- Start
- End
- Middle
- Name
Show answer
Answer: (b) End
Q603. There is a pointer variable named ptr of type float. Which type of variable address can be stored by ptr?
- int
- float
- char
- double
Show answer
Answer: (b) float
Part 2: Subjective Questions
Short Questions
Short answers of 1-5 marks.
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 semicolonQ9. 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
breakis 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.
| A | B | A && B | A || B |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 |
| 1 | 0 | 0 | 1 |
| 1 | 1 | 1 | 1 |
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: 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
Q37. 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
Q38. 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];
Q39. 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.
Q40. 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).
Q41. 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.
Q42. 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.
Q43. 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.
Q44. 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.
Q45. 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;
}Q46. 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
Q47. 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
fstreamobject (for both input and output) or with ifstream/ofstream. - Move the get pointer with
seekg(offset, origin)for reading and the put pointer withseekp(offset, origin)for writing. The origin isios::beg,ios::curorios::end. - Use
tellg()/tellp()to know the current position. - Read with
read()/get()/getline()and write withwrite()/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();Q48. 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";
}Q49. 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;
}Q50. 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.
Q51. 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>withusing namespace std;) is missing. long position, long positon;declares position twice with a misspelled name. It must belong 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.
Q52. 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.
Q53. 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 declareint main(). - Headers
iostream.handconio.hare 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();
}Q54. 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;
}Q55. 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.
Q56. 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.
Q57. 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])
Q58. 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 == 0is true only for 0 and 1. else()is wrong; else has no condition and no brackets:else.numberis never given a value (it holds garbage), so it must be read first (cin >> number;).coutneeds the insertion operator:cout << "The number is even";, and the closing brace must match.
Q59. 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;
}Q60. 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.
Q61. 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);Q62. 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 0Q63. 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
Q64. 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 = 10is 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;).
Q65. 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.
Q66. 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.
Q67. 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.
Q68. 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.
Q69. 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.
Q70. 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.
Q71. 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.
Q72. 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.
Q73. 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.
Q74. 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.
Q75. 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 requiredQ76. 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.
Q77. 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.
Q78. 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.
Q79. 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 10Q80. 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);Q81. 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.
Q82. 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.
Q83. 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.
Q84. 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.
Q85. 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.)
Q86. 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.
Q87. 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.
Q88. 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;
Q89. 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.
Q90. 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);.
Q91. 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.
Q92. 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.
Q93. 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.
Q94. 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;
}Q95. 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.
Q96. 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.
Q97. 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].
Q98. 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.
Q99. 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.
Q100. 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.
Q101. 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.
Q102. 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 bytesQ103. 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.
Q104. 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.
Q105. 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++;.
Q106. 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.
Q107. 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.
Q108. 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.
Q109. 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'
Q110. 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);Q111. 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();Q112. 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).
Q113. 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.
Q114. 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
Q115. 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.
Q116. 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.
Q117. 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.
Q118. 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.
Q119. Write the code to declare a 2D array of integers having two rows and three columns, then declare a pointer and point it to that array. (3 marks)
A pointer to a row of a 2D array is declared as a pointer to an array of 3 integers; the array name itself gives the address of its first row.
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
int (*ptr)[3] = arr; // ptr points to row 0 of arr
cout << ptr[1][2] << " " << *(*(ptr + 1) + 2); // both print 6Note: the parentheses in (*ptr)[3] are required; int *ptr[3] would declare an array of 3 pointers.
Q120. What will be the output of the following code? int num[3][2] = {12, 51, 34, 54, 14, 55}; for (int j = 0; j < 3; j++) cout << *(*(num + j) + 1) << endl; (3 marks)
num + j points to row j, *(num + j) is that row (address of its first element) and *(num + j) + 1 is the address of its second element. So the loop prints the second element of every row.
Rows: {12, 51} {34, 54} {14, 55}
Output:
51
54
55Note: the shared copy of this question was damaged by scanning (num + 7, j+4); it is read here as num + j and j++, the only reading that compiles. Checked by running it.
Q121. If p and q are two pointers and n is an integer, which of these are legal and which are illegal: p+q, p-q, p+n, p-n, n+q? What is the problem with cout << "p+q = " << p+q; (3 marks)
- p + q: illegal. Adding two addresses has no meaning.
- p - q: legal (both must point into the same array); the result is the number of elements between them.
- p + n, p - n, n + q: legal; the pointer moves forward or backward by n elements (n x size of the pointed type bytes).
So the statement that prints p+q gives a compile-time error because two pointers cannot be added.
Q122. If a structure is passed to a function, what is the default calling convention (by value or by reference)? (2 marks)
By value. A copy of the whole structure is passed, so changes made inside the function do not affect the original. To modify the original, pass the structure by reference (void f(student &s)) or pass a pointer to it. (Only arrays are passed by address by default.)
Q123. What happens if the file 'myfile.txt' does not exist and we still try to open it using file.open("myfile.txt", ios::out)? (2 marks)
With ios::out an output file is opened (and created if it does not exist), so the open succeeds and an empty new file named myfile.txt is created. If the file already exists, its old contents are erased. (For an input stream, opening a non-existent file fails.)
Q124. What happens if we open an existing file using the default output mode and write data into it? (2 marks)
The default mode of an ofstream is ios::out, which truncates the file: the old contents are deleted and the new data replaces them. To keep the old data and add at the end, open it with ios::app.
Q125. Suppose we want to store values like 10, 45.3, 4, 4, D, 6.4 and 50 using an array. Can we store all these elements by declaring a single array? Yes or no? Give a reason. (3 marks)
No. An array is a collection of elements of the same data type. These values are of different types (integers, floating-point numbers and the character 'D'), so they cannot be stored as they are in one array. They can be kept in separate arrays (int, float, char) or grouped in a structure.
Q126. Write the declaration of a function named getMax which takes a 2D array of integers (3x3 dimension) as its parameter and returns a double pointer to an integer. (2 marks)
int** getMax(int arr[][3]); // prototype
The return type is int** (pointer to pointer to int). For a 2D array parameter, the number of columns (3) must be given; the number of rows may be omitted.
Q127. Write a code segment that displays the diagonal elements of a matrix of N x N, where N can be any number. (3 marks)
for (int i = 0; i < N; i++)
cout << m[i][i] << " "; // diagonal: row index equals column indexFor the matrix 1 2 3 / 4 5 6 / 7 8 9 it prints 1 5 9. Only one loop is needed because the diagonal elements have equal row and column indexes.
Q128. Assuming that 'num' is a 2D array of characters, what does the statement *num contain? (2 marks)
For char num[3][10]; the name num points to the first row, so *num is the first row itself (that is num[0], the address of its first character). If that row holds a string, cout << *num; prints the first string.
Q129. Detect and correct the error(s): the following code passes a value to a function by reference and prints the value before and after the call. (5 marks)
In a reference parameter the name is used like an ordinary variable; it must not be dereferenced with *, and the function is called with the variable itself (not *x). Corrected code:
#include <iostream>
using namespace std;
int test(int &x) { // x is a reference to the caller's variable
x = x + 200;
return x;
}
int main() {
int x = 100;
cout << "x= " << x;
test(x); // pass the variable itself
cout << endl << "x= " << x;
return 0;
}Output: x= 100 then x= 300 (the original changed because it was passed by reference).
Note: the shared copy of the code was badly damaged by scanning; this is the corrected program for the stated purpose, checked by running it.
Q130. Assume that you have stored a binary file on the desktop and you open it in a text editor. What will happen? (2 marks)
The editor shows unreadable, garbled characters (symbols, boxes, blank or odd-looking characters). A binary file stores raw bytes of the data (for example the 4 bytes of an int), not readable characters, so a text editor tries to interpret those bytes as text and cannot display them meaningfully.
Q131. Write the code for calling the getline() member function of cin for reading 30 characters from the keyboard and storing them in the character array 'Arr'. (2 marks)
char Arr[30]; cin.getline(Arr, 30); // reads a line of at most 29 characters; the last place keeps '\0'
The second argument is the size of the array: getline stores at most (size - 1) characters and adds the null character.
Q132. How can we declare a character array? Is it different from an integer array declaration? Give one example. (2 marks)
The syntax is the same: type name[size];, only the type is char. The differences: a character array can be initialised with a string in double quotes and needs one extra place for the null character '\0', and it can be read or displayed as a whole with cin / cout, while an integer array needs a loop.
char name[20]; // can hold a string of up to 19 characters char city[] = "Lahore"; // size 7 (6 letters + '\0')
Q133. Write a program which opens a file named "this.txt" and then, using the write() function, writes the string "Introduction to Programming" at the end of the file. (5 marks)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out;
out.open("this.txt", ios::app); // app: write at the end of the file
if (!out) {
cout << "Error opening file";
return 1;
}
char text[] = "Introduction to Programming";
out.write(text, sizeof(text) - 1); // -1 so that '\0' is not written
out.close();
return 0;
}Q134. Write down the functionality of the functions strcpy(), strncpy(), atof() and atoi(). (4 marks)
- char *strcpy(char *s1, const char *s2): copies the string s2 (including its null character) into the array s1 and returns s1. s1 must be large enough.
- char *strncpy(char *s1, const char *s2, size_t n): copies at most n characters of s2 into s1 and returns s1. (If s2 has n or more characters, no null character is added automatically.)
- double atof(const char *nptr): converts the string to a
double, for example "3.14" becomes 3.14. - int atoi(const char *nptr): converts the string to an
int, for example "25" becomes 25.
strcpy and strncpy are string manipulation functions (header string.h); atof and atoi are string conversion functions (header stdlib.h).
Q135. Give one use of a pointer. (1 marks)
Pointers let a function work on the original variables, for example swapping two values by passing their addresses. Other uses: traversing arrays, passing arrays to functions, and dynamic memory allocation.
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}Q136. What are the basic steps of file handling? (3 marks)
- Include the header
<fstream>. - Declare a stream object:
ifstreamfor reading,ofstreamfor writing. - Open the file (
open()or in the constructor) and check that it opened successfully. - Read from or write to the file.
- Close the file with
close().
Q137. What operator do you use to assign a pointer the address of another variable or constant? (2 marks)
The address-of operator &.
int i; int *ptri; ptri = &i; // ptri now holds the address of i
Q138. What is meant by *num and &num? (1 marks)
If num is a pointer (int x = 5; int *num = &x;):
*numis the dereference operator: the value stored at the address held by num (here 5).&numis the address of the pointer variable num itself (not of x).
Q139. Find the output of the following program. union Num { int ValueI; float ValueF; double ValueD; char ValueC; }; Num TestVal = {100}; cout << TestVal.ValueI; TestVal.ValueF = 2.123; cout << TestVal.ValueF; cout << TestVal.ValueD; TestVal.ValueC = 'U'; cout << TestVal.ValueC; (5 marks)
All members of a union share the same memory (size of the largest member, 8 bytes here), and only the member written last holds a meaningful value.
Integer = 100 Float = 2.123 Uninitialized double = <garbage value, e.g. 5.30754e-315> character = U
The double is not the value that was stored: its bytes only partly overlap the float and the rest was never set, so the number printed is unpredictable and differs between compilers. Note: the shared code was damaged by scanning; it is read here in its obvious intended form.
Q140. Write the definition of a function if we want to pass the argument by reference without changing the value stored at that address. (5 marks)
Pass the argument by reference but declare the parameter const; the function can read the value but the compiler rejects any attempt to change it.
void show(const int &x) { // reference, but read-only
cout << x << endl;
// x = 10; // error: x is const
}
// pointer version: void show(const int *p);Q141. What will be the output of the following code? int x = 6; int y; x = x << 1; y = x >> 1; cout << "x = " << x << "\n"; cout << "y = " << y; (5 marks)
Left shift by 1 multiplies by 2: x = 6 << 1 = 12. Right shift by 1 divides by 2: y = 12 >> 1 = 6.
x = 12 y = 6
Q142. What is the output of the following program? #include iostream.h main() { int RollNo; int rollno; RollNo = 5; rollno = 8; cout << "Roll No is " << rollno; } (3 marks)
- The line
#include iostream.his missing the angle brackets (< >), so the program does not compile. - If this is corrected, the output is
Roll No is 8, because C/C++ identifiers are case sensitive:RollNoandrollnoare two different variables.
Q143. Find the error in the code given below. if ( num % 2 = 0 ) cout << "The number is even" << endl; (2 marks)
= is the assignment operator; the equality test needs ==. num % 2 = 0 is a compile-time error (an expression cannot be assigned to). Correct form:
if (num % 2 == 0)
cout << "The number is even" << endl;Q144. Which data type should be used to store the value 50.7? (1 marks)
A floating-point type: float (or double for more precision). An int would drop the fractional part.
Q145. Convert the following switch statement into if statements. switch (operator) { case '+': result = op1 + op2; break; case '-': result = op1 - op2; break; case 'x': case '*': result = op1 * op2; break; case '/': result = op1 / op2; break; default: cout << "Unknown operator"; } (5 marks)
if (op == '+') {
result = op1 + op2;
} else if (op == '-') {
result = op1 - op2;
} else if (op == 'x' || op == '*') { // two cases sharing one body
result = op1 * op2;
} else if (op == '/') {
result = op1 / op2;
} else {
cout << "Unknown operator"; // default
}Note: operator is a reserved word in C++, so the variable is named op here. The sample answer in the shared file wrongly put a space inside the characters (' +') and left out the 'x' case.
Q146. What are global variables? (1 marks)
Global variables are declared outside every function (including main). They are visible to all the functions written below the declaration, live for the whole run of the program, and are initialised to zero by default. Overusing them is discouraged because any function can change them.
Q147. Is it possible to evaluate the size of a structure? If yes, how? (1 marks)
Yes, with the sizeof operator, applied to the structure type or to a variable of it. The size is at least the sum of the sizes of the members, and can be larger because of padding added by the compiler.
struct VehicleParts { int wheels; int seats; };
cout << sizeof(VehicleParts); // 8 where int is 4 bytesQ148. What is the difference between a compiler and an interpreter? (5 marks)
- Compiler: translates the whole program into machine language at once and produces an executable file. If it finds an error it reports it and no executable is generated. The program then runs fast and independently of the compiler.
- Interpreter: translates and executes the program line by line. Errors are found as it reaches them, which makes correcting easy, but the program runs slower because translation happens every time, and the interpreter cannot optimise the program as a whole.
Both are system software. C/C++ is normally compiled.
Q149. Which bitwise operator returns true if both bits are different and false if both bits are the same? (1 marks)
The XOR operator ^.
0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0
Note: the shared answer was !=, which is a relational operator for whole values, not a bitwise operator.
Q150. The statement int Name[2][2]; defines a 2x2 array. Write the code which reads data from the keyboard for this array and displays it. (5 marks)
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
cin >> Name[i][j]; // read
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
cout << Name[i][j] << " "; // display
cout << endl;
}Q151. What is meant by array manipulation? (1 marks)
Working with the elements of an array using different operations: storing and reading values, traversing, searching, sorting, finding minimum or maximum, copying, and updating elements.
Q152. What is the output of the code given below? void main() { int a=10, b=20; char x=1, y=0; if (a, b, x, y) { cout << "EXAM"; } } (3 marks)
Inside the parentheses is the comma operator: it evaluates the operands from left to right and the value of the whole expression is the last one, y, which is 0 (false). So the condition is false and nothing is printed (checked by running).
Note: the shared explanation ("the if statement did not have any condition") is not the real reason.
Q153. What is an overflow condition? (3 marks)
Overflow occurs when we try to store in a variable a value larger than its data type can hold. The result is a wrong (wrapped-around) value or, in some situations, a run-time error.
unsigned char c = 255; // largest value of unsigned char c = c + 1; // overflow: c becomes 0
Q154. What is the functionality of the function char *strncat(char *s1, const char *s2, size_t n)? (1 marks)
It appends at most n characters of string s2 to the end of array s1. The first character of s2 overwrites the terminating null character of s1, and a null character is added at the end of the result. The value of s1 is returned. s1 must have enough room.
char s1[20] = "Vir"; strncat(s1, "tual University", 4); // s1 becomes "Virtual"
Q155. Write a piece of code that outputs three values of type int, long and float to a stream. (1 marks)
int a = 10; long b = 124568979; float c = 6.57; cout << a << "\t" << b << "\t" << c; // values separated by a tab
Q156. What is the difference between a single-dimensional and a multi-dimensional array? (3 marks)
- A single-dimensional array stores a simple list of values and needs one subscript:
int a[5]; - A multi-dimensional array stores values in a table (rows and columns, like a matrix) and needs one subscript per dimension:
int m[3][4];. A two-dimensional array is processed with nested loops.
Q157. What is meant by the scope of an identifier? Differentiate between the different scopes of identifiers and explain them with examples. (10 marks)
The scope of an identifier (variable, function, etc.) is the part of the program in which it can be used (is visible).
- Block (local) scope: declared inside a block
{ }; visible only from its declaration to the end of that block, and destroyed when the block ends. - Function scope: variables and parameters of a function are visible only inside that function. Different functions can use the same names without conflict.
- Global (file) scope: declared outside all functions; visible to every function below the declaration, for the whole run of the program.
- Function prototype scope: names of parameters in a prototype are visible only inside the prototype.
int g = 10; // global: visible everywhere below
void show() {
int x = 5; // local to show()
cout << g << x;
}
int main() {
int x = 1; // a different x, local to main()
if (x == 1) {
int y = 2; // block scope: exists only inside this if block
}
// cout << y; // error: y is not visible here
return 0;
}If a local variable has the same name as a global one, the local one is used inside its block.
Q158. Suppose there is a pointer to a structure, *sPtr. How can we access the data member 'name' with sPtr? (1 marks)
(*sPtr).name // dereference first; the brackets are needed sPtr->name // equivalent and more common arrow operator
Q159. From writing to execution of a program the following software are used. Explain the purpose of each: Editor, Compiler/Interpreter, Linker, Loader. (10 marks)
- Editor: a tool for writing the source code. A plain text editor is used (a word processor is unsuitable because it saves extra formatting information along with the text).
- Compiler / Interpreter: translate the program written in a high-level language into machine language. A compiler translates the whole program and produces executable code only if there is no syntax error; an interpreter translates and runs it line by line.
- Linker: the program uses routines and library functions that are stored in other files; the linker combines their code with our object code and produces one standalone executable file.
- Loader: loads the executable program from the disk into main memory and tells the processor to start executing it from its first instruction (main).
Linker and loader are part of the development environment and are system software.
Q160. Differentiate between C and C++. (10 marks)
- Paradigm: C is a procedural language; C++ supports procedural and object-oriented programming (classes, objects, inheritance, polymorphism).
- Origin: C came first (developed from B and BCPL); C++ was built on C and is nearly a superset of it.
- Input/output: C uses
printf/scanf; C++ uses the streamscout/cin(and also supports C's functions). - Features added in C++: classes, references, function overloading, default arguments, inline functions,
new/delete, templates, namespaces, exception handling and a built-inbooltype. - Structures: in C++ a struct can also contain functions; in C it contains only data.
- Use: C is common for system and embedded software where size and speed matter; C++ is used for larger software where objects help to organise the code.
Q161. When a pointer is incremented, what happens in (a) a single-dimensional array and (b) a two-dimensional array? (3 marks)
- (a) Single-dimensional array: the pointer moves to the next element, i.e. its address increases by the size of the type (4 bytes for an int pointer where int is 4 bytes).
- (b) Two-dimensional array: an element pointer (
int *p = &a[0][0]) moves to the next element, in row-major order. The array namea(or a pointer to a row) moves to the next row:a + 1advances by the size of a whole row (columns x size of the type).
Q162. For char name[] = "Hello World"; give the size of the array name. Also give the size of int arr[] = {0,0,0,0}; (2 marks)
"Hello World"has 11 characters plus the null character, sonameoccupies 12 bytes. (If the string is written with a leading space, " Hello World", it is 13 bytes.)arr[]has 4 elements (the size is taken from the initialiser), i.e. 16 bytes where an int is 4 bytes.
Both checked with sizeof.
Q163. Write the syntax to open the file trans.txt for input using an ifstream object inTransaction. (2 marks)
ifstream inTransaction;
inTransaction.open("trans.txt");
// or in one line: ifstream inTransaction("trans.txt");
if (!inTransaction)
cout << "File could not be opened";Q164. Mention the bitwise operators. (2 marks)
&bitwise AND,|bitwise OR,^bitwise XOR,~bitwise NOT (complement)<<left shift,>>right shift
Q165. Find the output: int y[10] = {10,20,30,40,50,60,70,80,90,100}; int *yptr; yptr = y; cout << *(yptr + 1*2); (2 marks)
yptr + 1*2 is yptr + 2, the address of y[2], so the dereference prints 30.
Q166. Declare a 10-character string and display its fourth and eighth elements using pointers. (3 marks)
char str[10] = "ABCDEFGHI"; // 9 letters + '\0' = 10 places char *p = str; cout << *(p + 3) << endl; // fourth element -> D cout << *(p + 7) << endl; // eighth element -> H
The n-th element is at offset n - 1 from the start.
Q167. Find the output: int x = 10; int y = 30; int *xptr; xptr = &x; cout << "x = " << *xptr + x; (2 marks)
*xptr is the value of x (10), and *xptr + x is 10 + 10, so the output is x = 20.
Note: the operators were missing in the shared copy of this question; it is read here in the form above.
Q168. Determine the output before and after calling updateAge for int age[5] = {10}; where updateAge sets age[3] = 20. (5 marks)
void updateAge(int a[]) { a[3] = 20; }
int age[5] = {10}; // 10 0 0 0 0
// before the call prints: 10 0 0 0 0
updateAge(age);
// after the call prints: 10 0 0 20 0Only the first element is given a value; the remaining elements of a partly initialised array become 0. Arrays are passed by address, so the change made inside the function is visible in main.
Note: the shared code was damaged by scanning (missing braces, wrong signature); this is the reconstructed intended version, checked by running.
Q169. Create the file cs201.txt, write the text "introduction to programming by Dr Naveed A Malik" into it, and display the file content using getline(). (5 marks)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out("cs201.txt");
out << "introduction to programming by Dr Naveed A Malik";
out.close();
ifstream in("cs201.txt");
char line[100];
in.getline(line, 100); // reads one whole line
cout << line << endl;
in.close();
return 0;
}Q170. Create a 4-row, 2-column integer array and display the values in the first column of each row. (5 marks)
int a[4][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
for (int i = 0; i < 4; i++)
cout << a[i][0] << endl; // column index 0 = first columnOutput: 1, 3, 5, 7 (one per line).
Q171. What is the difference between get() and getline()? (3 marks)
- get() reads a single character (or, with an array and a size, a group of characters) but leaves the delimiter (new line) in the stream.
- getline() reads a complete line up to the delimiter (new line by default), removes the delimiter from the stream and does not store it. It stores at most (size - 1) characters followed by the null character.
Q172. What are the constraints of random file access? (2 marks)
- The records should be of fixed length, so that the position of a record can be calculated (record number x record size).
- Space is wasted when a record does not use all of its fixed length.
- Inserting or deleting a record in the middle is difficult.
- The file is usually used in binary mode and must be opened for both reading and writing, using
seekg()/seekp()to move to a position.
Q173. Write C++ statements to assign the value 2 to the first element of each row of an integer array with three rows and four columns.
int matrix[3][4];
matrix[0][0] = 2;
matrix[1][0] = 2;
matrix[2][0] = 2;
// or with a loop
for (int r = 0; r < 3; r++)
matrix[r][0] = 2;Indexes start at 0, so the first element of each row is column 0.
Q174. Write C++ code to append the string "Introduction to Programming" to a file named this.txt using the write() member function.
#include <fstream>
#include <cstring>
using namespace std;
int main() {
ofstream out("this.txt", ios::app); // ios::app = append at the end
if (!out) return 1;
const char text[] = "Introduction to Programming";
out.write(text, strlen(text));
out.close();
}write(buffer, count) sends exactly count bytes; strlen excludes the null character.
Q175. Why is the iostream header included in C++ programs?
<iostream> declares the standard input and output stream objects cin, cout and cerr and the operators >> and <<, together with manipulators such as endl. Without it the program cannot read from the keyboard or print on the screen. Older compilers used the nonstandard <iostream.h>.
Q176. What is the array size of int arr[] = {0,0,0,0};?
The size is taken from the initializer list: 4 elements (indexes 0 to 3). If sizeof(int) is 4 bytes the array occupies 16 bytes, so the element count is sizeof(arr)/sizeof(arr[0]).
Long Questions
Longer questions that need complete code or a full explanation.
Q177. 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
Q178. 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
Q179. 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;
}Q180. 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.
Q181. 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;
}Q182. 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;
}Q183. 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;
}Q184. 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;
}Q185. 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;
}Q186. 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;
}Q187. 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;
}Q188. 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.
Q189. Write a program which declares and initializes two arrays of 2x2 dimensions, adds the member-wise elements of both arrays and stores the result in a new 2-D array. For example, if the first array has 4, 6, 3, 6 and the second has 2, 5, 4, 6, the new array should have 6, 11, 7, 12. (5 marks)
#include <iostream>
using namespace std;
int main() {
int a[2][2] = {{4, 6}, {3, 6}};
int b[2][2] = {{2, 5}, {4, 6}};
int sum[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
sum[i][j] = a[i][j] + b[i][j]; // member-wise addition
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
cout << sum[i][j] << " ";
cout << endl;
}
return 0;
}Output: 6 11 and 7 12.
Q190. What will be the output? int x[10] = {0,1,2,3,4,5,6,7,8,9}; int *xptr; xptr = &x[5]; cout << *(xptr++) + 1; (2 marks)
xptr points to x[5] (value 5). *(xptr++) uses the value 5 first and only then moves the pointer, so the expression is 5 + 1.
Output: 6
Q191. Write a program which declares an array initialized with the string "Welcome to Virtual University". Using string manipulation functions, replace all the white spaces with new line characters and convert all lower case letters to upper case. Display the new string. (5 marks)
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main() {
char str[] = "Welcome to Virtual University";
for (int i = 0; i < strlen(str); i++) {
if (str[i] == ' ')
str[i] = '\n'; // space -> new line
else
str[i] = toupper(str[i]); // lower case -> upper case
}
cout << str << endl;
return 0;
}Output: WELCOME, TO, VIRTUAL, UNIVERSITY, each on its own line (verified by running).
Q192. Write a program which declares and initializes an array of five integers and then, using a pointer, displays the square of each element. For example, for 4, 7, 9, 3, 5 the output should be 16, 49, 81, 9, 25. (5 marks)
#include <iostream>
using namespace std;
int main() {
int arr[5] = {4, 7, 9, 3, 5};
int *ptr = arr; // points to the first element
for (int i = 0; i < 5; i++) {
cout << (*ptr) * (*ptr) << " ";
ptr++; // move to the next element
}
return 0;
}Output: 16 49 81 9 25
Q193. Write a recursive function that takes three arguments (an integer array, a starting subscript 's' and an ending subscript 'e'). In the first call it displays the array from s to e; in each successive call it displays the array from s+1 to e. It stops when the starting subscript becomes equal to the ending subscript. For the array 2 3 4 5 6 the output should be: 2 3 4 5 6 / 3 4 5 6 / 4 5 6 / 5 6 / 6. (10 marks)
Each call prints the part of the array from s to e and then calls itself with s + 1; the base case is s == e, after printing the last line.
#include <iostream>
using namespace std;
void printArray(int arr[], int s, int e) {
if (s > e)
return;
for (int i = s; i <= e; i++)
cout << arr[i] << " ";
cout << endl;
if (s == e) // base case: stop
return;
printArray(arr, s + 1, e); // recursive call
}
int main() {
int a[5] = {2, 3, 4, 5, 6};
printArray(a, 0, 4);
return 0;
}Note: the sample answer in the shared file was not recursive (it called the function six times from main), so it was replaced; this version was run and gives the expected output.
Q194. Write a recursive function that takes a character array and a starting subscript as arguments. In each call it displays the string from the subscript to the end, and the subscript increases by one in every call. It stops when the null character is reached. For "SampleString" the output is SampleString / ampleString / mpleString / ... (10 marks)
#include <iostream>
using namespace std;
void printFrom(char str[], int start) {
if (str[start] == '\0') // base case: null character
return;
cout << &str[start] << endl; // prints from 'start' to the end
printFrom(str, start + 1); // recursive call
}
int main() {
char s[] = "SampleString";
printFrom(s, 0);
return 0;
}Output: SampleString, ampleString, mpleString, pleString, ... down to the single letter g (checked by running).
Q195. What will be the output of the following code segment? int x[5] = {2, 4, 5, 7, 1}; int *ptr = &x[2]; cout << (*ptr)++ << " "; cout << *ptr++; (3 marks)
ptrpoints tox[2](value 5).(*ptr)++prints the value 5 and then increases the value to 6.*ptr++prints the value now at x[2], which is 6, and then moves the pointer to x[3].
Output: 5 6 (checked by running).
Q196. Write a C/C++ program which calculates the aggregate of a student using Aggregate = (Matric_marks*2 + Fsc_marks*4) / 24. If the aggregate is less than 150 display "You can not be admitted to VU", otherwise display "Congratulation! You admitted in VU". (10 marks)
#include <iostream>
using namespace std;
int main() {
int matric, fsc;
float aggregate;
cout << "Enter Matric marks: ";
cin >> matric;
cout << "Enter FSc marks: ";
cin >> fsc;
aggregate = (matric * 2 + fsc * 4) / 24.0; // 24.0 avoids integer division
if (aggregate < 150)
cout << "You can not be admitted to VU";
else
cout << "Congratulation! You admitted in VU";
return 0;
}Note: the sample answer divided integers by 24, which drops the fractional part; dividing by 24.0 keeps it. Run with 400 and 800 it gives "Congratulation..."; with 300 and 400 it gives "You can not be admitted".
Q197. Write a program which reads a text file "PlayersInfo.txt" in the current directory and assigns the values to the struct Player (attributes: Name, Height, Age, Score, Game). Assume the data in the file is in the same order as the attributes. Close the file at the end. (10 marks)
#include <iostream>
#include <fstream>
using namespace std;
struct Player {
char name[30];
float height;
int age;
int score;
char game[30];
};
int main() {
Player p;
ifstream in("PlayersInfo.txt"); // read mode
if (!in) {
cout << "Error opening file";
return 1;
}
in >> p.name >> p.height >> p.age >> p.score >> p.game;
in.close(); // close the file
cout << p.name << " " << p.height << " " << p.age << " "
<< p.score << " " << p.game << endl;
return 0;
}Tested with a file containing Ali 5.9 20 75 cricket.
Q198. Write a C++ program with a function convertHeight which takes the height of a person in centimetres as an argument, converts it into feet and inches and displays them. Take the height from the user. (1 foot = 12 inches, 1 inch = 2.5 cm) (10 marks)
#include <iostream>
using namespace std;
void convertHeight(float cm) {
float inches = cm / 2.5; // 1 inch = 2.5 cm
int feet = (int)(inches / 12); // 1 foot = 12 inches
float remaining = inches - feet * 12;
cout << feet << " feet " << remaining << " inches" << endl;
}
int main() {
float cm;
cout << "Enter height in cm: ";
cin >> cm;
convertHeight(cm);
return 0;
}Example: 175 cm gives 5 feet 10 inches. Note: the sample answer in the shared file multiplied instead of dividing, which gives wrong values.
Q199. Write the C++ program that calculates the Zakat on the amount entered by the user. Zakat is 2.5% of the given amount. (5 marks)
#include <iostream>
using namespace std;
int main() {
float amount, zakat;
cout << "Enter the amount: ";
cin >> amount;
zakat = amount * 2.5 / 100;
cout << "Amount = " << amount << endl;
cout << "Zakat = " << zakat << endl;
return 0;
}For 10000 it prints Zakat = 250.
Q200. Find the output of the code: int a[6] = {2,1,3,15,20,50}; int i = ++a[1]; int j = a[1]++; int k = a[i++]; int l = a[--i] * i; int m = a[++i] - 1; cout << i << " " << j << " " << k << " " << l << " " << m; (5 marks)
i = ++a[1]: a[1] becomes 2, so i = 2.j = a[1]++: j = 2, then a[1] becomes 3.k = a[i++]: k = a[2] = 3, then i = 3.l = a[--i] * i: i becomes 2, so l = a[2] * 2 = 3 * 2 = 6.m = a[++i] - 1: i becomes 3, so m = a[3] - 1 = 15 - 1 = 14.
Output: 3 2 3 6 14 (checked by running).
Q201. Write a program to count the digits in "90some7text". The expected display is: The total nos are : 3 (3 marks)
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
int main() {
char str[] = "90some7text";
int count = 0;
for (int i = 0; i < strlen(str); i++)
if (isdigit(str[i])) // true for '0' to '9'
count++;
cout << "The total nos are : " << count << endl;
return 0;
}Q202. Given struct student { char name[64]; char course[128]; int age; int year; }; initialise a structure variable and display each member. (5 marks)
#include <iostream>
using namespace std;
struct student {
char name[64];
char course[128];
int age;
int year;
};
int main() {
student s = {"Ali", "Introduction to Programming", 20, 1};
cout << "Name: " << s.name << endl;
cout << "Course: " << s.course << endl;
cout << "Age: " << s.age << endl;
cout << "Year: " << s.year << endl;
return 0;
}Part 3: 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.