210 QB Mid 2
210 QB Mid 2
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.
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
Example:
Input:
Enter number of elements: 4
Enter 4 elements:
1234
Output:
Reversed array: 4 3 2 1
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.
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
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.
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++).
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.
* 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.
* 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.
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.
#include<stdio.h>
#include<conio.h>
void main() {
int n, i, is_prime = 1;
clrscr();
scanf("%d",&n);
if (n <= 1) {
is_prime = 0;
} else {
if (n % i == 0) {
is_prime = 0;
break;
if (is_prime == 1) {
} else {
}
getch();
Example 1 (Prime):
Input:
Output:
13 is a prime number.
Input:
Output:
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>
int i;
if (num <= 1) {
if (num % i == 0) {
return 1; // Prime
}
void main() {
int n;
clrscr();
scanf("%d",&n);
if (isPrime(n) == 1) {
} else {
getch();
Example 1 (Prime):
Input:
Output:
29 is a prime number.
Input:
Output:
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)
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.
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);
Example:
Input:
Enter number of elements: 3
Enter 3 elements:
10 20 30
Output:
Sum of elements: 60
Average: 20.00
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.
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]);
Example:
Input:
Enter number of elements: 5
Enter 5 elements:
12345
Output:
Reversed array: 5 4 3 2 1