0% found this document useful (0 votes)
4 views21 pages

210 QB Mid 2

The document explains the differences between WHILE and DO-WHILE loops, detailing their execution guarantees and conditions for iteration. It also covers the concept of loops, types of loops (for, while, do-while), and the advantages of arrays in programming. Additionally, it includes programming examples in C for reversing a number, summing a series, reversing an array, bubble sorting, linear search, checking for prime numbers, and finding Fibonacci numbers recursively.

Uploaded by

sumiyaahmedachol
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views21 pages

210 QB Mid 2

The document explains the differences between WHILE and DO-WHILE loops, detailing their execution guarantees and conditions for iteration. It also covers the concept of loops, types of loops (for, while, do-while), and the advantages of arrays in programming. Additionally, it includes programming examples in C for reversing a number, summing a series, reversing an array, bubble sorting, linear search, checking for prime numbers, and finding Fibonacci numbers recursively.

Uploaded by

sumiyaahmedachol
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

1. a) What is the difference between WHILE loop and DO-WHILE loop?

Both WHILE and DO-WHILE loops are used for iteration (repeating a block of code), but they
differ in when they check their condition:
* WHILE Loop:
* Condition Check: The condition is checked before executing the loop's body.
* Execution Guarantee: If the condition is initially false, the loop's body will never execute.
* Analogy: Imagine you're told to "Stay inside WHILE it is raining." If it's not raining when
you get the instruction, you never go inside.
* DO-WHILE Loop:
* Condition Check: The loop's body is executed at least once, and then the condition is
checked.
* Execution Guarantee: The loop's body is guaranteed to execute at least once, regardless
of whether the condition is initially true or false.
* Analogy: Imagine you're told to "DO your homework, WHILE your parents are awake." You
will start doing your homework right away, and only after doing some, you check if your
parents are still awake to decide if you continue. Even if they fall asleep immediately, you
would have done at least a little bit of homework.

2. a) What is iteration/loop? Describe different types of loops.


* Iteration/Loop:
Iteration, or looping, is a fundamental concept in programming that refers to the repeated
execution of a block of statements or instructions. It allows a program to perform the same
task multiple times without writing redundant code. It's like telling someone to "keep stirring
the pot until the soup thickens" – the "stirring" is the repeated action.
* Different Types of Loops:
* for Loop:
* Purpose: Ideal when you know (or can calculate) exactly how many times you need to
repeat a task. It's often used for iterating over a sequence of numbers or elements in a
collection.
* Example: Imagine you have a list of 10 students, and you need to call out each student's
name. You know you'll do this exactly 10 times. A for loop would be perfect for this. "For each
student from 1 to 10, call out their name."
* while Loop:
* Purpose: Best when you don't know exactly how many repetitions are needed, but you
know a condition that, when false, should stop the repetition. The loop continues as long as
a specified condition remains true.
* Example: Think about playing a game where you continue "WHILE your score is below
100." You don't know how many rounds it will take to reach 100, but you stop once the
condition (score below 100) becomes false.
* do-while Loop:
* Purpose: Similar to while, but guarantees at least one execution of the loop's body
before checking the condition. Useful when you need to perform an action at least once, and
then decide whether to continue based on the result of that action.
* Example: Imagine a game where you must make at least one move (DO the move).
After that move, you check if you've won (WHILE you haven't won). Even if your very first
move wins, you still made that one move.

3. a) What is an array? What are the advantages of an array?


