0% found this document useful (0 votes)
14 views

CSE PME Semester Final Question Solve

Uploaded by

Abrar Zahin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

CSE PME Semester Final Question Solve

Uploaded by

Abrar Zahin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

রিরিকেি মারিে আল্লাহ,

CGPA মানুকেি মাকে


ভেদাকেদ তৈরিি িনয
শয়ৈাকনি এেটা চাি মাত্র!
আমিা একে অপিকে
রিরেয়াস ইয়াকিি ভোকয়শ্চান
সিে েকি ভিাোইড েকি
ও শয়ৈাকনি কুিচনা হকৈ
রনকিকদি রিিৈ িারি।
Question:

Determine which of the following are valid identifiers. If invalid, state why.

1) a&b 2) 203N c) brake d) return e) 72Ekattor

Ans.: -

1. a&b - Invalid.
Reason: Contains the special character &.
2. 203N - Invalid.
Reason: Starts with a digit (2).
3. brake - Valid.
Reason: Follows all the rules.
4. return - Invalid.
Reason: return is a reserved keyword in most programming languages.
5. 72Ekattor - Invalid.
Reason: Starts with a digit (7).

Question:
What is a datatype format specifier? Write the format specifiers for the basic datatypes of C
language.

Ans.:-:

A datatype format specifier is a special character or sequence of characters used in C


programming to indicate the type of data to be read, printed, or processed. These
specifiers are used mainly with input/output functions like printf and scanf to specify
the type of variable being handled.

Format Specifiers for Basic Data Types in C:


Data Type Format Specifier
Data Type Format Specifier

int %d or %i

char %c

float %f

double %lf

short int %hd

long int %ld

long long int %lld

unsigned int %u

unsigned char %c (reads as a character) / %u (as an integer)

unsigned short int %hu

unsigned long int %lu

unsigned long long int %llu

string (character array) %s

long double %Lf

octal integer %o

hexadecimal integer %x or %X

pointer %p

Question:
What will be the output of the following C program: #include<stdio.h> void main() {int a=8,
b=7; a<b ? a++:a=b; printf("%d",a); }

Ans.:-:

Let's analyze the given C program step by step:

Code:
c
Copy code
#include<stdio.h>
void main() {
int a = 8, b = 7;
a < b ? a++ : a = b;
printf("%d", a);
}

Explanation:

1. Variable Initialization:
o a is initialized to 8.
o b is initialized to 7.
2. Ternary (Conditional) Operator:
o The expression a < b is evaluated.
o Since 8 is not less than 7, the condition a < b is false.
o When the condition is false, the expression after the colon ( :) is executed: a
= b.
3. Assignment:
o The statement a = b assigns the value of b (which is 7) to a.
o So, a becomes 7.
4. Print Statement:
o printf("%d", a); will print the value of a, which is now 7.

Output:
Copy code
7
4o

Question:
What are the static variables & functions? What is their scope?

Ans.:-:
ChatGPT

Static Variables:

A static variable in C is a variable that retains its value across function calls. Unlike
regular local variables that are created and destroyed each time a function is executed,
static variables persist throughout the lifetime of the program.

Key Characteristics:

1. Lifetime: The lifetime of a static variable is the entire duration of the program. It is
initialized only once and retains its value between function calls.
2. Scope: If declared inside a function, the scope of the static variable is limited to that
function. If declared outside all functions (at the global level), it is accessible only
within the same file, not from other files.
3. Initialization: Static variables are initialized to 0 by default if no explicit
initialization is provided.
Static Functions:

A static function in C is a function that can only be accessed within the file in which it is
declared. By declaring a function as static, it is made private to the file, preventing its use
in other source files, even if those files are linked together.

Key Characteristics:

1. Scope: The scope of a static function is limited to the file where it is defined. It
cannot be called from other files.
2. Use Case: Useful for implementing helper functions that are not meant to be
exposed to other parts of the program, maintaining encapsulation.

Question:
What is typecasting? Write the syntax of typecasting with an example.

Ans.:-:

