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

C-PROGRAMMING Q.b solns(musa)

Uploaded by

betkarritesh806
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)
134 views

C-PROGRAMMING Q.b solns(musa)

Uploaded by

betkarritesh806
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/ 57

C-PROGRAMMING Q.

BANK
SOLUTIONS(MUSA) (BY.Umar)
THEORY Q. SOLNS
1. What are the tokens of c language explain with example
SOLN: Tokens are the fundamental building blocks of a C program.
They are the smallest individual units of code that have a distinct meaning to
the compiler.
During the first stage of compilation (called lexical analysis), the compiler
breaks down the program into these tokens, forming the basis for further
processing and translation.
Here's an explanation of tokens in C with examples:

Tokens are the fundamental building blocks of a C program. They are the
smallest individual units of code that have a distinct meaning to the
compiler. During the first stage of compilation (called lexical analysis), the
compiler breaks down the program into these tokens, forming the basis for
further processing and translation.

C has the following major types of tokens:

1. Keywords:
○ Predefined, reserved words with specific meanings in C.
○ Examples: int, float, char, if, else, while, for, return,
void, main, struct, union, typedef, sizeof, const,

volatile, enum, goto

2. Identifiers:
○ User-defined names for variables, functions, arrays,
structures, unions, etc.
○ Rules:
■ Must start with a letter (a-z, A-Z) or an underscore (_).
■ Can contain letters, digits, or underscores.
■ Case-sensitive (e.g., Age and age are different).
○ Examples: sum, count, average, myFunction, employeeName
3. Constants:
○ Fixed values that don't change during program execution.
○ Types:
■ Numeric constants:
■ Integer constants: Whole numbers (e.g., 10, -5, 0)
■ Floating-point constants: Numbers with decimal
parts (e.g., 3.14159, -2.5e2)
■ Character constants: Single characters enclosed in
single quotes (e.g., 'A', 'z', '!')
■ String literals: Sequences of characters enclosed in
double quotes (e.g., "Hello, world!")
4. Operators:
○ Symbols that perform operations on values.
○ Examples: Arithmetic operators (+, -, *, /, %), Relational
operators (==, !=, <, >, <=, >=), Logical operators (&&, ||, !),
Assignment operator (=), Increment/decrement operators (++,
--), etc.

5. Special Symbols:
○ Punctuation marks with specific functions in C syntax.
○ Examples: Parentheses (), braces {}, brackets [], semicolon
;, comma ,, period ., colon :

6. White Spaces:
○ Spaces, tabs, newlines, used for readability but ignored by the
compiler (except within strings).

Q. Explain following functions with example(a) sqrt(), (b)


fabs(), (c) pow(), (d) ceil(), (e) floor(), (f) strcmp(),(g)
strcat(), (h) strlen(), (i) gets(), (j) strrev().
SOLN: Here's an explanation of the functions with examples:

Note: Most of these functions require the math.h or string.h header


files.

Mathematical Functions:

(a) sqrt():

● Calculates the square root of a non-negative number.


● Returns a double value.
● Example: double result = sqrt(25); // result will be 5.0

(b) fabs():

● Returns the absolute value (non-negative magnitude) of a


floating-point number.
● Example: double absValue = fabs(-3.14); // absValue will
be 3.14

(c) pow():

● Raises a number to a specified power.


● Returns a double value.
● Example: double powerResult = pow(2, 3); // powerResult
will be 8.0

(d) ceil():

● Rounds a number up to the nearest integer.


● Returns a double value.
● Example: double roundedUp = ceil(3.14); // roundedUp will
be 4.0
(e) floor():

● Rounds a number down to the nearest integer.


● Returns a double value.
● Example: double roundedDown = floor(3.14); // roundedDown
will be 3.0

String Functions:

(f) strcmp():

● Compares two strings lexicographically (character by


character).
● Returns 0 if strings are equal, a negative value if the first string
is less than the second, and a positive value if the first string is
greater than the second.
● Example: int comparison = strcmp("apple", "banana"); //
comparison will be negative

(g) strcat():

● Appends one string to the end of another string.


● Modifies the first string directly.
● Example: char str1[50] = "Hello "; strcat(str1,
"world!"); // str1 will become "Hello world!"

(h) strlen():

● Calculates the length of a string (excluding the null terminator).


● Returns an unsigned integer value.
● Example: int stringLength = strlen("Hello"); //
stringLength will be 5
(i) gets():

● Caution: Avoid using gets() due to security vulnerabilities. Use


fgets() instead.

● Reads a line of input from the user and stores it in a string.

(j) strrev():

● Reverses the characters of a string.


● Modifies the string directly.
● Note: strrev() is not a standard C library function. You might
need to implement it yourself or use a third-party library.

3. Explain conditional operator used in c with


proper examples.

Soln: Conditional Operator (also known as Ternary Operator):

It's a shorthand way of writing simple if-else statements within a