* What is an Array?
An array is a collection of similar data items stored at contiguous (next to each other)
memory locations. Think of it as a list or a series of boxes, all designed to hold the same type
of thing (e.g., all numbers, or all names). Each box has a unique number (index) starting from
0, which allows you to access its contents directly.
* Example: If you want to store the ages of 5 friends, instead of creating 5 separate
variables like friend1_age, friend2_age, etc., you could use one array called ages that holds
all 5 ages: ages[0], ages[1], ages[2], ages[3], ages[4].
* Advantages of an Array:
* Efficient Data Storage: It allows you to store a large number of related items under a
single variable name, making your code cleaner and more organized.
* Random Access: You can directly access any element in an array using its index. You
don't need to go through all previous elements to reach a specific one.
* Example: If you want to find the age of your 3rd friend in the ages array, you just go to
ages[2] (since indexing starts from 0). You don't need to check ages[0] and ages[1] first.
* Easy Traversal: It's very easy to loop through all elements of an array, which is useful for
performing operations on every item (like calculating a sum or finding the largest value).
* Example: To find the average age of all 5 friends, you can use a loop that goes from
ages[0] to ages[4], adding each age to a total.
* Used in Other Data Structures: Arrays form the basis for many other complex data
structures like stacks, queues, hash tables, and matrices.
* Performance: Accessing array elements is generally very fast due to their contiguous
memory allocation.
Section 2: Programming Questions (Turbo C++ specific, no comments)

1. b) Write a program in C to reverse a number (Hints: Input 12030 output: 3021).


#include<stdio.h>
#include<conio.h>
void main() {
int n, reversed_n = 0, remainder;
clrscr();
printf("Enter an integer: ");
scanf("%d",&n);
while (n != 0) {
remainder = n % 10;
reversed_n = reversed_n * 10 + remainder;
n /= 10;
}
printf("Reversed number: %d\n", reversed_n);
getch();
}

Example:
Input:
Enter an integer: 12030
Output:
Reversed number: 3021

2. b) Write a program in C to find the sum of the following series sum = 1 + 2^2 + 2^3 + ... +
2^n
#include<stdio.h>
#include<math.h>// For pow() function
#include<conio.h>
void main() {
int n, i;
long double sum = 0; // Use long double for potentially large sums
clrscr();
printf("Enter the value of n: ");
scanf("%d",&n);
if (n < 1) {
printf("Please enter a positive integer for n.\n");
getch();
return;
}
sum = 1; // Start with the first term '1'
for (i = 2; i <= n; i++) {
sum += pow(2, i);
}
printf("Sum of the series = %.0Lf\n", sum); // Use %Lf for long double
getch();
}

Example:
Input:
Enter the value of n: 3
Output:
Sum of the series = 13

Self-check for n=3: 1 + 2^2 + 2^3 = 1 + 4 + 8 = 13. Correct.


3. b) Write a program in C to reverse the elements of array.
(This is a duplicate of the previous array questions, so the same code applies.)
#include<stdio.h>
#include<conio.h>
void main() {
int a[100], n, i, temp;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
printf("Enter %d elements:\n", n);
for(i=0; i<n; i++)
scanf("%d",&a[i]);
for(i=0; i<n/2; i++) {
temp = a[i];
a[i] = a[n-i-1];
a[n-i-1] = temp;
}
printf("Reversed array: ");
for(i=0; i<n; i++)
printf("%d ", a[i]);
getch();
}

Example:
Input:
Enter number of elements: 4
Enter 4 elements:
1234
Output:
Reversed array: 4 3 2 1

4. a) Sort the following data items using bubble sort.


