Solved Question Paper : MGKVP BCA I Sem 2022 , Programming Principle & Algorithm ( PPA )
******************
1.Write down the structure of a C program. how can we use functions as the building block of the program ?illustrate with an example.
Answer:
The structure of a C program typically consists of:
Preprocessor Directives: These are statements that instruct the compiler to include certain header files or perform certain pre-processing tasks before compiling the main program.
#include <stdio.h>
Function Prototypes: These are declarations of the functions that will be used in the program, including their return type, function name, and parameter types.
int add(int num1, int num2);
Main Function: This is the starting point of the program, where execution begins. It can call other functions as needed.
int main() {
int result = add(3, 5);
printf("The result is %d\n", result);
return 0;
}
Function Definitions: These are the actual implementations of the functions declared in the function prototypes.
int add(int num1, int num2) {
return num1 + num2;
}
Here is an example program that uses functions as building blocks:
#include <stdio.h>
// Function prototype
int add(int num1, int num2);
int main() {
int result = add(3, 5);
printf("The result is %d\n", result);
return 0;
}
// Function definition
int add(int num1, int num2) {
return num1 + num2;
}
In this example, the add() function takes two integer parameters and returns their sum. The main() function calls the add() function with arguments 3 and 5, and then prints the result to the console. By using functions in this way, we can create modular, reusable code that is easier to understand and maintain.
////////////////////
2. Explain with examples, the following in a c program
(a)Variable
(b)Data type
(c)Operator precedence
(d)Break and continue
Answer:
(a) Variables: Variables are storage locations in a computer's memory where we can store data. In C, we declare variables with a data type and a name, and optionally assign an initial value to them. Here is an example
#include <stdio.h>
int main() {
int age = 20; // declaring an integer variable called age and assigning it a value of 20
float price = 9.99; // declaring a float variable called price and assigning it a value of 9.99
char grade = 'A'; // declaring a character variable called grade and assigning it a value of 'A'
printf("Age: %d, Price: %f, Grade: %c\n", age, price, grade); // printing the values of the variables
return 0;
}
In this example, we declare and initialize three variables of different data types - age, price, and grade - and then print their values to the console using the printf() function.
(b) Data Types: Data types in C specify the type of data that a variable can hold. Some common data types in C include int, float, char, and double. Here is an example:
#include <stdio.h>
int main() {
int num = 10; // declaring an integer variable called num and assigning it a value of 10
float price = 9.99; // declaring a float variable called price and assigning it a value of 9.99
char letter = 'A'; // declaring a character variable called letter and assigning it a value of 'A'
printf("Num: %d, Price: %f, Letter: %c\n", num, price, letter); // printing the values of the variables
return 0;
}
In this example, we declare and initialize three variables of different data types - num, price, and letter - and then print their values to the console using the printf() function.
(c) Operator Precedence: Operator precedence in C determines the order in which operators are evaluated in an expression. For example, in the expression 2 + 3 * 4, the multiplication operator * has higher precedence than the addition operator +, so the expression is evaluated as 2 + (3 * 4), which gives a result of 14. Here is an example:
#include <stdio.h>
int main() {
int result = 2 + 3 * 4; // evaluating the expression 2 + 3 * 4
printf("Result: %d\n", result); // printing the result
return 0;
}
In this example, we use the + and * operators in an expression, and the expression is evaluated according to operator precedence.
(d) Break and Continue: The break and continue statements are used to control the flow of a loop. The break statement is used to terminate a loop prematurely, while the continue statement is used to skip over an iteration of a loop. Here is an example:
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) { // using a for loop
if (i == 5) {
break; // terminating the loop when i equals 5
}
printf("%d\n", i);
}
for (i = 1; i <= 10; i++) { // using a for loop
if (i == 5) {
continue; // skipping over the iteration
////////////////////////////
3. Differentiate between followings with the help of examples
(a)While and do-while
(b)Algorithm and flow chart
(c)If-else and switch statements
Answer:
(a)while loop in C:
The while loop in C executes a set of statements repeatedly until the condition specified in the loop becomes false. In the while loop, the condition is checked before the execution of the loop body. Here is an example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5); // using a do-while loop
return 0;
}
do-while loop in C:
The do-while loop in C executes a set of statements at least once, and then repeatedly until the condition specified in the loop becomes false. In the do-while loop, the condition is checked after the execution of the loop body. Here is an example
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5); // using a do-while loop
return 0;
}
(b) Algorithm and flow chart
Algorithm Flowchart
An algorithm is a step-by-step procedure to solve a problem. while a flowchart is a diagram created with different shapes to show the flow of data.
The algorithm is complex to understand. while a flowchart is easy to understand.
In the algorithm, plain text is used. In the flowchart, symbols/shapes are used.
The algorithm is easy to debug. while a flowchart is hard to debug.
The algorithm is difficult to construct. A flowchart is simple to construct.
The algorithm does not follow any rules. The flowchart follows rules to be constructed.
/////////////////////
(c) Differentiate between if else and switch statements with an example
Answer:
If-else and switch statements are both used in programming to control the flow of execution based on certain conditions.
The if-else statement is a conditional statement that evaluates a Boolean expression, and executes one block of code if the expression is true, and another block of code if the expression is false. It is often used when there are only two possible outcomes. Here's an example:
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
} else {
printf("x is less than or equal to 5\n");
}
In this example, the if-else statement checks if x is greater than 5. If the condition is true, the first block of code will execute and print "x is greater than 5". If the condition is false, the second block of code will execute and print "x is less than or equal to 5".
On the other hand, the switch statement is used to execute one of several blocks of code based on the value of a variable or expression. It is often used when there are multiple possible outcomes. Here's an example:
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Invalid day\n");
break;
}
In this example, the switch statement checks the value of day. If day is 1, the first block of code will execute and print "Monday". If day is 2, the second block of code will execute and print "Tuesday". If day is 3, the third block of code will execute and print "Wednesday". If day does not match any of the cases, the default block of code will execute and print "Invalid day". The break statement is used to exit the switch statement once a match is found.
////////////////////////////////
4. (a) What is pseudo code? Where is it used?
Answer:
Pseudocode is a high-level, informal language that is used to express the basic steps involved in solving a problem or performing a task, without being tied to a specific programming language. It is typically used as an intermediate step between the problem-solving phase and the implementation phase of a software project.
Pseudocode is designed to be easy to read and understand, even for non-technical stakeholders such as project managers and end-users. It uses natural language constructs, such as "if-then" statements, loops, and variables, to describe the logical flow of a program.
Pseudocode is used in a variety of contexts, including:
Algorithm development: Pseudocode is often used to develop and refine algorithms before they are translated into a specific programming language.
Documentation: Pseudocode can be used to document the logic of a program, making it easier for other developers to understand and maintain.
Communication: Pseudocode can be used to communicate ideas and concepts between developers, project managers, and other stakeholders.
Education: Pseudocode is often used as a teaching tool in computer science courses, as it allows students to focus on the logic and structure of a program without getting bogged down in the details of a specific programming language.
///////////////////////////////
4. (b) Write the flowchart and the algorithm for finding the sum of n terms of the Fibonacci series of numbers.
Answer:
Here's a flowchart and algorithm for finding the sum of n terms of the Fibonacci series:
Algorithm:
Start
Take input n
Initialize variables a=0, b=1, sum=0, count=1
while(count<=n)
set c=a+b
add b to a, assign b to c
add b to sum
add 1 to count
Display sum
End
Flow chart
////////////////////////////
5. Write a program in c for reversing the digits of a number
Answer:
#include <stdio.h>
int main() {
int number, reversed = 0, remainder;
printf("Enter a number: ");
scanf("%d", &number);
while (number != 0) {
remainder = number % 10;
reversed = reversed * 10 + remainder;
number /= 10;
}
printf("The reversed number is: %d", reversed);
return 0;
}
//////////////////////
6. Write a program in c for the computation of the factorial value of a number by using the method of recursion.
Answer :
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n;
printf("Enter a non-negative integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Error: Input must be non-negative.");
} else {
int result = factorial(n);
printf("%d! = %d", n, result);
}
return 0;
}
7. (a) What is meant by function prototype? What information does it convey to a c compiler?
Answer :
A function prototype in C is a declaration of a function that provides the compiler with information about the function's return type, name, and parameters. A function prototype typically appears at the beginning of a program or in a header file, before the function is actually defined or called.
The syntax for a function prototype in C is as follows:
return_type function_name(parameter_list);
Here, return_type is the data type of the value returned by the function, function_name is the name of the function, and parameter_list is the list of input parameters to the function, along with their data types.
When a C compiler encounters a function prototype, it uses the information provided to ensure that any subsequent calls to the function are correct and that the function is defined correctly elsewhere in the program. Specifically, the function prototype conveys the following information to the compiler:
The return type of the function: This tells the compiler what type of value the function returns.
The name of the function: This allows the compiler to identify the function and link any calls to the function with its definition.
The parameter list of the function: This tells the compiler the number, order, and data types of the input parameters to the function. This information is used to check that any calls to the function pass the correct number and type of arguments.
By providing the compiler with this information, function prototypes help ensure that function calls are correct and that the program is compiled successfully.
7.(b) Distinguish between function call and function body with an example function defined by you.
Answer:
Consider the following function named multiply_numbers that takes two arguments and returns their product:
def multiply_numbers(x, y):
product = x * y
return product
In the code above, the def keyword is used to define a function called multiply_numbers that takes two arguments named x and y. The body of the function is the indented block of code between the def statement and the return statement.
The function body contains the instructions that the function executes when it is called. In this case, the function calculates the product of the two arguments x and y and assigns it to the variable product, and then returns the value of product.
To call this function and use its functionality, you need to invoke it with appropriate arguments. For example, you can call multiply_numbers function with the following statement:
result = multiply_numbers(2, 3)
In the code above, the function is called by its name multiply_numbers, passing arguments 2 and 3 to the function. The function calculates their product and returns it, which is then assigned to the variable result.
So, the function call is the statement that invokes a function with appropriate arguments to execute its functionality, while the function body is the block of code containing the instructions that the function executes when it is called.
//////////////////
8. Define recursion. Illustrate it by calling a recursive function that computes the gcd of two integers M,N.
Answer:
Recursion is a programming technique in which a function calls itself one or more times within its own code. Recursion is a powerful concept in computer science that can simplify complex problems by breaking them down into smaller, more manageable sub-problems.
To illustrate recursion, we can write a recursive function that computes the greatest common divisor (GCD) of two integers M and N. The GCD of two integers is the largest positive integer that divides both M and N without leaving a remainder.
Here's an example code in C++ that uses recursion to compute the GCD of two integers:
#include <iostream>
using namespace std;
int gcd(int m, int n) {
if (n == 0) {
return m;
}
else {
return gcd(n, m % n);
}
}
int main() {
int num1 = 24;
int num2 = 36;
int result = gcd(num1, num2);
cout << "GCD of " << num1 << " and " << num2 << " is " << result << endl;
return 0;
}
In this code, the gcd() function takes two integers M and N as inputs and returns their GCD using recursion.
The function first checks if N is equal to zero. If it is, then it returns M as the GCD. If N is not equal to zero, then the function calls itself recursively with the arguments (N, M % N), where % is the modulus operator that returns the remainder of the division of M by N.
The function keeps calling itself with smaller and smaller values of N until N becomes zero, at which point it returns the final value of M as the GCD.
In the main() function, we call the gcd() function with two integers 24 and 36, and store the result in the variable result. We then print out the result using cout. The output of this program will be:
GCD of 24 and 36 is 12
This demonstrates how recursion can be used to solve complex problems by breaking them down into simpler sub-problems. In this case, the GCD of two integers is computed by recursively finding the GCD of smaller and smaller pairs of integers until a base case is reached.
////////////////////////
9.Differentiate between
(i)Call by reference and call by value
(ii)Perfect number and prime number
(iii)Getchar() and putchar()
Answer:
(i) Call by reference and call by value:
Call by reference and call by value are two ways of passing arguments to a function in programming.
In call by value, a copy of the argument is passed to the function. Any changes made to the argument inside the function do not affect the original value of the argument outside the function. In other words, the function works with a copy of the original value.
In call by reference, the memory location of the argument is passed to the function. Any changes made to the argument inside the function affect the original value of the argument outside the function. In other words, the function works with the original value directly.
(ii) Perfect number and prime number:
A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). For example, 6 is a perfect number because its proper divisors are 1, 2, and 3, and 1 + 2 + 3 = 6.
A prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself. For example, 5 is a prime number because its only positive divisors are 1 and 5.
(iii) getchar() and putchar():
In C programming, getchar() and putchar() are two functions used for input and output of characters.
The getchar() function reads a single character from the standard input (usually the keyboard) and returns it as an integer. This function is commonly used in programs that require user input.
The putchar() function writes a single character to the standard output (usually the console). This function is commonly used in programs that require output to the user.
To summarize, getchar() reads a single character from the input stream, while putchar() writes a single character to the output stream.
********************************************************
0 Comments