single expression.
It has three operands and is written as:

condition ? expression1 : expression2

How it works:
1.The condition is evaluated first.
2.If the condition is true, expression1 is evaluated and its
value 3.becomes the result of the entire expression.
4.If the condition is false, expression2 is evaluated and its
value becomes the result.
EX.
int age = 25;
char *status = (age >= 18) ? "Adult" : "Minor"; // status will be
"Adult"
Breakdown:
age >= 18 is evaluated as true.
So, "Adult" is assigned to the status variable
Key Points:
1. It's a concise way to write simple conditional statements.
2. It's often used for variable assignments and returning values
from functions.
3. It can improve readability in some cases, but overuse can
make code less clear.
4. Use parentheses for clarity if expressions are complex.
5. It has lower precedence than most other operators, so use
parentheses for grouping as needed.

Q. What are the different ways of parameter passing


to a function? Explain with examples.

Soln: Here are the different ways of parameter passing to a


function in C, with examples:

1. Call by Value:
- A copy of the actual parameter's value is passed to the function.
- Changes made to the parameter within the function do not affect the
original value.

Example:

C
void increment(int x) { // x is a copy of the original
value

x = x + 1;

int main() {

int num = 5;

increment(num); // Call by value

printf("%d", num); // Output: 5 (original value


remains unchanged)

2. Call by Reference:
- The address of the actual parameter is passed to the function.
- Changes made to the parameter within the function directly affect
the original value.
- It's often used for modifying large data structures or returning
multiple values.

Example:

C
void swap(int *a, int *b) { // a and b are pointers to
the original values

int temp = *a;

*a = *b;

*b = temp;
}

int main() {

int x = 10, y = 20;

swap(&x, &y); // Call by reference

printf("x = %d, y = %d", x, y); // Output: x = 20, y


= 10 (values swapped)

3. Arrays as Parameters:
- Arrays are always passed by reference in C, even if you don't use
the & operator.
- Any changes made to the array within the function affect the original
array.

Example:

C
void modifyArray(int arr[], int size) { // arr is a
pointer to the original array

for (int i = 0; i < size; i++) {

arr[i] *= 2; // Doubles each element

int main() {
int numbers[] = {1, 2, 3, 4};

modifyArray(numbers, 4); // Array is modified

printf("%d %d %d %d", numbers[0], numbers[1],


numbers[2], numbers[3]); // Output: 2 4 6 8

}
Key Points:
- Choose the appropriate method based on whether you want to
modify the original values or not.
- Call by value is often used for simple data types and when you
want to preserve the original values.
- Call by reference is used for arrays, large structures, and when
you need to modify the original values or return multiple values.

Q. Give the difference between entry and exit


controlled loop with an example

Soln: Here's the difference between entry-controlled and


exit-controlled loops in C, with examples:

Entry-controlled loops:
- The loop condition is checked before entering the loop body.
- If the condition is false at the beginning, the loop body won't
execute even once.
- Examples in C: for loop and while loop

Example of a for loop:

C
for (int i = 1; i <= 5; i++) {
printf("%d ", i);

- The condition i <= 5 is checked first. If it's false (e.g., if i is


initially 6), the loop body won't execute.

Example of a while loop:

C
int count = 10;

while (count > 0) {

printf("%d ", count);

count--;

- The condition count > 0 is checked first. If it's false (e.g., if


count is initially 0), the loop body won't execute.

Exit-controlled loops:
- The loop condition is checked after executing the loop body.

- The loop body is guaranteed to execute at least once, even if


the condition is initially false.
- Example in C: do-while loop

Example of a do-while loop:

C
int choice = 0;

do {
printf("Enter a positive number: ");

scanf("%d", &choice);

} while (choice <= 0);

● The loop body (prompting for input) will execute at least once,
even if choice is initially negative.
● The condition choice <= 0 is checked after the first iteration,
and the loop continues if it's true.

Key Points:

- Entry-controlled loops are generally more efficient because they


avoid unnecessary executions of the loop body.
- Exit-controlled loops are useful when you need to ensure that
the loop body executes at least once, even if the condition is
initially false.
- Choose the appropriate type of loop based on the specific
requirements of your program.

Q. Differentiate between arrays and structures in C

Soln. Here's a table differentiating arrays and structures in C:

Feature Arrays Structures

Purpo Storing collections Storing collections of elements


se of elements of the of different data types
same data type
Declar data_type struct struct_name {
ation array_name[size member1; member2; ... };
];

Access Using index: Using dot operator:


ing array_name[inde struct_variable.member_na
elemen x] me
ts

Memor Continuous block Not necessarily contiguous,


y of memory members may be stored in
allocati different memory locations
on

Size Fixed at Flexible, determined by the


declaration number and types of members

Passin Can be passed by Usually passed by reference


g to value or reference (address)
functio
ns

Additional Key Differences:

● Homogeneity: Arrays hold elements of the same data type,


while structures can hold elements of different data types.
● Member Names: Arrays access elements using numerical
indices, while structures access members using meaningful
names.
● Nesting: Arrays can be nested within structures, and structures
can be nested within other structures.
● Operations: Arrays support common operations like sorting and
searching, while structures are typically used for organizing
and grouping data.
When to Use Which:

● Arrays: Use arrays when you need to store a collection of


similar data items, such as a list of numbers, names, or scores.
● Structures: Use structures when you need to represent a
complex entity with multiple attributes of different types, such
as a student record with name, age, grades, etc.

Q. Distinguish between structure and union

SOLN:

Both structures and unions in C are used to group related data, but
they differ in how they store that data:

1. Memory allocation:

● Structure: Each member of a structure has its own dedicated


memory space within the structure. The total size of the
structure is the sum of the sizes of its members.
● Union: All members of a union share the same memory
location. The size of the union is equal to the size of its largest
member.

2. Accessing members:

● Structure: Members of a structure are accessed using the dot


operator (.) followed by the member name.
● Union: Only one member of a union can be accessed at a time
because they share the same memory location. To access
different members, you need to explicitly cast the union to the
specific member type before accessing it.
3. Data Type Consistency:

● Structure: Members of a structure can be of different data types.


● Union: Typically, members of a union are of the same data type
or related data types, although technically they can be different.
This is because accessing different types with the same
memory location can lead to unpredictable behavior.

4. Usage:

● Structure: Used for representing complex data types with


various attributes, like a student record with name, age, and
grades.
● Union: Used for situations where data size is critical and you
only need one member at a time, like representing different data
depending on a specific condition.

Here's a table summarizing the key differences:

Feature Structure Union

Memory Each member has All members share the


allocation dedicated space same space (size of largest
member)

Member Dot operator (.) Explicit casting and


access and member name member name

Data type Different data Typically same or related


consistenc types allowed data types (avoiding mixed
y access)
Usage Complex data Size-critical scenarios, one
types with various member active at a time
attributes

When to Choose Which:

● Use a structure when you need to represent a complex data


type with different attributes that need their own dedicated
memory space.
● Use a union when you need to save memory and only one
member of the data will be active at a time.

Q. What are bitwise and logical operators in C.

Soln.

Here's a breakdown of bitwise and logical operators in C:

Bitwise Operators:

● Operate directly on the individual bits of integer values.


● Used for tasks like manipulating flags, bitmasks, and low-level
data representation.

Common Bitwise Operators:

● & (bitwise AND): Performs AND operation on each pair of


corresponding bits.
● | (bitwise OR): Performs OR operation on each pair of
corresponding bits.
● ^ (bitwise XOR): Performs XOR operation on each pair of
corresponding bits.
● ~ (bitwise NOT): Inverts the bits of a value (flips 0s to 1s and 1s
to 0s).
● << (left shift): Shifts bits to the left, filling new bits with 0s.
● >> (right shift): Shifts bits to the right, filling new bits with 0s
(for unsigned values) or with the sign bit (for signed values).

Logical Operators:

● Operate on Boolean expressions (true or false).


● Used for making decisions and controlling program flow.

Common Logical Operators:

● && (logical AND): Returns true if both operands are true,


otherwise false.
● || (logical OR): Returns true if either or both operands are true,
otherwise false.
● ! (logical NOT): Inverts the truth value of an operand (true
becomes false, false becomes true).

Key Differences:

● Operand Type: Bitwise operators work on integer values, while


logical operators work on Boolean expressions.
● Bit-level vs. Truth Value: Bitwise operators manipulate
individual bits, while logical operators evaluate the overall truth
or falsity of expressions.
● Precedence: Logical operators have lower precedence than
bitwise operators.

Examples:
Bitwise:
C
int a = 5, b = 3; // Binary: a = 0101, b = 0011

int result = a & b; // result will be 1 (0001)

Logical:

C
int x = 10, y = 20;

if (x > 5 && y > 15) {

// This code will execute

Q. What are strings and give any 4 string related


functions.

Soln.

Here's an explanation of strings and four common string-related functions


in C:

Strings in C:

● A string is a sequence of characters that represent text.


● Technically, C doesn't have a built-in string data type.
● Strings are typically represented as arrays of characters, terminated
by a null character (\0).

Common String-Related Functions (from the string.h header file):

1. strlen(str):
○ Calculates the length of a string (excluding the null
terminator).
○ Returns an unsigned integer value representing the number of
characters in the string.
○ Example: int length = strlen("Hello"); // length will be
5

2. strcpy(dest, src):
○ Copies one string to another.
○ Copies the characters of src to dest, including the null
terminator.
○ Caution: Be sure dest has enough space to accommodate the
copied string.
○ Example: char name1[20] = "Alice"; char name2[20];
strcpy(name2, name1);

3. strcat(dest, src):

○ Appends one string to the end of another.


○ Concatenates src to the end of dest, overwriting the null
terminator of dest.
○ Caution: Ensure dest has enough space for the combined
string.
○ Example: char message[50] = "Hello "; strcat(message,
"world!");

4. strcmp(str1, str2):
○ Compares two strings lexicographically (character by
character).
○ Returns 0 if the strings are equal, a negative value if str1 is
less than str2, and a positive value if str1 is greater than str2.
○ Example: int result = strcmp("apple", "banana"); //
result will be negative

Remember:

Include the string.h header file to use these functions.

Be mindful of buffer overflows when using strcpy and strcat. Ensure


destination arrays have enough space to prevent potential security
vulnerabilities.

Q. Explain nested structures with examples.

Soln.

Here's an explanation of nested structures in C with examples:

Nested Structures:

● A nested structure is a structure that contains another structure


as one of its members.
● This allows you to create more complex data types by
combining multiple structures.
● It's useful for representing hierarchical relationships between
data.

Example:

C
struct Address {

char street[50];

char city[30];

char state[20];

int zipcode;

};

struct Employee {

int id;

char name[50];

struct Address address; // Nested structure

double salary;

};

Accessing Members:

● Access members of the outer structure using the dot operator


(.) as usual.
● To access members of the nested structure, use another dot
operator:

C
struct Employee emp1;

strcpy(emp1.name, "John Doe");

strcpy(emp1.address.street, "123 Main St"); // Accessing


nested member

emp1.salary = 50000.0;

Initialization:

● You can initialize a nested structure within a single declaration:

struct Employee emp2 = {1234, "Jane Smith", {"456 Elm St",


"Anytown", "CA", 98765}, 60000.0};

Benefits of Nested Structures:

● Organizing Complex Data: Model real-world relationships


between entities (e.g., employee and address).
● Grouping Related Information: Keep related data together,
improving code readability and maintainability.
● Building Hierarchical Structures: Create more sophisticated
data structures with multiple levels of nesting.

Example with Multiple Nested Structures:

struct Date {
int day;

int month;

int year;

};

struct Student {

int roll_no;

char name[50];

struct Date dob; // Nested Date structure

float marks;

};

Key Points:

● Nested structures can be nested to any level (structures within


structures within structures).
● Use nested structures judiciously to avoid overly complex data
models.
● Consider using pointers to structures for flexibility and memory
management in certain scenarios.

Q. List and explain different components of computer


systems.
Soln:

Here are the different components of a computer system:

Hardware:

● Central processing unit (CPU): The brain of the computer,


responsible for processing instructions and data. It consists of:
○ Control unit (CU): Decodes instructions and directs other
components.
○ Arithmetic logic unit (ALU): Performs mathematical and
logical operations.
○ Registers: Temporary storage for data and instructions.
● Memory: Stores data and instructions that the CPU needs to
access quickly. There are two main types:
○ Random access memory (RAM): Volatile memory that
loses data when the computer is turned off. Used for
storing data and instructions currently being used by the
CPU.
○ Read-only memory (ROM): Non-volatile memory that
retains data even when the computer is turned off. Used
for storing the BIOS and boot sequence.
● Storage: Stores data and programs permanently. There are two
main types:
○ Hard disk drive (HDD): A mechanical storage device with
rotating platters and magnetic heads. Slower than SSDs
but cheaper and offer large capacities.
○ Solid-state drive (SSD): A flash-based storage device with
no moving parts. Faster than HDDs but more expensive
and offer lower capacities.
● Input devices: Allow users to enter data and instructions into
the computer. Examples include:
○ Keyboard
○ Mouse
○ Touchscreen
○ Microphone
○ Scanner
● Output devices: Present information to the user. Examples
include:
○ Monitor
○ Printer
○ Speakers

Software:

● Operating system (OS): Manages the hardware and provides a


platform for running applications. Examples include:
○ Windows
○ macOS
○ Linux
○ Android
○ iOS
● Applications: Specific programs that perform tasks for the user.
Examples include:
○ Word processors
○ Web browsers
○ Games
○ Email clients
● Data: Information that is processed by the computer. Examples
include:
○ Documents
○ Photos
○ Videos
○ Music
These are just the most basic components of a computer
system. There are many other components, such as the
motherboard, graphics card, and sound card, that can be
added to customize and enhance the functionality of the
computer.

Q. Define structures and explain the syntax of


declaration of structures with examples.

Soln:

Here's a definition of structures and an explanation of their


declaration syntax in C, with examples:

Structures:

● User-defined data types that group variables of different data


types under a single name.
● Used to model complex entities with multiple attributes.
● Provide a way to organize and manage related data together,
improving code readability and maintainability.

Syntax for Declaring a Structure:

struct struct_name {

member_type1 member_name1;

member_type2 member_name2;
// ... more members

};

Explanation:

● struct: Keyword indicating a structure declaration.


● struct_name: Name you choose for the structure (follows
variable naming conventions).
● member_type1, member_type2, ...: Data types of the individual
members within the structure.
● member_name1, member_name2, ...: Names you assign to the
members (also follow variable naming conventions).
● Members are enclosed within curly braces {}.
● Declaration only defines the structure's blueprint; it doesn't
allocate memory for variables of this type.

Examples:

1. Employee Structure:

struct Employee {

int id;

char name[50];

float salary;

};
2. Address Structure:

struct Address {

char street[100];

char city[50];

char state[30];

int zipcode;

};

3. Student Structure:

struct Student {

int roll_no;

char name[30];

float marks;

struct Address address; // Nested structure

};
Key Points:

● Member names within a structure must be unique.


● Structures can be nested within other structures.
● Size of a structure is the sum of the sizes of its individual
members.
● To create variables of a structure type, use the structure name
like any other data type:

struct Employee emp1; // Declares a variable emp1 of type


Employee

● Access members using the dot operator (.):

emp1.id = 101;

strcpy(emp1.name, "John Doe");

emp1.salary = 50000.0;

Q. What is flowchart ? Explain the different symbols


used in flowchart.

Soln:
Here's an explanation of flowcharts and the common symbols used in
them:

Flowchart:
● A visual diagram that represents the flow of a process or
algorithm.
● Uses a set of standard symbols connected by arrows to depict
the sequence of steps and decisions involved.
● Helps in understanding, planning, analyzing, documenting, and
communicating processes.

Common Flowchart Symbols:

1. Oval/Ellipse:

○ Represents the start or end of a process.


○ Typically labeled "Start" or "End" within the shape.
2. Rectangle:

○ Represents a process or action step.


○ Contains a description of the task to be performed.
3. Diamond:

○ Represents a decision point.


○ Contains a question or condition that determines the flow
direction.
○ Arrows flow out of the diamond based on possible
outcomes (usually "Yes" and "No").
4. Parallelogram:

○ Represents input or output.


○ Used for data entry or display.
5. Arrow:

○ Indicates the flow direction.


○ Shows the sequence of steps and the path to follow based
on decisions.

Additional Symbols:

● Circle: Used for connectors to link distant parts of the


flowchart, avoiding long lines.
● Document: Represents a document or report.
● Data Storage: Represents a database or data storage.
● Predefined Process: Represents a subroutine or sub-process
that is defined elsewhere.

Benefits of Flowcharts:

● Visual clarity: Easy to understand and follow the process flow.


● Communication: Effective tool for communicating processes to
others.
● Analysis: Aids in identifying potential problems, bottlenecks,
and areas for improvement.
● Documentation: Serves as a visual record of the process for
future reference.
● Debugging: Helps in identifying errors in logic and
troubleshooting problems.

Q. Explain different data type modifiers available in c


language.

Soln.
Here are the different data type modifiers available in C, along with
their purposes and examples:

1. Signed and Unsigned:


● Signed: Default for most integer types. Can represent both
positive and negative values.
● Unsigned: Restricts values to non-negative numbers only,
doubling the maximum positive value.

Examples:

C
signed int x = -5;
unsigned int y = 100;

2. Short and Long:

● Short: Modifies integer types to use less memory, usually half


the size of the normal type.
● Long: Modifies integer types to use more memory, typically
twice the size of the normal type.

Examples:

C
short int age = 25;
long int population = 785462135;

3. Long Long (C99 and later):

● Provides even larger integer types than long for extensive


storage needs.

Example:

C
long long int huge_number = 9223372036854775807LL; // Maximum
value for long long

Key Points:

● Modifiers are applied to base data types like int, char, and
float.

● They can be combined, like unsigned short int or long long


int.

● Size of modified types can vary depending on compiler and


system architecture.
● Use sizeof operator to determine the exact size of a data type
on a specific system.

Additional Notes:

● C99 introduced long long and _Bool (for boolean values).


● There's no unsigned for floating-point types (float, double) as
they already represent a wide range of positive and negative
values.
● Use appropriate modifiers to optimize memory usage and
represent required value ranges accurately.

Q. Explain multi way branching statements available in


c-langauge with examples.

Soln: Multi-way branching allows a program to choose among


multiple execution paths based on the value of an expression. C
supports multi-way branching using the switch statement.
Syntax:

C
switch (expression) {

case value1:

// Code to execute if expression equals value1

break;

case value2:

// Code to execute if expression equals value2

break;

// ... more cases

default:

// Code to execute if expression doesn't match any


case

Explanation:

1. switch: Keyword indicating the start of the multi-way branching


statement.
2. expression: An expression that evaluates to an integer or
character value.
3. case: Marks a specific value to match against the expression.
4. value1, value2, ...: Constant values to be compared with the
expression.
5. break: Terminates the current case and exits the switch
statement.
6. default: Optional block that executes if none of the case values
match.

Example:

C
int day = 3; // Assume a value has been assigned to day

switch (day) {

case 1:

printf("Monday\n");

break;

case 2:

printf("Tuesday\n");

break;

case 3:

printf("Wednesday\n");

break;

// ... cases for other days

default:

printf("Invalid day number\n");

Key Points:
● The expression must evaluate to a compatible type for
comparison (integer or character).
● case values must be constant expressions.
● break statements are crucial to prevent fall-through (execution
continuing to the next case even if the expression doesn't
match).
● default is optional but often used to handle unexpected values.
● switch statements can be nested within each other for more
complex multi-way branching.

Q. Explain the function prototype with examples.

Soln:

Function Prototypes:

● Declarations that provide essential information about a function


before its actual definition.
● Act as a blueprint for the function, outlining its name, return
type, and parameters.
● Serve several purposes:
○ Inform the compiler about the function's existence and
characteristics, enabling it to check for errors during
compilation.
○ Allow functions to be called before they are defined,
improving code organization and modularity.
○ Facilitate separate compilation of different code modules.

Syntax:

C
return_type function_name(parameter_list);
Explanation:

● return_type: The data type of the value the function returns


(e.g., int, double, void for no return value).
● function_name: The name you assign to the function, following
variable naming conventions.
● parameter_list: A comma-separated list of parameters the
function accepts, specifying their data types and names.

Example:

C
int calculate_area(int length, int width); // Function
prototype

int main() {

int area = calculate_area(5, 10); // Function call


before definition

printf("Area: %d\n", area);

return 0;

int calculate_area(int l, int w) { // Function


definition

return l * w;

}
Key Points:

● Function prototypes are typically placed before main() or in


header files.
● They don't contain the function's body (code block), only its
signature.
● The actual function definition must match the prototype in
terms of return type, name, and parameter list.
● Using prototypes enhances code readability, maintainability,
and error checking.

Additional Notes:

● Parameter names in the prototype are optional but can improve


clarity.
● Prototypes can be included multiple times without issues.
● They are especially important in large projects with multiple
source files.

Q. Define: (i) recursion (ii) break (iii) goto (iv) continue


(v) Structure.

Soln:
(i) Recursion:

● A programming technique where a function calls itself directly


or indirectly.
● It breaks down a problem into smaller, self-similar subproblems.
● Each recursive call handles a smaller part of the problem until a
base case is reached (a condition where the function no longer
calls itself).
● It's often used for tasks that can be naturally expressed in a
recursive manner, such as tree traversals, factorial calculations,
and divide-and-conquer algorithms.

(ii) Break:

● A control flow statement used to exit a loop (e.g., for, while,


do-while) prematurely, even if the loop's condition is still true.

● It transfers control to the statement immediately following the


loop.
● It's often used to terminate a loop when a specific condition is
met or to avoid unnecessary iterations.

(iii) Goto:

● A statement that allows an unconditional jump to a specified


label within the code.
● Generally considered a less structured approach to control
flow, potentially leading to harder-to-understand and
maintainable code.
● Its use is often discouraged in modern programming practices
in favor of more structured alternatives like conditional
statements and loops.

(iv) Continue:

● A control flow statement used to skip the remaining statements


in the current iteration of a loop and move to the next iteration.
● It doesn't exit the loop entirely, only skips the rest of the current
cycle.
● It's often used to filter out certain elements within a loop or to
conditionally execute a portion of code within each iteration.
(v) Structure:

● A user-defined composite data type that groups variables of


different data types under a single name.
● It allows you to create custom data structures to model
real-world entities or complex data relationships.
● Members of a structure are accessed using the dot operator (.).
● Structures enhance code organization, readability, and
maintainability by grouping related data together.

Q. Write a short note on von neumann model.

The von Neumann model, also known as the von Neumann


architecture, is a fundamental design for digital computers first
proposed by John von Neumann in 1945. It defines the basic
structure and functionality of how computers operate, with the
following key components:

● Central processing unit (CPU): The brain of the computer,


responsible for executing instructions and manipulating data. It
consists of:
○ Control unit (CU): Decodes instructions and directs other
components.
○ Arithmetic logic unit (ALU): Performs mathematical and
logical operations.
○ Registers: Temporary storage for data and instructions.

● Memory: Stores data and instructions that the CPU needs to


access quickly. There are two main types:
○ Random access memory (RAM): Volatile memory that
loses data when the computer is turned off. Used for
storing data and instructions currently being used by the
CPU.
○ Read-only memory (ROM): Non-volatile memory that
retains data even when the computer is turned off. Used
for storing the BIOS and boot sequence.

● Input/Output (I/O) devices: Allow users to interact with the


computer and provide a way to access data from the outside
world. Examples include keyboard, mouse, monitor, printer, etc.
● Program: A set of instructions that the CPU understands and
executes to perform specific tasks.

Key Points of the von Neumann model:

● Stored-program concept: Instructions are stored in memory


alongside data, allowing for flexible execution and modification.
● Linear sequence: Instructions are executed sequentially, one
after the other.
● Binary representation: Data and instructions are represented
using binary digits (0s and 1s).

Impact of the von Neumann model:

● The von Neumann model has become the cornerstone of


modern computer architecture, influencing most existing digital
computers.
● Its simplicity and flexibility have made it a foundational concept
for teaching and understanding computer science principles.
● However, some limitations have led to the development of
alternative architectures and computing paradigms for specific
applications.
PROGRAMMING (Solns)

Q.1) Write a Program to calculate and display sum of all the


elements of the matrix.

SOLN:
#include <stdio.h>

int main() {
int rows, cols, i, j, sum = 0;

printf("Enter the number of rows and columns: ");


scanf("%d %d", &rows, &cols);

int matrix[rows][cols]; // Declare the matrix

printf("Enter the elements of the matrix:\n");


for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Calculate the sum of all elements


for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
sum += matrix[i][j];
}
}

printf("Sum of all elements of the matrix: %d\n", sum);

return 0;
}

Q.2) Write a program to check whether the entered string is


palindrome or not
SOLN:
#include <stdio.h>
#include <string.h>

int main() {
char str[100];
int len, i, flag = 1;

printf("Enter a string: ");


fgets(str, 100, stdin); // Safer input function than scanf

len = strlen(str) - 1; // Remove trailing newline from fgets

// Check for palindrome


for (i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {
flag = 0;
break;
}
}

if (flag) {
printf("%s is a palindrome.\n", str);
} else {
printf("%s is not a palindrome.\n", str);
}

return 0;
}

Q.3) Implement a program to find transpose of a matrix.

Soln:
#include <stdio.h>

int main() {
int rows, cols, i, j;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);

int matrix[rows][cols], transpose[cols][rows];

printf("Enter the elements of the matrix:\n");


for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Transpose the matrix


for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j]; // Swap rows and columns
}
}