10 9 20 40 2 7
Let's walk through the Bubble Sort process step-by-step for the given data:
Initial Array: [10, 9, 20, 40, 2, 7]
Pass 1:
* (10, 9) -> Swap: [9, 10, 20, 40, 2, 7]
* (10, 20) -> No Swap: [9, 10, 20, 40, 2, 7]
* (20, 40) -> No Swap: [9, 10, 20, 40, 2, 7]
* (40, 2) -> Swap: [9, 10, 20, 2, 40, 7]
* (40, 7) -> Swap: [9, 10, 20, 2, 7, 40]
End of Pass 1. Largest element (40) is at its correct last position.
Pass 2:
* (9, 10) -> No Swap: [9, 10, 20, 2, 7, 40]
* (10, 20) -> No Swap: [9, 10, 20, 2, 7, 40]
* (20, 2) -> Swap: [9, 10, 2, 20, 7, 40]
* (20, 7) -> Swap: [9, 10, 2, 7, 20, 40]
End of Pass 2. Second largest (20) is in place.
Pass 3:
* (9, 10) -> No Swap: [9, 10, 2, 7, 20, 40]
* (10, 2) -> Swap: [9, 2, 10, 7, 20, 40]
* (10, 7) -> Swap: [9, 2, 7, 10, 20, 40]
End of Pass 3. Third largest (10) is in place.
Pass 4:
* (9, 2) -> Swap: [2, 9, 7, 10, 20, 40]
* (9, 7) -> Swap: [2, 7, 9, 10, 20, 40]
End of Pass 4. Fourth largest (9) is in place.
Pass 5:
* (2, 7) -> No Swap: [2, 7, 9, 10, 20, 40]
End of Pass 5. Array is sorted.
Sorted Array: [2, 7, 9, 10, 20, 40]

4. b) Write a program in C to implement linear search.


#include<stdio.h>
#include<conio.h>
void main() {
int a[100], n, i, search_element, found_at = -1;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
printf("Enter %d elements:\n", n);
for(i=0; i<n; i++)
scanf("%d",&a[i]);
printf("Enter element to search: ");
scanf("%d",&search_element);
for(i=0; i<n; i++) {
if (a[i] == search_element) {
found_at = i;
break; // Element found, no need to continue search
}
}
if (found_at != -1) {
printf("%d found at index %d.\n", search_element, found_at);
} else {
printf("%d not found in the array.\n", search_element);
}
getch();
}

Example 1 (Element Found):


Input:
Enter number of elements: 5
Enter 5 elements:
10 20 30 40 50
Enter element to search: 30
Output:
30 found at index 2.
Example 2 (Element Not Found):
Input:
Enter number of elements: 4
Enter 4 elements:
5 15 25 35
Enter element to search: 20
Output:
20 not found in the array.

1. a) What is a loop? What are the different parts of a loop?


* What is a Loop?
A loop in programming is a sequence of instructions that is repeated until a certain
condition is met. It's a way to automate repetitive tasks. Imagine you have a chore chart:
"Clean your room every Saturday." The "cleaning your room" is the action that loops, and
"every Saturday" sets the condition for when it happens again.
* Different Parts of a Loop:
* Initialization: This is where you set up a starting point for your loop. It's usually done once
before the loop begins.
* Example: If you're counting how many times you jump rope, you'd start by saying, "My
jump count is 0." (Initial count = 0)
* Condition (or Test Expression): This is a statement that is evaluated before or after each
repetition. If the condition is true, the loop continues; if it's false, the loop stops.
* Example: You continue jumping rope "as long as your jump count is less than 100."
(Condition: jump_count < 100)
* Body of the Loop: This is the block of code or instructions that gets executed repeatedly
during each iteration.
* Example: The action you perform is "jump rope one more time." (Body: Increment
jump_count)
* Update (or Increment/Decrement): This is an action that changes the loop control
variable or state, bringing the loop closer to its termination condition. Without it, the loop
might run forever.
* Example: After each jump, you update your count: "My jump count is now one higher."
(Update: jump_count++)

1. b) What is infinite loop? Give an example.


* What is an Infinite Loop?
An infinite loop is a sequence of instructions in a computer program that loops endlessly,
either because it has no terminating condition, or because the condition is never met. It's
like being stuck in a never-ending cycle, typically a mistake in programming that prevents
the program from progressing.
* Example:
Imagine you're trying to escape a maze. Your instruction is: "Keep walking straight until
you see a wall." If you're put in a maze where the path just goes straight forever without any
walls, you would walk straight endlessly. You would never reach an end, because the
condition to stop ("see a wall") is never fulfilled. In programming, this happens when the
condition for a loop always remains true.
Section 2: Programming Questions (Turbo C++ specific, short, easy, no comments)