What is Typecasting?

Typecasting is the process of converting a variable from one data type to another. In C,
typecasting allows you to manually change the data type of a variable, which can be
useful for various operations, such as mathematical calculations where different data
types need to be mixed, or to control how data is interpreted.

Types of Typecasting:

1. Implicit Typecasting (Automatic Type Conversion):


o Done automatically by the compiler when compatible types are used.
o Example: Assigning an int to a float.
2. Explicit Typecasting (Manual Type Conversion):
o Requires the programmer to manually specify the conversion.
o This is useful when you want to control how the conversion happens.
o Syntax: (type) expression

Syntax of Explicit Typecasting:


c
Copy code
(data_type) expression;

• data_type: The type you want to convert the expression to.


• expression: The variable or value you want to convert.

Example:
c
Copy code
#include <stdio.h>
int main() {
int a = 5, b = 2;
float result;

// Without typecasting
result = a / b;
printf("Without typecasting: %f\n", result); // Output: 2.000000

// With typecasting
result = (float) a / b;
printf("With typecasting: %f\n", result); // Output: 2.500000

return 0;
}

Explanation:

• Without Typecasting: When a (an int) is divided by b (another int), the result is
also treated as an int, which results in 2.
• With Typecasting: (float) a converts a to a float, so the division a / b is
treated as float division, giving a more precise result of 2.5.

4o

Question:
Differentiate between calloc() & malloc()

Ans.:-:
ChatGPT

calloc() and malloc() are two functions in C that are used for dynamic memory
allocation. Both are part of the C standard library (<stdlib.h>), but they have some key
differences in terms of usage and behavior.

Differences Between calloc() and malloc()


Feature malloc() calloc()

Memory Allocates multiple blocks of memory,


Allocates a single block of memory.
Allocation each of a specified size.

Does not initialize the allocated


Initializes all the allocated memory
Initialization memory; it contains garbage
blocks to zero.
values.

void *calloc(size_t num,


Syntax void *malloc(size_t size);
size_t size);

Parameters Takes one parameter: the total size Takes two parameters: the number of
Feature malloc() calloc()

in bytes. elements and the size of each element.

Generally faster because it does not Slightly slower due to the initialization
Speed
initialize memory. of memory.

When you do not need the memory When you want to ensure the memory
Use Case
to be initialized. is initialized to zero.

Question:
What is the difference between an array & a pointer.

Ans.:-:

Differences Between an Array and a Pointer in C


Feature Array Pointer

A collection of elements of the same


A variable that stores the address
Definition data type stored in contiguous
of another variable.
memory locations.

Memory can be allocated at


Memory
Memory is allocated at compile-time. runtime (using malloc, calloc,
Allocation
etc.).

Has a fixed size that cannot be Can point to different memory


Fixed Size
changed after declaration. locations and can be reallocated.

The name of an array represents the


A pointer is a variable that can be
Name Behavior address of the first element, but it is
assigned different addresses.
not a modifiable lvalue.

Supports full pointer arithmetic


Arithmetic Limited arithmetic (like incrementing
(incrementing, decrementing,
Operations the index).
adding offsets).

Accessed using dereferencing (*),


Accessing Accessed using the index (e.g.,
e.g., *(ptr + 2) for the 3rd
Elements arr[2]).
element.

Implicitly decays to a pointer to its Can be directly assigned to point to


Relationship
first element when passed to a an array or another address.
Feature Array Pointer

function.

sizeof(array) gives the total size of sizeof(pointer) returns the size


Size the array (number of elements × size of the pointer itself (usually 4 or 8
of data type). bytes).

Example
int arr[5]; int *ptr;
Declaration

Question:
Write the outputs of the following expressions: 1) y=pow(4,3); 2) y=abs(2-3*5); 3)
y=ceil(3+5.1); 4) c=toupper('c'); 5) y=strlen("Flat No");

Ans.:-:

Expressions and Outputs:

