1. Programming Fundamentals – Detailed Solutions
Question No. 1 – Attempt Any Three [10 Marks]
1. (a) What is the difference between a compiler and an interpreter?
A compiler and an interpreter are both used to convert high-level programming code into
machine language, but they do so differently.
- Compiler: It scans the entire program and translates it into machine code at once. Errors are
shown after compilation. The execution is faster after the code is compiled.
- Interpreter: It translates the program line by line. It stops and shows an error whenever it
encounters an issue, making it useful for debugging. However, it is slower than a compiler.
2. (b) Define keywords and identifiers with suitable examples.
- Keywords: These are reserved words in C++ that have predefined meanings and purposes.
They cannot be used as names for variables or functions.
Examples: int, float, if, else, return
- Identifiers: These are names created by the programmer to identify variables, functions,
arrays, etc.
Examples: age, total, sum
Example Code:
int age = 25;
- 'int' is a keyword.
- 'age' is an identifier.
3. (c) What are header files? Name any two commonly used ones.
Header files in C++ are files that contain function declarations and macro definitions. They
allow programmers to use built-in functions and libraries.
Common header files:
1. <iostream> – Used for input and output operations (cin, cout).
2. <cmath> – Used for mathematical operations (sqrt(), pow(), etc.).
Example:
#include <iostream>
4. (d) Write the basic syntax rules of C++ with a simple example.
2. Basic syntax rules:
1. Every C++ program must have a main() function.
2. Statements end with a semicolon (;).
3. Curly braces { } are used to define blocks of code.
4. Preprocessor directives like #include are used to include libraries.
Example Code:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
Question No. 2 (a) – What is a loop? [3 Marks]
A loop is a programming construct that allows a set of instructions to be executed repeatedly
until a certain condition is met.
Importance:
- Reduces code repetition.
- Allows tasks to be automated, such as processing data, printing patterns, etc.
- Makes code more efficient and easier to maintain.
Types of loops in C++:
- for loop
- while loop
- do-while loop
Part (b)
#include <iostream>
using namespace std;
int main() {
int number;
// Taking input from user
cout << "Enter a number: ";
cin >> number;
3. // Using a loop to print multiplication table
for(int i = 1; i <= 10; i++) {
cout << number << " x " << i << " = " << number * i << endl;
}
return 0;
}
Explanation of the Code
The program begins by including the iostream library, which is required for input
and output.
Inside the main() function, we declare an integer variable number to store the user's
input.
The user is prompted to enter a number using cout, and the input is read using cin.
A for loop runs from 1 to 10. In each iteration, it prints one line of the multiplication
table using the format:
Question No. 3 (a) – What is an array? [3 Marks]
An array is a collection of elements of the same data type stored in contiguous memory
locations. Arrays are used to store multiple values under a single name.
Benefits of arrays:
- Simplifies the process of storing and accessing large sets of data.
- Reduces the need for multiple variables.
- Can be easily manipulated using loops.
Example:
int numbers[5] = {1, 2, 3, 4, 5};
Part (b)
#include <iostream>
using namespace std;
int main() {
// Declare and initialize an array with 5 fixed numbers
int numbers[5] = {10, 20, 30, 40, 50};
int sum = 0; // Variable to store the sum
// Loop through the array and add each element to sum
4. for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
// Display the result
cout << "Sum of array elements = " << sum << endl;
return 0;
}
Explanation of the Code
The array numbers[5] is declared and initialized with 5 fixed integers: {10, 20,
30, 40, 50}.
The variable sum is initialized to 0.
A for loop runs from index 0 to 4 (since array indices start at 0) and adds each
element to sum using sum += numbers[i];.
After the loop finishes, the final sum is printed using cout.
This program demonstrates how arrays and loops work together to process multiple
values efficiently.
Question No. 4 (a) – What is a pointer? [3 Marks]
A pointer is a variable that stores the memory address of another variable. In C++, pointers are
used for dynamic memory allocation, accessing arrays, and passing data by reference to
functions.
Syntax:
int *ptr; // declares a pointer to an integer
ptr = &x; // assigns the address of variable x to pointer ptr
Benefits:
- Efficient memory management
- Allows direct access to memory
- Enables dynamic allocation and deallocation of memory
Part (b)
5. #include <iostream>
using namespace std;
int main() {
int num = 25; // Declare an integer variable
int* ptr = # // Declare a pointer and store the address of num
// Print the value using pointer
cout << "Value of num using pointer: " << *ptr << endl;
return 0;
}
Explanation of the Code
int num = 25; declares an integer variable num and initializes it with the value 25.
int* ptr = # declares a pointer variable ptr that stores the address of num.
*ptr is the dereferencing operator, which accesses the value stored at the address ptr
is pointing to.
cout << *ptr; prints the value of num using the pointer.
This shows how pointers can be used to access and manipulate data stored in other
variables via memory addresses.
Question No. 5 (a) – What is a function? [3 Marks]
A function is a block of code that performs a specific task. Functions help to divide a program
into smaller, manageable parts, making the program easier to understand and maintain.
Benefits:
- Promotes code reuse
- Enhances modularity
- Makes debugging easier
Syntax:
returnType functionName(parameters) {
// function body
6. }
Example:
int add(int a, int b) {
return a + b;
}
#include <iostream>
using namespace std;
float add(float a, float b) { return a + b; }
float subtract(float a, float b) { return a - b; }
float multiply(float a, float b) { return a * b; }
float divide(float a, float b) { return a / b; }
int main() {
float x, y;
char op;
cout << "Enter two numbers: ";
cin >> x >> y;
cout << "Enter operator (+, -, *, /): ";
cin >> op;
if (op == '+') {
cout << "Result: " << add(x, y);
} else if (op == '-') {
7. cout << "Result: " << subtract(x, y);
} else if (op == '*') {
cout << "Result: " << multiply(x, y);
} else if (op == '/') {
if (y != 0)
cout << "Result: " << divide(x, y);
else
cout << "Error: Division by zero!";
} else {
cout << "Invalid operator!";
}
return 0;
}
Explanation of the Program
Header File:
#include <iostream> is used to include the input/output stream library.
using namespace std; allows using cout, cin without writing std::.
Function Definitions:Four functions are created: add, subtract, multiply, and divide.
Each function takes two numbers and returns the result of the operation.
Main Function:
It starts the execution of the program.
Two variables x and y are declared to hold numbers.
op is a character variable used to store the operator.
8. Input Section:
The program prompts the user to enter two numbers and an arithmetic operator.
If-Else Logic:
Based on the operator entered (+, -, *, /), the program calls the appropriate function.
If / is selected, the program also checks if y is zero to prevent a division error.
Error Handling
If the user enters an invalid operator or tries to divide by zero, an error message is shown.