1. c) Write a program in C/C++ to test a number is prime or not.


A prime number is a natural number greater than 1 that has no positive divisors other than 1
and itself.
#include<stdio.h>
#include<conio.h>
void main() {
int n, i, is_prime = 1; // Assume it's prime initially
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);

if (n <= 1) { // Numbers less than or equal to 1 are not prime


is_prime = 0;
} else {
for (i = 2; i <= n / 2; i++) { // Check for divisors from 2 up to n/2
if (n % i == 0) { // If n is divisible by i, it's not prime
is_prime = 0;
break; // No need to check further
}
}
}

if (is_prime == 1) {
printf("%d is a prime number.\n", n);
} else {
printf("%d is not a prime number.\n", n);
}
getch();
}

Example 1 (Prime):
Input:
Enter a positive integer: 7
Output:
7 is a prime number.
Example 2 (Not Prime):
Input:
Enter a positive integer: 1
Output:
10 is not a prime number.

2. a) Write a recursive algorithm to find the N-th Fibonacci number.


A recursive algorithm solves a problem by calling itself as a sub-routine, breaking down a
complex problem into simpler sub-problems of the same type.
The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the
two preceding ones.
Sequence: 0, 1, 1, 2, 3, 5, 8, 13, ...
(F0=0, F1=1, F2=1, F3=2, F4=3, F5=5, etc.)
Algorithm for N-th Fibonacci Number (Recursive):
* Base Cases:
* If n is 0, the Fibonacci number is 0.
* If n is 1, the Fibonacci number is 1.
* Recursive Step:
* If n is greater than 1, the Fibonacci number at n is the sum of the Fibonacci number at
(n-1) and the Fibonacci number at (n-2).
* Fib(n) = Fib(n-1) + Fib(n-2)
Simple Example Trace (Finding Fib(4)):
* Fib(4) needs Fib(3) + Fib(2)
* Fib(3) needs Fib(2) + Fib(1)
* Fib(2) needs Fib(1) + Fib(0)
* Fib(1) is 1 (Base Case)
* Fib(0) is 0 (Base Case)
* So, Fib(2) = 1 + 0 = 1
* Fib(1) is 1 (Base Case)
* So, Fib(3) = 1 + 1 = 2
* Fib(2) is 1 (already calculated above)
* So, Fib(4) = 2 + 1 = 3

2. b) Write a program in C/C++ to find the maximum value from an array.


#include<stdio.h>
#include<conio.h>

void main() {
int a[100], n, i, max_val;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
printf("Enter %d elements:\n", n);
for(i=0; i<n; i++)
scanf("%d",&a[i]);

if (n <= 0) {
printf("Array is empty or invalid size.\n");
getch();
return;
}
max_val = a[0]; // Assume first element is max
for(i=1; i<n; i++) { // Start from second element
if (a[i] > max_val) {
max_val = a[i]; // Update max_val if a larger element is found
}
}
printf("Maximum value in the array: %d\n", max_val);
getch();
}

Example:
Input:
Enter number of elements: 5
Enter 5 elements:
12 45 6 78 30
Output:
Maximum value in the array: 78

2. c) State and explain the Tower of Hanoi problem.