printf("\nTranspose of the matrix:\n");


for (i = 0; i < cols; i++) {
for (j = 0; j < rows; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}

return 0;
}

Q.4) Write a program to find the power of x raised to n that


is:x n , using recursive function

Soln:
#include <stdio.h>

int power(int x, int n) {


if (n == 0) {
return 1; // Base case: x^0 = 1
} else {
return x * power(x, n - 1); // Recursive call: x^n = x * x^(n-1)
}
}

int main() {
int x, n, result;

printf("Enter the value of x: ");


scanf("%d", &x);
printf("Enter the value of n: ");
scanf("%d", &n);

result = power(x, n);

printf("x^n = %d\n", result);

return 0;
}

Q.5) Write a program to accept elements of one


dimensional array from user and sort and display them in
ascending order
Soln:
#include <stdio.h>

void bubbleSort(int arr[], int n) {


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

printf("Enter the number of elements: ");


scanf("%d", &n);

int arr[n];

printf("Enter the elements:\n");


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

bubbleSort(arr, n); // Sort the array

printf("Sorted array in ascending order:\n");


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

return 0;
}

Q.6) Write a C program to find GCD of two numbers using


recursion
Soln:
#include <stdio.h>

int gcd(int a, int b) {


if (b == 0) {
return a; // Base case: GCD(a, 0) = a
} else {
return gcd(b, a % b); // Recursive call: GCD(a, b) = GCD(b, a % b)
}
}