1. y = pow(4,3);
o Explanation: The pow() function calculates the power of a number. Here, 4
is raised to the power of 3.
o Calculation: 43=644^3 = 6443=64
o Output: y = 64
2. y = abs(2 - 3 * 5);
o Explanation: The abs() function returns the absolute value of an integer.
First, evaluate the expression 2 - 3 * 5.
o Calculation: 2 - 15 = -13, and abs(-13) = 13
o Output: y = 13
3. y = ceil(3 + 5.1);
o Explanation: The ceil() function returns the smallest integer greater than
or equal to the given number. First, evaluate 3 + 5.1.
o Calculation: 3 + 5.1 = 8.1, and ceil(8.1) = 9
o Output: y = 9
4. c = toupper('c');
o Explanation: The toupper() function converts a lowercase letter to its
uppercase equivalent.
o Output: c = 'C'
5. y = strlen("Flat No");
o Explanation: The strlen() function returns the length of a string,
excluding the null terminator (\0).
o Calculation: The string "Flat No" has 7 characters (F, l, a, t,
space, N, o).
o Output: y = 7
Summary of Outputs:

1. y = 64
2. y = 13
3. y = 9
4. c = 'C'
5. y = 7

Question:
Find out & explain the errors in the following program- #include<stdo.h> #define PI 3.14
float process(float r); main() { float radius, area, printf('Radius=?'); scanf("%d", radius);
float process(float r) {int a; a=PI*r*r;} if(radius<0) area=0; else area=process(radius);
printf("Area=%f",&area) ; }

2/2

Ans.:-:
ChatGPT

Let's identify and explain the errors in the provided C program. Here’s the original code
for reference:

Original Code:
c
Copy code
#include<stdo.h>
#define PI 3.14
float process(float r);

main()
{
float radius, area,
printf('Radius=?');
scanf("%d", radius);
float process(float r)
{
int a;
a = PI * r * r;
}
if (radius < 0)
area = 0;
else
area = process(radius);
printf("Area=%f", &area);
}

Errors and Corrections:

1. Incorrect Header File:


o Error: #include<stdo.h>
o Correction: Use #include<stdio.h> instead. There is no header file
named stdo.h.
2. Incorrect main() Return Type:
o Error: main() should have a return type (int) instead of being implicitly
defined.
o Correction: Change main() to int main() and add a return 0; at the
end.
3. Missing Semicolon:
o Error: float radius, area, (missing semicolon at the end).
o Correction: Add a semicolon: float radius, area;
4. Incorrect printf Format:
o Error: printf('Radius=?'); uses single quotes, which are meant for
characters, not strings.
o Correction: Use double quotes: printf("Radius=?");
5. Incorrect scanf Format Specifier:
o Error: scanf("%d", radius); - The %d format specifier is used for
integers, but radius is a float. Additionally, radius should be passed by
address.
o Correction: Change to scanf("%f", &radius);
6. Incorrect Nested Function Declaration:
o Error: The function process is defined inside main(), which is not allowed
in C.
o Correction: Move the function process outside main(). Place it after or
before main().
7. Incorrect Variable Type in process:
o Error: Inside process, the variable a is defined as int, but it should be
float to store the area correctly.
o Correction: Change int a; to float a;
8. No Return Statement in process:
o Error: The function process does not return a value, despite its return type
being float.
o Correction: Add return a; at the end of process.
9. Incorrect printf Argument:
o Error: printf("Area=%f", &area); - Using &area (address) will print
garbage because it expects a float.
o Correction: Use printf("Area=%f", area);

Corrected Code:
c
Copy code
#include<stdio.h>
#define PI 3.14

float process(float r); // Function prototype

int main()
{
float radius, area;
printf("Radius=?");
scanf("%f", &radius);
if (radius < 0)
area = 0;
else
area = process(radius);

printf("Area=%f", area);
return 0;
}

// Function definition moved outside of main


float process(float r)
{
float a;
a = PI * r * r;
return a;
}