* State the Tower of Hanoi Problem:
The Tower of Hanoi is a classic mathematical puzzle consisting of three pegs and a
number of disks of different sizes. The objective is to move all the disks from a starting peg
to a destination peg, following these three rules:
* Only one disk can be moved at a time.
* Each move consists of taking the upper disk from one of the stacks and placing it on top
of another stack or on an empty peg.
* No disk may be placed on top of a smaller disk.
* Explanation:
Imagine you have three poles (let's call them Source, Destination, and Auxiliary) and a set
of rings of decreasing size stacked on the Source pole (largest at the bottom, smallest at the
top). Your goal is to move the entire stack of rings to the Destination pole.
The beauty of the Tower of Hanoi lies in its elegant recursive solution. To move N disks
from Source to Destination using Auxiliary, you follow these steps:
* Move N-1 disks from Source to Auxiliary: This is the tricky part, as it's a smaller version of
the original problem. You pretend the largest disk isn't there and focus on moving the N-1
disks out of the way to the "middle" pole.
* Move the N-th (largest) disk from Source to Destination: Once the smaller disks are out
of the way, you can freely move the largest disk directly to its final spot.
* Move the N-1 disks from Auxiliary to Destination: Now, you treat the Auxiliary pole as
your new Source and move the stack of N-1 disks on top of the largest disk on the
Destination pole.
This process breaks down the problem into smaller, identical sub-problems, making it a
perfect example of how recursion works. For example, if you have 3 disks:
* Move disk 1 and 2 from Source to Auxiliary (this is N-1 disks, a sub-problem).
* Move disk 3 (largest) from Source to Destination.
* Move disk 1 and 2 from Auxiliary to Destination (another N-1 sub-problem).
The minimum number of moves required to solve the Tower of Hanoi problem with N disks
is 2^N - 1.

Section 1: Theoretical Questions (Descriptive answers with easy, non-coding examples)

1. a) What is loop? How many parts are there in a loop? Explain with example.

* What is a Loop?

A loop is like a repeated instruction. Imagine you're making cookies and the recipe says,
"Stir the batter until smooth." You keep doing the "stirring" action over and over until the
batter is smooth. That repeated action, governed by a condition, is what a loop does in
programming. It lets the computer do the same task many times without you having to write
the instruction multiple times.

* How many parts are there in a loop? Explain with example.

A typical loop has four main parts that work together to control its repetition:

* Initialization: This is where you set up a starting point before the loop begins. Think of it
as preparing for the first step.

* Example: You want to count how many times you bounce a ball. Before you start, you
say, "My bounces count is zero." (You initialize bounces = 0).

* Condition (or Test): This is a rule that the loop checks before (or sometimes after) each
repetition. If the rule is true, the loop continues; if it's false, the loop stops.

* Example: You continue bouncing the ball "as long as my bounces count is less than 10."
(The condition is bounces < 10).

* Body of the Loop: This is the actual set of actions or instructions that get repeated each
time the loop runs.
* Example: The action you perform is "bounce the ball once." (This is the loop's body).

* Update (or Increment/Decrement): After the body of the loop is executed, something
needs to change to bring the loop closer to stopping. If nothing changes, the loop might run
forever.

* Example: After each bounce, you update your count: "Now my bounces count is one
higher." (You update bounces++).

1. c) What is infinite loop? Give example.

* What is an Infinite Loop?

An infinite loop is a loop that never stops. It runs forever because its condition for stopping
is never met, or there's no condition at all. It's usually a mistake in programming, causing the
program to get stuck and not move forward.

* Example:

Imagine a robot is programmed with the instruction: "Walk forward one step. If you have
not reached the wall, repeat." Now, imagine the robot is placed on an infinitely long path
with no wall anywhere. The robot will just keep walking forward, step after step, forever,
because it will never reach the condition "reached the wall" that would tell it to stop. This is
an infinite loop in action.

2. a) What is an array? What are the properties of an array?

* What is an Array?

An array is like a series of connected storage boxes, all designed to hold the same kind of
items. For example, if you want to store the scores of 10 students in a test, instead of
creating 10 separate variables (score1, score2, etc.), you can create one array called scores
that holds all 10 scores. Each box in the array has a number (called an "index") starting from
0, so you can easily point to any specific score, like scores[0] for the first student's score,
scores[1] for the second, and so on.

* What are the properties of an array?

* Fixed Size (Usually): Once an array is created, its size (how many items it can hold) is
usually set and cannot be changed later. If you declared an array for 10 scores, it can only
hold 10, not 11 or 9.