int main() {
int num1, num2, result;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);

result = gcd(num1, num2);

printf("GCD of %d and %d is %d\n", num1, num2, result);

return 0;
}

Q.7) Write a C-program to create an array of structures in


order to store details of almost 100books. The
Book details are book name, book price, book page
number and book author name.

Soln.
#include <stdio.h>
#include <string.h>

struct Book {
char name[50];
float price;
int pages;
char author[50];
};

int main() {
struct Book books[100]; // Array to store details of 100 books
int num_books;

printf("Enter the number of books: ");


scanf("%d", &num_books);

for (int i = 0; i < num_books; i++) {


printf("\nEnter details for book %d:\n", i + 1);

printf("Name: ");
fgets(books[i].name, 50, stdin); // Safer input for strings
books[i].name[strcspn(books[i].name, "\n")] = '\0'; // Remove
newline

printf("Price: ");
scanf("%f", &books[i].price);

printf("Pages: ");
scanf("%d", &books[i].pages);

printf("Author: ");
fgets(books[i].author, 50, stdin);
books[i].author[strcspn(books[i].author, "\n")] = '\0';
}

printf("\nBook Details:\n");
for (int i = 0; i < num_books; i++) {
printf("Book %d:\n", i + 1);
printf("Name: %s\n", books[i].name);
printf("Price: %.2f\n", books[i].price);
printf("Pages: %d\n", books[i].pages);
printf("Author: %s\n", books[i].author);
printf("--------------------\n");
}

return 0;
}