Question:
Write equivalent if-else statement for the following- #include<stdio.h> int main() { int num;
scanf("%d", &num); switch (num) { case 1: printf("1st Block"); break; case 2: printf("2nd
Block"); break; case 3: printf("3rd Block"); break; default: printf("Out of range"); break; }
return 0; }

Ans.:-:
ChatGPT

To convert the switch statement into an equivalent if-else statement, we'll need to use
multiple if and else if conditions to check each case. Below is the equivalent code:

Equivalent if-else Statement:


c
Copy code
#include<stdio.h>

int main() {
int num;
scanf("%d", &num);

if (num == 1) {
printf("1st Block");
}
else if (num == 2) {
printf("2nd Block");
}
else if (num == 3) {
printf("3rd Block");
}
else {
printf("Out of range");
}

return 0;
}

Question:
What is the purpose of the continue statement? Within which control statements can the
continue statement be included? Compare it with the break statement.

Ans.:-:
ChatGPT

Purpose of the continue Statement:

The continue statement in C is used to skip the rest of the code inside a loop for the
current iteration and move directly to the next iteration of the loop. When continue is
encountered, the loop does not terminate; instead, the control jumps to the beginning of
the loop, where the condition is checked, and the next iteration starts.

Use Cases:

• Skipping Iterations: It is useful when you want to skip certain iterations based on a
condition without exiting the loop completely.

Control Statements That Can Include continue:

The continue statement can be used inside:

1. for Loops
2. while Loops
3. do-while Loops

Comparison Between continue and break:


Feature continue Statement break Statement

Skips the remaining code for the current


Exits the loop (or switch
Purpose iteration and proceeds to the next
statement) entirely.
iteration.

Continues to the next iteration of the Breaks out of the loop or switch
Control Flow
loop. and proceeds to the code after it.

Where It Can Can be used within loops (for, while, Can be used within loops and
Be Used do-while). switch statements.

Effect on Does not terminate the loop; just skips Terminates the loop or switch
Loop the current iteration. statement completely.
Question:
Take some numbers & display them in ascending order using array, where values are given
by the user.

Ans.:-:
ChatGPT

To display numbers in ascending order using an array, where the values are given by the
user, you can use a sorting algorithm like Bubble Sort or Selection Sort. Below is an
example program in C that takes user input for an array of integers, sorts them in
ascending order, and then displays the sorted values.

C Program to Sort Numbers in Ascending Order:


c
Copy code
#include <stdio.h>

int main() {
int n, i, j, temp;

// Step 1: Take input for the number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

int arr[n]; // Declare the array with user-defined size

// Step 2: Input elements into the array


printf("Enter %d numbers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Step 3: Sort the array using Bubble Sort


for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

// Step 4: Display the sorted array


printf("Numbers in ascending order:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}
Example Output:
yaml
Copy code
Enter the number of elements: 5
Enter 5 numbers:
45 12 78 34 9
Numbers in ascending order:
9 12 34 45 78

This program will successfully take an array of numbers from the user, sort them using
Bubble Sort, and print them in ascending order.

4o

Question:
Differentiate between a do-while & a while loop.

Ans.:-:
ChatGPT

Differences Between do-while and while Loops in C


Feature while Loop do-while Loop

c while (condition) { // c do { // Loop body } while


Syntax Loop body } (condition);

The condition is evaluated first,


Execution The loop body is executed first, and
and if it is true, the loop body is
Flow then the condition is checked.
executed.

Minimum May execute zero times if the Executes at least once, even if the
Iterations condition is false initially. condition is false on the first check.

Suitable when you want the loop Useful when you need to ensure that the
Use Case to execute only if a condition is loop runs at least once before checking
true. the condition.

The condition is checked before


Condition The condition is checked after the loop
the loop body (entry-controlled
Check body (exit-controlled loop).
loop).

c int i = 0; while (i < 5) c int i = 0; do { printf("%d ",


Example { printf("%d ", i); i++; } i); i++; } while (i < 5);

Question:
Explain the difference between pass by reference & pass by value.
Ans.:-:
ChatGPT

Difference Between Pass by Reference and Pass by Value


Feature Pass by Value Pass by Reference

A method of passing the address


A method of passing the actual value
Definition (reference) of the variable to a
of a variable to a function.
function.

Changes made to the parameter


Effect on Changes made to the parameter
inside the function do not affect the
Original Data directly affect the original variable.
original variable.

A copy of the variable is passed to the A reference (address) of the


Data Passing
function. variable is passed to the function.

Uses less memory as no additional


Requires more memory because a
Memory Usage copy is created, only an address is
new copy of the data is created.
passed.

Suitable when you do not want the


Useful when you want the function
Use Case function to modify the original
to modify the original variable.
variable.

Common in C++ (using pointers or


Example Common in C for basic data types,
references), C#, Python (for
Languages Java (primitive types), etc.
objects), etc.

Question:
Write a simple example of a structure in C language.

Ans.:-:
ChatGPT

In C, a structure (struct) is used to group different data types together under a single
name. Here's a simple example of how to define and use a structure in C:

Example of a Structure in C:
c
Copy code
#include <stdio.h>
#include <string.h>

// Defining a structure called 'Person'


struct Person {
char name[50];
int age;
float height;
};

int main() {
// Declaring a variable of type 'struct Person'
struct Person person1;

// Assigning values to the members of the structure


strcpy(person1.name, "John Doe");
person1.age = 25;
person1.height = 5.9;

// Displaying the values stored in the structure


printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.1f\n", person1.height);

return 0;
}

Explanation:

1. Defining the Structure:


o We define a structure Person that has three members: name (a
string/character array), age (an integer), and height (a floating-point
number).
2. Declaring a Structure Variable:
o In the main() function, we declare a variable person1 of type struct
Person.
3. Assigning Values to Structure Members:
o We use strcpy() to assign a string to the name member (because name is a
character array).
o The age and height members are assigned values directly.
4. Accessing Structure Members:
o To access the members of the structure, we use the dot operator ( .), like
person1.name, person1.age, and person1.height.

Output:
makefile
Copy code
Name: John Doe
Age: 25
Height: 5.9

Question:
What is a preprocessor? How do you define a constant in C programming?

Ans.:-:
ChatGPT
What is a Preprocessor in C?

The preprocessor in C is a tool that processes the source code before it is compiled. It
performs tasks such as including header files, macro expansion, and conditional
compilation. Preprocessor commands, also known as directives, begin with a # symbol
and are executed before the actual compilation of the code starts.

Common preprocessor directives include:

• #include: Includes the contents of a header file.


• #define: Defines macros or constants.
• #ifdef, #ifndef, #if, #else, #endif: Used for conditional compilation.

How to Define a Constant in C Programming?

In C, you can define a constant using either the #define preprocessor directive or the
const keyword.

1. Using #define Preprocessor Directive:


o The #define directive allows you to define a macro that represents a
constant value.
o Syntax:

c
Copy code
#define CONSTANT_NAME value

o Example:

c
Copy code
#define PI 3.14159
#define MAX_SIZE 100

int main() {
printf("The value of PI is: %f\n", PI);
printf("The maximum size is: %d\n", MAX_SIZE);
return 0;
}

o Explanation: The preprocessor replaces every occurrence of PI with


3.14159 and MAX_SIZE with 100 before the code is compiled.
2. Using the const Keyword:
o The const keyword can be used to declare a variable whose value cannot
be changed after it is initialized.
o Syntax:

c
Copy code
const data_type variable_name = value;
o Example:

c
Copy code
const float PI = 3.14159;
const int MAX_SIZE = 100;

int main() {
printf("The value of PI is: %f\n", PI);
printf("The maximum size is: %d\n", MAX_SIZE);
return 0;
}

o Explanation: Here, PI and MAX_SIZE are constants, and attempting to


modify them later in the code will result in a compilation error.

Question:
Which of the following are valid integer constants? Justify your answer. i) 750 ii) '750' iii)
075