* Homogeneous Elements: All items stored in an array must be of the same data type. You
can't store a number and a word in the same array of numbers. If it's an array of integers, all
elements must be integers.
* Contiguous Memory Location: The items in an array are stored one after another in
memory, right next to each other. This makes it very fast to access any element.

* Random Access (Indexed Access): You can directly access any element in an array by
simply knowing its position (its index). You don't have to start from the beginning and go
through each item one by one.

* Example: If you want the 5th student's score, you just go directly to scores[4].

* Zero-Based Indexing: In most programming languages (like C/C++), the first element of
an array is at index 0, the second at index 1, and so on. So, an array of 10 elements will have
indices from 0 to 9.

2. c) What are the benefits of using function in programming?

* What are the benefits of using functions in programming?

Functions are like mini-programs or specialized tools that you can define once and then
use multiple times in your main program. They help make your code better in several ways:

* Code Reusability: Instead of writing the same lines of code over and over again whenever
you need to perform a specific task, you can put those lines into a function. Then, you just
"call" that function whenever you need that task done.

* Example: If you frequently need to calculate the area of a circle, you can write an
calculate_circle_area() function once. Then, every time you need an area, you just call this
function instead of rewriting the formula.

* Modularity (Breaking Down Problems): Functions help you break down a large, complex
problem into smaller, more manageable pieces. Each function can handle a specific part of
the overall task. This makes the program easier to understand, design, and manage.

* Example: For building a house, instead of one giant plan, you have separate plans for
"building the foundation," "framing the walls," "installing plumbing," etc. Each plan is like a
function, making the whole project manageable.

* Easier Debugging: When your program has an error (a "bug"), if it's divided into functions,
you can often pinpoint which specific function is causing the problem. This makes it much
faster to find and fix errors.

* Example: If your house's lights aren't working, you check the "electrical wiring" function,
not the entire house.

* Improved Readability: Programs organized with functions are easier for humans to read
and understand. Each function has a clear purpose, making the overall flow of the program
more apparent.

* Example: Reading a story with chapters is easier than reading one long continuous text.
Each function is like a chapter.
* Reduced Code Duplication: By reusing functions, you write less code overall. Less code
means fewer chances for mistakes and an easier time making changes.

* Example: Instead of giving the instruction "mix sugar, flour, eggs" for every cake recipe,
you just say "make batter" if you have a make_batter() function.

Section 3: Programming Questions (Turbo C++ specific, short, easy, no comments)

1. b) Write a program in C/C++ to test a number is prime or not.

#include<stdio.h>

#include<conio.h>