Q.8) Write a program to find summation of n numbers


using recursion

Soln:
#include <stdio.h>

int sum_recursive(int n) {
if (n == 0) {
return 0; // Base case: sum of 0 numbers is 0
} else {
return n + sum_recursive(n - 1); // Recursive call: add n to the sum
of (n-1) numbers
}
}

int main() {
int n;

printf("Enter the value of n: ");


scanf("%d", &n);

int sum = sum_recursive(n);

printf("Sum of first %d natural numbers: %d\n", n, sum);

return 0;
}

Q.9) Write a program in C to find the reverse of a given


string without using inbuilt string function

Soln:
#include <stdio.h>

void reverseString(char str[]) {


int len = 0, i, temp;

// Find the length of the string


while (str[len] != '\0') {
len++;
}

// Reverse the string


for (i = 0; i < len / 2; i++) {
// Swap characters at the beginning and end of the unreversed
portion
temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
int main() {
char str[100];

printf("Enter a string: ");


fgets(str, 100, stdin); // Safer input for strings

reverseString(str);

printf("Reversed string: %s", str);

return 0;
}

Q.10) Write a program to check if the entered number is


prime number or not
Soln:
#include <stdio.h>

int main() {
int num, i, isPrime = 1;

printf("Enter a positive integer: ");


scanf("%d", &num);

// Handle cases for 0 and 1


if (num <= 1) {
isPrime = 0; // 0 and 1 are not prime
} else {
// Check for divisibility from 2 up to the square root of num
for (i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = 0; // Number is divisible, not prime
break;
}
}
}

if (isPrime) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}