Ans.:-:
ChatGPT

Let's analyze each of the given examples to determine if they are valid integer constants
in C:

i) 750

• Valid: Yes, this is a valid integer constant.


• Explanation: 750 is a simple, decimal (base 10) integer constant. It represents the
value seven hundred and fifty and follows the rules of integer constants, which can
include digits (0-9) without any leading symbols.

ii) '750'

• Invalid: No, this is not a valid integer constant.


• Explanation: In C, anything enclosed in single quotes ( ' ') is treated as a
character constant, not an integer. Character constants usually represent a single
character (e.g., 'a', '1'). Since '750' contains more than one character, it is not a
valid character constant either. In C, '750' would cause an error or undefined
behavior.

iii) 075

• Valid: Yes, this is a valid integer constant, but it is not a decimal number.
• Explanation: In C, an integer that starts with a 0 is interpreted as an octal (base 8)
number. The value 075 is an octal constant, which translates to 7 * 8 + 5 = 61 in
decimal. It is still valid as an integer constant, but the interpretation of the value
changes because it is read as an octal number.
Summary:
Constant Valid or Invalid Explanation

750 Valid A normal decimal integer constant.

'750' Invalid Not an integer; invalid multi-character constant.

075 Valid An octal (base 8) integer constant (value is 61 in decimal).