void main() {

int n, i, is_prime = 1;

clrscr();

printf("Enter a positive integer: ");

scanf("%d",&n);

if (n <= 1) {

is_prime = 0;

} else {

for (i = 2; i <= n / 2; i++) {

if (n % i == 0) {

is_prime = 0;

break;

if (is_prime == 1) {

printf("%d is a prime number.\n", n);

} else {

printf("%d is not a prime number.\n", n);

}
getch();

Example 1 (Prime):

Input:

Enter a positive integer: 13

Output:

13 is a prime number.

Example 2 (Not Prime):

Input:

Enter a positive integer: 9

Output:

9 is not a prime number.

2. b) Write a program in C/C++ to find whether a number is, prime or not using function.

#include<stdio.h>

#include<conio.h>

// Function to check if a number is prime

int isPrime(int num) {

int i;

if (num <= 1) {

return 0; // Not prime

for (i = 2; i <= num / 2; i++) {

if (num % i == 0) {

return 0; // Not prime

return 1; // Prime
}

void main() {

int n;

clrscr();

printf("Enter a positive integer: ");

scanf("%d",&n);

if (isPrime(n) == 1) {

printf("%d is a prime number.\n", n);

} else {

printf("%d is not a prime number.\n", n);

getch();

Example 1 (Prime):

Input:

Enter a positive integer: 29

Output:

29 is a prime number.

Example 2 (Not Prime):

Input:

Enter a positive integer: 18

Output:

18 is not a prime number.

1. a) What is loop? How many parts are there in a loop? Explain with example.
* What is a Loop?
Imagine you have a task that you need to do over and over again, like putting one toy car
into a box until the box is full. Instead of telling you "Put car, put car, put car..." many times, I
can just say, "Keep putting a car in the box until it's full." The "keep putting a car in the box"
part, repeated until a condition is met, is what a loop does in programming. It makes the
computer repeat actions.
* How many parts are there in a loop? Explain with example.
A typical loop has four main "ingredients" or steps that help it work correctly:
* Initialization: This is where you set things up at the very beginning, before the repeating
starts. It's like setting a counter to zero before you begin counting.
* Example: If you're counting how many stickers you put on a page, you'd start by saying,
"My sticker count is zero." (You initialize sticker_count = 0).
* Condition (or Test): This is a rule that the loop checks each time before it decides if it
should repeat the action again. If the rule is true, the loop continues; if it's false, the loop
stops.
* Example: You continue putting stickers on the page "as long as my sticker count is less
than 10." (The condition is sticker_count < 10).
* Body of the Loop: This is the actual action or set of instructions that gets repeated each
time the loop runs.
* Example: The action you perform is "put one sticker on the page." (This is the loop's
body).
* Update (or Increment/Decrement): After the action is done one time, something needs
to change to bring the loop closer to stopping. If nothing changes, the loop might never end.
* Example: After putting a sticker, you update your count: "Now my sticker count is one
higher." (You update sticker_count++).
Section 2: Programming Questions (Turbo C++ specific, short, easy, no comments)

1. b) Write a program in C/C++/Python to find a number is prime or not.


(Using C/C++ for Turbo C++ as per your request)
#include<stdio.h>
#include<conio.h>

void main() {
int n, i, is_prime = 1;
clrscr();
printf("Enter a positive integer: ");
scanf("%d",&n);

if (n <= 1) {
is_prime = 0;
} else {
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
is_prime = 0;
break;
}
}
}

if (is_prime == 1) {
printf("%d is a prime number.\n", n);
} else {
printf("%d is not a prime number.\n", n);
}
getch();
}
Example 1 (Prime):
Input:
Enter a positive integer: 5
Output:
5 is a prime number.
Example 2 (Not Prime):
Input:
Enter a positive integer: 8
Output:
8 is not a prime number.

1. c) Write the following code by using while and do-while loop.


The given code is:
prime = 0;
for(i = 0; i < n; i++)
{
prime = prime + a[i];
}
avg = (float) prime / n;

This code snippet calculates the sum of elements in an array a and then calculates their
average. I'll translate it to use while and do-while loops.
Using while loop:
#include<stdio.h>
#include<conio.h>
void main() {
int a[100], n, i = 0;
int sum_of_elements = 0; // Renamed 'prime' for accurate representation
float avg;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);

if (n <= 0) { // Added a check for valid 'n' before input/calculation


printf("Number of elements must be positive.\n");
getch();
return;
}
printf("Enter %d elements:\n", n);
// Input elements
while (i < n) {
scanf("%d",&a[i]);
i++;
}
// Reset i for summation
i = 0;
while (i < n) {
sum_of_elements = sum_of_elements + a[i];
i++;
}
avg = (float) sum_of_elements / n;
printf("Sum of elements: %d\n", sum_of_elements);
printf("Average: %.2f\n", avg);
getch();
}

Example:
Input:
Enter number of elements: 3
Enter 3 elements:
10 20 30

Output:
Sum of elements: 60
Average: 20.00

Using do-while loop:


#include<stdio.h>
#include<conio.h>
void main() {
int a[100], n, i = 0;
int sum_of_elements = 0; // Renamed 'prime' for accurate representation
float avg;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
if (n <= 0) { // Added a check for valid 'n' before input/calculation
printf("Number of elements must be positive.\n");
getch();
return;
}
printf("Enter %d elements:\n", n);
// Input elements
i = 0;
do {
scanf("%d",&a[i]);
i++;
} while (i < n);

// Reset i for summation


i = 0;
do {
sum_of_elements = sum_of_elements + a[i];
i++;
} while (i < n);

avg = (float) sum_of_elements / n;


printf("Sum of elements: %d\n", sum_of_elements);
printf("Average: %.2f\n", avg);

getch();
}

Example:
Input:
Enter number of elements: 4
Enter 4 elements:
5 10 15 20
Output:
Sum of elements: 50
Average: 12.50

2. a) What is the difference between a function and a procedure? Explain with easy
examples as if I read in class 2.
* What is the difference between a function and a procedure?
Let's think of your favorite toys and how they work.
* A Function is like a toy that you play with, and when you're done, it gives you something
back, an answer, or a result.
* Example: Imagine you have a special toy calculator. You put in "2" and "3" and press the
"add" button. The calculator does its job (adds them) and then shows you a number: "5". That
"5" is the answer it gives you back.
* A Procedure is like a toy that you make do something, but it doesn't give you anything
back as a specific answer or result. It just performs an action.
* Example: Imagine you have a robot toy. You tell it, "Robot, wave your hand!" The robot
does its job (waves its hand). But it doesn't give you a number or a new toy back. It just
completed the action you asked it to do.
The main difference:
* Functions give you an answer or result.
* Procedures just do an action.

2. b) What is an array? State the properties of an array.