return 0;
}

Q.11) Write a program to accept a set of 10 numbers and


print the numbers using arrays

Soln:
#include <stdio.h>

int main() {
int numbers[10];
int i;

printf("Enter 10 numbers:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &numbers[i]); // Store each number in the array
}

printf("\nEntered numbers:\n");
for (i = 0; i < 10; i++) {
printf("%d ", numbers[i]); // Print each number from the array
}
printf("\n");

return 0;
}

Q.12) Write a program to print Fibonacci series


Soln:
#include <stdio.h>

int main() {
int n, i, t1 = 0, t2 = 1, nextTerm;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Fibonacci Series: ");

for (i = 1; i <= n; ++i) {


printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}

return 0;
}

Q.13) Write a program using recursion to find factorial of a


number.

Soln:
#include <stdio.h>

long long factorial(int n) {


if (n == 0 || n == 1) {
return 1; // Base case: factorial of 0 or 1 is 1
} else {
return n * factorial(n - 1); // Recursive call: n! = n * (n-1)!
}
}

int main() {
int num;

printf("Enter a non-negative integer: ");


scanf("%d", &num);

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

return 0;
}

Q.14) Write a C program to find LCM of two numbers using


recursion.

Soln:

#include <stdio.h>

int lcm(int a, int b) {


static int common = 1; // Static variable to store the common multiple

if (common % a == 0 && common % b == 0) {


return common; // Base case: found LCM
} else {
common++;
return lcm(a, b); // Recursive call with incremented common
multiple
}
}