Thus, 750 and 075 are valid integer constants, while '750' is not.

4o

Question:
What are the advantages of using preprocessors?

Ans.:-:
ChatGPT

Advantages of Using Preprocessors in C

Preprocessors are tools that allow the pre-compilation of code, performing various text
substitutions and manipulations before the actual compilation process begins. Using
preprocessors provides several advantages, including:

1. Code Reusability

• By using the #include directive, you can include the contents of a header file in
multiple programs. This allows you to write reusable code, such as commonly used
functions, macros, or variable definitions, in a separate file and include them
wherever needed.
• Example:

c
Copy code
#include <stdio.h> // Includes the standard input-output header
file

2. Ease of Maintenance

• Preprocessors help in maintaining the code. When you define constants or macros
using #define, you can change their values in one place, and it will automatically be
reflected throughout the code. This is particularly useful for constants or settings
that might change frequently.
• Example:

c
Copy code
#define MAX_SIZE 100 // Define a constant for array size

3. Conditional Compilation

• Using directives like #ifdef, #ifndef, #if, #else, and #endif, you can include or
exclude portions of the code during compilation. This is useful for:
o Creating code that works on multiple platforms (e.g., Windows, Linux).
o Enabling or disabling debugging code without deleting it.
o Compiling code based on certain conditions or configurations.
• Example:

c
Copy code
#ifdef DEBUG
printf("Debugging mode is on.\n");
#endif

4. Code Optimization

• Preprocessors can be used to replace repetitive code with macros, which can
make the code shorter, cleaner, and easier to read. This reduces typing effort and
can help with code readability.
• Example:

c
Copy code
#define SQUARE(x) ((x) * (x)) // Macro to calculate the square
of a number

5. Platform Independence

• Preprocessor directives can be used to write code that works across multiple
platforms. For example, you can include platform-specific code based on conditions
checked by the preprocessor.
• Example:

c
Copy code
#ifdef _WIN32
// Windows-specific code
#else
// Code for other platforms
#endif

6. Enhanced Readability and Consistency

• Defining macros for common constants or operations improves readability. If you


use #define to set constants like PI or MAX_SIZE, it ensures that these values
remain consistent throughout your code, and anyone reading the code knows what
they represent.
• Example:

c
Copy code
#define PI 3.14159

7. Reducing Compilation Time

• Preprocessors can help reduce compilation time by excluding unnecessary code


using conditional compilation. This means that only the relevant parts of the code
are compiled, speeding up the process.
• Example:

c
Copy code
#ifndef HEADER_FILE
#define HEADER_FILE
// Code inside this block will be included only once
#endif

Question:
How is a function declared in c language.

Ans.:-:

Function Declaration (Prototype) in C Language