* What is an array?
An array is like a single, organized box that has many separate sections inside it. All these
sections are designed to hold the same type of items. For example, if you want to keep track
of the scores from 5 games, instead of using 5 different labels like "game1score,"
"game2score," etc., you can use one big box called "gameScores" with 5 sections. Each
section has a number (like 0, 1, 2, 3, 4) so you can easily find any score, like gameScores[0]
for the first game's score.
* State the properties of an array.
Arrays have a few key things that make them special:
* Fixed Size (usually): Once you decide how many items your array box can hold (its size)
when you first create it, that size usually cannot be changed later. If you make a box for 5
game scores, it can always hold 5, no more, no less.
* Same Type of Items (Homogeneous): All the items you put into an array must be of the
exact same kind. You can't mix numbers and words in the same array; if it's an array for
numbers, only numbers go in.
* Memory is Side-by-Side (Contiguous): The items in an array are stored one right after the
other in the computer's memory, like books neatly lined up on a shelf. This makes it very fast
for the computer to find any item.
* Direct Access by Position (Indexed): You can go straight to any item in the array just by
knowing its position number (its "index"). You don't have to start from the beginning and look
at every item one by one.
* Example: If you want the score for the 3rd game, you go directly to gameScores[2]
(because counting usually starts from 0).
* Starts Counting from Zero (Zero-Based Indexing): In most programming languages (like
C and C++), the very first item in an array is at position 0, the second at position 1, the third
at position 2, and so on. So, an array with 5 items will have positions from 0 to 4.
Section 2: Programming Questions (Turbo C++ specific, short, easy, no comments)

2. c) Write down a program in C/C++/Python to reverse the content of an array.


(Using C/C++ for Turbo C++ as per your request)
#include<stdio.h>
#include<conio.h>

void main() {
int a[100], n, i, temp;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
printf("Enter %d elements:\n", n);
for(i=0; i<n; i++)
scanf("%d",&a[i]);

for(i=0; i<n/2; i++) {


temp = a[i];
a[i] = a[n-i-1];
a[n-i-1] = temp;
}
printf("Reversed array: ");
for(i=0; i<n; i++)
printf("%d ", a[i]);
getch();
}

Example:
Input:
Enter number of elements: 5
Enter 5 elements:
12345

Output:
Reversed array: 5 4 3 2 1

You might also like