int main() {
int num1, num2, result;

printf("Enter two positive integers: ");


scanf("%d %d", &num1, &num2);

result = lcm(num1, num2);

printf("LCM of %d and %d is %d\n", num1, num2, result);

return 0;
}
Q.15) Write a program to find largest of three numbers
using nested if-else.

Soln:

#include <stdio.h>

int main() {
int num1, num2, num3;

printf("Enter three numbers: ");


scanf("%d %d %d", &num1, &num2, &num3);

if (num1 >= num2) {


if (num1 >= num3) {
printf("%d is the largest number.\n", num1);
} else {
printf("%d is the largest number.\n", num3);
}
} else {
if (num2 >= num3) {
printf("%d is the largest number.\n", num2);
} else {
printf("%d is the largest number.\n", num3);
}
}

return 0;
}

Q.16) Write a program to display the following for the user


specified number of lines.
*
**
***
****
*****
******

Soln:
#include <stdio.h>

int main() {
int rows;

printf("Enter the number of lines: ");


scanf("%d", &rows);

for (int i = 1; i <= rows; i++) {


// Print spaces before asterisks
for (int j = 1; j <= rows - i; j++) {
printf(" ");
}

// Print asterisks
for (int j = 1; j <= i; j++) {
printf("*");
}

printf("\n"); // Move to the next line


}

return 0;
}

Q.17) Write a program to print the following pattern. Accept


number of rows from user and display that
much number of rows in output.
1
01
101
0101
Soln:
#include <stdio.h>

int main() {
int rows;

printf("Enter the number of rows: ");


scanf("%d", &rows);

for (int i = 1; i <= rows; i++) {


// Print 1 or 0 based on the current row number and column
for (int j = 1; j <= i; j++) {
printf("%d", 1 - (i + j) % 2); // Alternate between 1 and 0
}

printf("\n"); // Move to the next line


}

return 0;
}

Compiled by Umar

You might also like