In C, a function declaration (or function prototype) specifies the function name, return
type, and parameters. It tells the compiler what kind of function it is, how many
parameters it takes, and what types those parameters are. The function declaration
typically appears before the main() function or in a header file to ensure the compiler
recognizes the function when it is called.

Syntax of a Function Declaration:


c
Copy code
return_type function_name(parameter_type1 parameter_name1,
parameter_type2 parameter_name2, ...);

int add(int a, int b);

In this example:

• int: The return type indicates that the function will return an integer.
• add: The name of the function.
• int a, int b: Two integer parameters the function will accept.

Question:
Write a C program to find out the factorial of an integer number.
Ans.:-:
ChatGPT

Here is a C program to calculate the factorial of an integer number:

C Program to Find Factorial of a Number:


c
Copy code
#include <stdio.h>

// Function to calculate the factorial of a number


int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

int main() {
int number;

// Asking the user to input a number


printf("Enter a positive integer: ");
scanf("%d", &number);

// Check if the input is a non-negative integer


if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
int fact = factorial(number);
printf("The factorial of %d is: %d\n", number, fact);
}

return 0;
}

Enter a positive integer: 5


The factorial of 5 is: 120

Question:
Differentiate between actual parameters & formal parameters.

Ans.:-:

Difference Between Actual Parameters and Formal Parameters

In C programming (and other languages), parameters refer to the values passed to a


function. These parameters are categorized into two types: actual parameters and
formal parameters.
Aspect Actual Parameters Formal Parameters

The real values or arguments The variables or placeholders declared in


Definition passed to a function during a the function definition to receive the actual
function call. parameters.

Location Appear in the function call. Appear in the function definition.

Provide the input data for the Receive and store the input data provided
Role
function to operate on. by the actual parameters.

Exist outside the function, where Exist inside the function, only accessible
Scope
the function is called. within the function.

sum(5, 10); — Here, 5 and 10 int sum(int a, int b) — Here, a and b


Example
are actual parameters. are formal parameters.

Question:
What advantage is there in defining an array size in terms of symbolic constant rather than
a fixed integer quantity?

Ans.:-:
ChatGPT

Defining an array size in terms of a symbolic constant instead of a fixed integer quantity
offers several advantages in programming, particularly in C. Here are some key benefits:

1. Improved Readability

• Symbolic Constants: When you define an array size using a symbolic constant (e.g.,
#define SIZE 100), it makes the code more readable and understandable. A
symbolic name like SIZE clearly indicates its purpose compared to a magic number
like 100, which may not convey its meaning.
• Example:

c
Copy code
#define SIZE 100
int arr[SIZE]; // Clearer than int arr[100];

2. Easier Maintenance

• If you need to change the size of the array, you can do so in one place (the definition
of the symbolic constant). This eliminates the risk of missing occurrences of a
hardcoded value throughout your code, which could lead to inconsistencies and
errors.
• Example:

c
Copy code
#define SIZE 100
// Later, if you need to change the size:
#define SIZE 200

3. Prevention of Magic Numbers

• Using symbolic constants helps avoid "magic numbers" in your code. Magic numbers
are hardcoded values that appear without context, making the code harder to
understand. By using constants, you provide context and meaning to the values.
• Example:

c
Copy code
int arr[100]; // Magic number
int arr[SIZE]; // Using a constant for clarity

4. Facilitates Code Reusability

• When using symbolic constants, the same constant can be used across different
functions or modules. This allows for easier reuse of the array size in multiple
places, enhancing code modularity.
• Example:

c
Copy code
void function() {
int arr[SIZE]; // Consistent use of SIZE in multiple
functions
}

5. Supports Easy Scaling

• If the size of the array needs to be modified based on different configurations (e.g.,
user input, project requirements), symbolic constants can be defined based on
preprocessor directives, allowing for flexible and scalable code.
• Example:

c
Copy code
#define SIZE 100
// Change to #define SIZE 200 for a larger array in different
contexts

6. Enhanced Debugging

• If an array size is defined as a symbolic constant, any error messages or debugging


output that reference the constant will have a clear and meaningful context, making
it easier to track down issues related to array sizes.
• Example:
o An error message that includes SIZE will be clearer than one that includes a
number like 100.

7. Consistency Across the Code

• Using a symbolic constant for array sizes ensures that the same value is used
consistently throughout the code. This helps avoid bugs that can arise from
mistakenly using different sizes in different places.

Question:
Write a program that calculates & prints the sum of the integers which are divisible by 7
and ranges from 11 to 111.

Ans.:-:
ChatGPT

Here's a C program that calculates and prints the sum of integers that are divisible by 7
within the range of 11 to 111:

C Program to Calculate the Sum of Integers Divisible by 7


c
Copy code
#include <stdio.h>

int main() {
int sum = 0; // Variable to hold the sum of integers
int start = 11; // Start of the range
int end = 111; // End of the range

// Loop through the range from 11 to 111


for (int i = start; i <= end; i++) {
if (i % 7 == 0) { // Check if the number is divisible by 7
sum += i; // Add the number to the sum
}
}

// Print the result


printf("The sum of integers divisible by 7 between %d and %d is:
%d\n", start, end, sum);

return 0;
}

Question:
What is recursion? What are the conditions to be satisfied to write a program recursively?
In which cases you should use recursion?
Ans.:-:
ChatGPT

What is Recursion?

Recursion is a programming technique where a function calls itself directly or indirectly


to solve a problem. In a recursive function, the problem is divided into smaller
subproblems of the same type, and the function continues to call itself until it reaches a
base case, which is a condition that stops the recursion.

Conditions to Write a Recursive Program

To effectively implement recursion, the following conditions must be satisfied:

1. Base Case: Every recursive function must have at least one base case to terminate
the recursion. Without it, the function will call itself indefinitely, leading to a
stack overflow error.
2. Progression Towards Base Case: Each recursive call must bring the function
closer to the base case. This usually involves reducing the size of the input or
modifying the input parameters in such a way that it eventually meets the base
case.
3. Well-Defined Problem: The problem should be clearly defined and should be
expressible in terms of smaller instances of the same problem.

When to Use Recursion

Recursion can be particularly useful in the following cases:

1. Divide and Conquer Algorithms: Many algorithms, such as quicksort and


mergesort, are naturally recursive as they divide a problem into smaller
subproblems and solve each one.
2. Problems with a Natural Recursive Structure: Some problems have a recursive
nature, such as calculating the Fibonacci sequence, traversing trees (e.g., binary
trees), or solving problems like the Tower of Hanoi.
3. Backtracking Algorithms: Recursion is often used in backtracking algorithms,
such as solving puzzles (like Sudoku), generating permutations or combinations,
and searching through all possible solutions.
4. Dynamic Programming: In some cases, recursion can be used in dynamic
programming, where the problem can be broken down into overlapping
subproblems. However, memoization or tabulation is often used alongside
recursion to optimize it.
5. Simplifying Code: In some cases, recursion can lead to simpler and more elegant
code compared to iterative solutions. Recursive functions can be easier to read
and understand when dealing with problems that fit the recursive paradigm.
Question:
You are given a string consisting of only alpha-numerals. Write a program to count the
number of vowels in the string.

Ans.:-:
ChatGPT

Here's a C program that counts the number of vowels in a string consisting of


alphanumeric characters:

C Program to Count the Number of Vowels in a String


c
Copy code
#include <stdio.h>
#include <ctype.h>

int countVowels(const char *str) {


int count = 0;
char ch;

// Loop through each character in the string


for (int i = 0; str[i] != '\0'; i++) {
// Convert the character to lowercase to handle both uppercase
and lowercase vowels
ch = tolower(str[i]);

// Check if the character is a vowel


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==
'u') {
count++;
}
}

return count;
}

int main() {
char str[100];

// Ask user to input a string


printf("Enter a string: ");
scanf("%s", str);

// Count the vowels


int vowelCount = countVowels(str);

// Display the result


printf("Number of vowels in the string: %d\n", vowelCount);

return 0;
}

You might also like