0% found this document useful (0 votes)
25 views86 pages

CLanguage Notes

C programming is a general-purpose, procedural language known for its low-level access to system memory, making it efficient for system programming and embedded systems. It combines features of both low-level and high-level languages, allowing for fine-grained control over hardware while maintaining readability. Developed in the early 1970s, C has a straightforward syntax and a rich library, forming the foundation for many modern programming languages.
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)
25 views86 pages

CLanguage Notes

C programming is a general-purpose, procedural language known for its low-level access to system memory, making it efficient for system programming and embedded systems. It combines features of both low-level and high-level languages, allowing for fine-grained control over hardware while maintaining readability. Developed in the early 1970s, C has a straightforward syntax and a rich library, forming the foundation for many modern programming languages.
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

‭1. What is C programming?

[BCA-2016,2018,2019]‬

‭ programming is‬‭a general-purpose, procedural programming‬‭language that provides‬


C
‭low-level access to system memory‬‭,‬

‭Key points about C programming:‬

‭ rocedural:‬
P
‭Instructions are executed in a sequential manner, following a set of procedures.‬
‭Low-level access:‬
‭Can directly interact with system memory and hardware, giving fine-grained control.‬
‭Widely used:‬
‭Commonly used for developing operating systems (like Unix), device drivers, and‬
‭embedded systems.‬
‭Efficient:‬
‭Considered one of the fastest programming languages due to its close connection to‬
‭machine code.‬
‭Learning curve:‬
‭Can be challenging for beginners due to its manual memory management and‬
‭low-level features.‬

‭2. What are the features or characteristics of C? [BCA-2016,2018]‬


‭Simplicity‬‭: C has a straightforward syntax, making‬‭it easy to learn and use.‬
‭Efficiency‬‭: Provides high performance and enables‬‭direct interaction with hardware.‬
‭Portability‬‭: Programs written in C can run on different‬‭platforms with minimal changes.‬
‭Low-Level Access‬‭: Supports memory manipulation through‬‭pointers, offering‬
‭fine-grained control.‬
‭Structured Programming‬‭: Encourages modular programming‬‭by dividing code into‬
‭functions.‬
‭Rich Library Support‬‭: Includes a robust standard library‬‭with numerous built-in‬
‭functions.‬
‭Wide Application Range‬‭: Used in system programming,‬‭embedded systems, and‬
‭performance-critical software.‬
‭Extensibility‬‭: Allows integration with other programming‬‭languages and tools.‬
‭Dynamic Memory Allocation‬‭: Enables efficient use of‬‭memory through functions like‬
‭malloc and free.‬
‭Foundation for Modern Languages‬‭: Forms the basis of‬‭languages like C++, Java, and‬
‭Python.‬

‭3. Why C is called a Mid-level programming language? [BCA-2016,2019]‬

‭ is called a‬‭mid-level programming language‬‭because‬‭it combines the features of‬


C
‭both low-level and high-level languages:‬
‭1.‬ ‭Low-Level Features‬‭:‬
‭○‬ ‭Provides direct access to hardware and memory through pointers.‬
‭○‬ ‭Enables system-level programming, such as writing operating systems‬
‭and drivers.‬
‭2.‬ ‭High-Level Features‬‭:‬
‭○‬ ‭Supports structured programming, functions, and modular code design.‬
‭○‬ ‭Offers a rich standard library and easier syntax compared to assembly‬
‭language.‬

‭ his dual nature makes C versatile, allowing programmers to write efficient,‬


T
‭hardware-focused code while maintaining readability and portability, bridging the gap‬
‭between machine-level and high-level programming.‬

‭4. Explain a brief history of C.‬


‭C was developed by‬‭Dennis Ritchie‬‭at Bell Labs in‬‭the early 1970s. It evolved from the‬
‭B language‬‭, which was created by Ken Thompson. Initially‬‭designed for developing the‬
‭UNIX operating system, C became popular due to its efficiency, portability, and ability to‬
‭write system-level programs. The first standardized version of C, known as‬‭K&R C‬‭, was‬
‭introduced in 1978 with the book‬‭The C Programming‬‭Language‬‭by Kernighan and‬
‭Ritchie. Later, the‬‭ANSI C standard‬‭was established‬‭in 1989 to ensure uniformity across‬
‭platforms, making C a foundation for modern programming languages.‬

‭5. Explain the general structure of C. [BCA-2016,2018,2019]‬

‭The general structure of a C program includes the following components:‬

#include‬
‭1.‬ ‭Preprocessor Directives‬‭: Includes header files and‬‭macros (e.g.,‬‭
‭stdio.h>‬
< ‭).‬
‭ .‬
2 ‭Global Declarations‬‭: Defines global variables and‬‭function prototypes.‬
‭3.‬ ‭Main Function‬‭: The entry point of the program (‬‭ int‬‭main()‬ ‭), where execution‬
‭starts.‬
‭ .‬
4 ‭Variable Declarations‬‭: Declares variables and initializes‬‭them as needed.‬
‭5.‬ ‭Statements and Logic‬‭: Contains the main logic, including‬‭loops, conditional‬
‭statements, and function calls.‬
‭6.‬ ‭Functions‬‭: User-defined or library functions to organize‬‭and reuse code.‬

‭This modular structure ensures readability, reusability, and maintainability in C programs.‬


‭6. Explain how can we execute a C program? [BCA-2016,2018,2019]‬

‭To execute a C program, follow these steps:‬

‭1.‬ W ‭ rite the Code‬‭: Create a C program using a text editor‬‭(e.g., Notepad, VS‬
‭Code) and save the file with a‬‭ .c‬‭extension (e.g.,‬‭
program.c‬ ‭).‬
‭2.‬ ‭Compile the Code‬‭: Use a C compiler like‬‭GCC‬‭(GNU Compiler‬‭Collection) to‬
‭compile the C code. This step converts the source code into machine-readable‬
‭code (an executable).‬
gcc program.c -o program‬

‭3.‬ ‭Link the Code‬‭: The compiler automatically links the‬‭necessary libraries and‬
program‬
‭produces an executable file (e.g.,‬‭ ‭).‬
‭4.‬ ‭Execute the Program‬‭: Run the compiled executable from‬‭the terminal or‬
‭command prompt.‬
program.exe‬

‭ hese steps will compile and execute your C program, displaying the output on‬
T
‭the‬ ‭screen.‬

‭7. What are the comments in c.‬

‭ omments in C are used to add explanatory notes to the code, making it easier to understand‬
C
‭and maintain. They are ignored by the compiler and do not affect the program's execution.‬
‭There are two types of comments in C:‬

//‬‭and continue to‬‭the end of the line.‬


‭1.‬ ‭Single-line comments‬‭: Begin with‬‭

‭// This is a single-line comment‬

‭2.‬ M /*‬‭and end with‬‭


‭ ulti-line comments‬‭: Begin with‬‭ */‬
‭,‬‭allowing comments to span‬
‭multiple lines.‬

‭// This is a single-line comment‬

‭8. What is a token? Explain different types of C tokens. [BCA 2018,2019]‬

I‭n C, a‬‭token‬‭is the smallest unit of a program that‬‭has meaningful interpretation by the‬
‭compiler. Tokens are the building blocks of C code. There are six types of tokens in C:‬

int‬
‭1.‬ ‭Keywords‬‭: Reserved words with special meaning (e.g.,‬‭ return‬
‭,‬‭ if‬
‭,‬‭ ‭).‬
‭ .‬ I‭dentifiers‬‭: Names given to variables, functions, or other user-defined entities.‬
2
‭3.‬ ‭Constants‬‭: Fixed values, such as numbers (‬‭ 100‬ 3.14‬
‭,‬‭ ‭)‬‭or characters (‬‭
'a'‬
‭).‬
+‭,‬‬‭
‭4.‬ ‭Operators‬‭: Symbols that perform operations (e.g.,‬‭ -‭,‬‬‭
*‬ ==‬
‭,‬‭ ‭).‬
‭ .‬ P
5 ;‭,‬‬‭
‭ unctuation‬‭: Characters used to separate code components‬‭(e.g.,‬‭ {‭,‬‬‭
}‭,‬‬‭
,‭)‬.‬
‭6.‬ ‭String Literals‬‭: Sequences of characters enclosed‬‭in double quotes (e.g.,‬
"Hello, World!"‬
‭ ‭).‬

‭Tokens are essential for constructing valid C programs.‬

‭9. Explain the term variable and constants. Explain the types of constants. [BCA 2017,2019]‬

‭ ariable‬‭:‬
V
‭A‬‭variable‬‭is a named storage location in memory that‬‭can hold different values during‬
‭program execution. The value of a variable can be changed, and it must be declared‬
int‬
‭with a specific data type (e.g.,‬‭ float‬
‭,‬‭ ‭).‬

‭ onstant‬‭:‬
C
‭A‬‭constant‬‭is a value that cannot be modified during‬‭program execution. Once‬
‭assigned, it remains fixed. Constants provide safety and clarity in the code by preventing‬
‭accidental changes.‬

‭Types of Constants:‬

10‬
‭1.‬ ‭Integer Constants‬‭: Whole numbers (e.g.,‬‭ -5‬
‭,‬‭ 200‬
‭,‬‭ ‭).‬
3.14‬
‭2.‬ ‭Floating-point Constants‬‭: Numbers with decimals (e.g.,‬‭ -0.5‬
‭,‬‭ ‭).‬
'A'‬
‭3.‬ ‭Character Constants‬‭: Single characters enclosed in‬‭single quotes (e.g.,‬‭ ‭,‬
‭1'‬
' ‭).‬
‭4.‬ ‭String Constants‬‭: Sequences of characters enclosed‬‭in double quotes (e.g.,‬
"Hello"‬
‭ "C language"‬
‭,‬‭ ‭).‬

‭ onstants ensure values remain constant throughout the program and are often used for‬
C
‭fixed values like pi or max limits.‬
‭10. Explain escape sequence characters. [BCA 2016,2018,2019]‬

‭ scape Sequence Characters‬‭in C are special characters used to represent certain‬


E
‭actions or formatting in strings, often involving characters that are difficult to type directly.‬
‭They begin with a backslash (‬‭\‭)‬followed by a character. Here are some commonly used‬
‭escape sequences:‬

‭1.‬ ‭
\n‬
‭: Newline (moves the cursor to the next line).‬
‭2.‬ ‭
\t‬
‭: Tab (inserts a tab space).‬
‭3.‬ ‭
\\‬
‭: Backslash (inserts a literal backslash).‬
‭4.‬ ‭
\'‬
‭: Single quote (inserts a literal single quote).‬
‭5.‬ ‭
\"‬
‭: Double quote (inserts a literal double quote).‬
‭6.‬ ‭
\r‬
‭: Carriage return (moves the cursor to the beginning of the line).‬
‭7.‬ ‭
\b‬
‭: Backspace (moves the cursor one character back).‬
‭8.‬ ‭
\f‬
‭: Form feed (moves the cursor to the next page in printing).‬
‭9.‬ ‭
\0‬
‭: Null character (marks the end of a string).‬

‭ hese escape sequences are essential for formatting output and handling special‬
T
‭characters in C programs.‬

‭11. What is Data Type? Explain various data types in C. [BCA-2016,2018.2019]‬

‭ ata Type‬‭:‬
D
‭A‬‭data type‬‭in C defines the type and size of data that can be stored in a variable. It‬
‭specifies the operations that can be performed on the data and determines the memory‬
‭required to store it.‬

‭Types of Data Types in C:‬

‭1.‬ ‭Basic Data Types‬‭:‬


10‬
‭○‬ ‭int‬‭: Stores integers (e.g.,‬‭ -5‬
‭,‬‭ ‭).‬
3.14‬
‭○‬ ‭float‬‭: Stores floating-point numbers (e.g.,‬‭ -0.5‬
‭,‬‭ ‭).‬
3.14159‬
‭○‬ ‭double‬‭: Stores double-precision floating-point numbers (e.g.,‬‭ ‭).‬
‭ ‬ ‭char‬‭: Stores single characters (e.g.,‬‭
○ 'A'‬ '1'‬
‭,‬‭ ‭).‬
‭2.‬ ‭Derived Data Types‬‭:‬
‭○‬ ‭Arrays‬‭: A collection of elements of the same data type.‬
‭○‬ ‭Pointers‬‭: Stores the address of another variable.‬
‭○‬ ‭Structures‬‭: A collection of different data types grouped together.‬
‭○‬ ‭Unions‬‭: A collection where different data types share the same memory‬
‭location.‬
‭ .‬ ‭Void Data Type‬‭:‬
3
‭○‬ v
‭ oid‬‭: Represents no value or absence of type (e.g., function that doesn’t‬
‭return a value).‬

‭ hese data types allow C programs to store and manipulate various types of data‬
T
‭efficiently.‬

‭12. What is an Operator? Explain various operators in C. [BCA-2016,2018,2019]‬

‭ perator‬‭:‬
O
‭An‬‭operator‬‭in C is a symbol used to perform operations on variables and values.‬
‭Operators allow manipulation of data and variables, enabling arithmetic, logical, and‬
‭relational operations in a program.‬

‭Types of Operators in C:‬

‭1.‬ ‭Arithmetic Operators‬‭: Perform basic mathematical operations.‬


‭○‬ ‭+‬‭(Addition),‬‭
-‬‭(Subtraction),‬‭
*‬‭(Multiplication),‬‭
/‬‭(Division),‬‭
%‬‭(Modulus).‬
‭2.‬ ‭Relational Operators‬‭: Compare two values.‬
‭○‬ ‭
==‬‭(Equal to),‬‭!=‬‭(Not equal to),‬‭
>‬‭(Greater than),‬‭ <‬‭(Less than),‬‭
>=‬
<=‬‭(Less than or equal to).‬
(‭ Greater than or equal to),‬‭
‭3.‬ ‭Logical Operators‬‭: Used for logical operations, often in conditional statements.‬
‭○‬ ‭ &&‬‭(Logical AND),‬‭||‬‭(Logical OR),‬‭ !‬‭(Logical NOT).‬
‭ .‬ ‭Bitwise Operators‬‭: Perform bit-level operations.‬
4
‭○‬ ‭&‬‭(Bitwise AND),‬‭
|‬‭(Bitwise OR),‬‭^‬‭(Bitwise XOR),‬‭~‬‭(Bitwise NOT),‬‭
<<‬
>>‬‭(Right shift).‬
‭(Left shift),‬‭
‭5.‬ ‭Assignment Operators‬‭: Assign values to variables.‬
‭○‬ ‭ =‬‭(Simple assignment),‬‭ +=‬ -=‬
‭,‬‭ *=‬
‭,‬‭ /=‬
‭,‬‭ %=‬‭(Compound assignment).‬
‭,‬‭
‭6.‬ ‭Increment/Decrement Operators‬‭: Increase or decrease the value of a variable‬
‭by 1.‬
‭○‬ ‭ ++‬‭(Increment),‬‭ --‬‭(Decrement).‬
‭7.‬ ‭Conditional (Ternary) Operator‬‭: Shortened form of if-else.‬
‭○‬ ‭ ?:‬‭(Condition ? True_expression : False_expression).‬
‭8.‬ ‭Sizeof Operator‬‭: Returns the size of a data type or variable.‬
‭○‬ ‭ sizeof‬ ‭.‬
‭9.‬ ‭Pointer Operators‬‭: Used to access the address or value of a pointer.‬
‭○‬ ‭&‬‭(Address of),‬‭ *‬‭(Dereference).‬

‭ hese operators are fundamental to performing calculations, comparisons, and‬


T
‭manipulating data in C programs.‬
‭13. Explain different types of input/output functions with syntax.[BCA-2016,2018,2019]‬
‭// Output Functions‬

/‭/ printf() - Prints formatted output‬


‭printf("format_string", argument1, argument2, ...);‬

/‭/ Example:‬
‭printf("Hello, World!\n");‬

/‭/ putchar() - Prints a single character‬


‭putchar(char);‬

/‭/ Example:‬
‭putchar('A');‬

/‭/ puts() - Prints a string followed by a newline‬


‭puts("string");‬

/‭/ Example:‬
‭puts("Hello, World!");‬

‭// Input Functions‬

/‭/ scanf() - Reads formatted input‬


‭scanf("format_string", &variable1, &variable2, ...);‬

/‭/ Example:‬
‭scanf("%d", &age);‬

/‭/ getchar() - Reads a single character‬


‭getchar();‬

/‭/ Example:‬
‭char ch = getchar();‬

/‭/ gets() - Reads a string until newline (not recommended for safety reasons)‬
‭gets(str);‬

/‭/ Example:‬
‭gets(name);‬
‭ 4. Explain different types of Flow control or Control structure or statements in C.‬
1
‭[BCA-2016,2019]‬

‭// Flow Control Statements in C‬

‭// 1. Sequential Control - Default execution (one after another)‬

‭// 2. Conditional Statements (Decision-making)‬

/‭/ if - Executes block of code if condition is true‬


‭if (condition) {‬
‭// code to execute‬
‭}‬

/‭/ if-else - Executes one block if condition is true, another if false‬


‭if (condition) {‬
‭// true code‬
‭} else {‬
‭// false code‬
‭}‬

/‭/ else-if - Checks multiple conditions‬


‭if (condition1) {‬
‭// code for condition1‬
‭} else if (condition2) {‬
‭// code for condition2‬
‭} else {‬
‭// code if no condition is true‬
‭}‬

/‭/ switch - Executes one block of code based on variable's value‬


‭switch (variable) {‬
‭case value1:‬
‭// code for value1‬
‭break;‬
‭case value2:‬
‭// code for value2‬
‭break;‬
‭default:‬
‭// default code‬
‭}‬
‭// 3. Looping Statements (Repetition)‬

/‭/ for - Repeats code a specified number of times‬


‭for (initialization; condition; increment) {‬
‭// code to execute‬
‭}‬

/‭/ while - Repeats code as long as condition is true‬


‭while (condition) {‬
‭// code to execute‬
‭}‬

/‭/ do-while - Repeats code at least once, then checks condition‬


‭do {‬
‭// code to execute‬
‭} while (condition);‬

‭// 4. Jump Statements‬

/‭/ break - Exits a loop or switch statement early‬


‭break;‬

/‭/ continue - Skips the current iteration of a loop and continues to the next‬
‭continue;‬

/‭/ return - Exits from a function and optionally returns a value‬


‭return value;‬

‭ 5. Explain Decision Making or Control Statement. [BCA 2018] Explain difference between‬
1
‭if-else and switch case statement.‬

‭Decision Making / Control Statements:‬

‭ ecision-making statements in C allow the program to execute different code depending on‬
D
‭whether a condition is true or false. These control statements help in making decisions,‬
‭branching, and executing certain sections of code based on conditions.‬

‭Types of Decision Making Statements:‬

‭ .‬ i‭f‬‭: Executes a block of code if the condition is true.‬


1
‭2.‬ ‭if-else‬‭: Executes one block of code if the condition‬‭is true, another if false.‬
‭3.‬ ‭else-if‬‭: Checks multiple conditions and executes corresponding‬‭blocks.‬
‭4.‬ s
‭ witch-case‬‭: Compares a variable with different values (cases) and executes the‬
‭corresponding block of code.‬

if-else‬‭and‬‭
‭Difference between‬‭ switch-case‬
‭:‬
‭Aspect‬ if-else‬‭Statement‬
‭ switch-case‬‭Statement‬

‭Use Case‬ ‭ est for complex conditions with‬


B ‭ est for selecting among a limited set‬
B
‭relational or logical comparisons.‬ ‭of options based on a single variable.‬

‭ ondition‬
C ‭ an evaluate a wide range of‬
C ‭ ompares a variable against a series‬
C
‭Type‬ ‭conditions (comparisons, logical‬ ‭of constants or values.‬
‭operators).‬

‭Efficiency‬ ‭ ess efficient for checking multiple‬


L ‭ ore efficient for handling many‬
M
‭conditions.‬ ‭possible values for a single variable.‬

‭Flexibility‬ ‭ ore flexible, can handle complex‬


M ‭ ess flexible, only works with specific‬
L
‭conditions with different operators.‬ ‭constant values.‬

‭Example‬ c if (x > 10) { /* code */ }‬ ‭


‭ c switch(x) { case 1: /*‬
else { /* code */ }‬
‭ code */ break; default: /*‬

code */ }‬

if-else‬‭when you have complex conditions‬‭or different types of comparisons,‬


‭In short, use‬‭
‭ nd use‬‭
a switch-case‬‭when you need to compare a single‬‭variable with multiple constant‬
‭values.‬

‭16. Compare if-else with the ternary operator. [BCA 2017]‬

if-else‬‭and Ternary Operator:‬


‭Comparison between‬‭
‭Aspect‬ if-else‬‭Statement‬
‭ ‭Ternary Operator (‬‭
?:‬
‭)‬

‭Syntax‬ if (condition) {‬ ‭Compact:‬‭


‭More verbose:‬‭ condition ?‬
/* code */ } else { /* code‬ ‭
‭ true_expression :‬
*/ }‬
‭ false_expression;‬

‭Use Case‬ ‭ sed for multiple statements or more‬ B


U ‭ est for simple conditions with one‬
‭complex logic.‬ ‭expression for both true/false.‬
‭Readability‬ ‭ asier to read for complex‬
E ‭ ore concise but can be harder to‬
M
‭conditions.‬ ‭read for complex conditions.‬

‭ xecution‬
E ‭ xecutes multiple statements for‬
E ‭ xecutes only one expression based‬
E
‭Flow‬ ‭each condition.‬ ‭on the condition.‬

‭Example‬ if (x > 10) { y = 5; } else‬ ‭


‭ y = (x > 10) ? 5 : 10;‬
{ y = 10; }‬

‭Key Differences:‬

‭‬ ‭
● if-else‬‭is used for more complex conditions and multiple‬‭statements.‬
‭●‬ ‭Ternary operator‬‭is a more compact way of writing‬‭simple‬‭if-else‬‭logic in a single line.‬

if-else‬‭for more‬
I‭n summary, use the‬‭ternary operator‬‭for simpler,‬‭one-liner conditions, and‬‭
‭complex decision-making.‬

‭17. What is Loop? Explain all types of loops in C with an example. [BCA-2016,2017,2018]‬

/‭/ Loop in C‬
‭// A loop is a control structure that repeats a block of code as long as a condition is true.‬

/‭/ 1. for Loop‬


‭// The for loop is used when the number of iterations is known beforehand.‬
‭for (initialization; condition; increment/decrement) {‬
‭// code to execute‬
‭}‬

/‭/ Example:‬
‭for (int i = 0; i < 5; i++) {‬
‭printf("%d ", i); // Output: 0 1 2 3 4‬
‭}‬

/‭/ 2. while Loop‬


‭// The while loop executes the code block as long as the given condition is true.‬
‭// The condition is checked before each iteration.‬
‭while (condition) {‬
‭// code to execute‬
‭}‬

‭// Example:‬
i‭nt i = 0;‬
‭while (i < 5) {‬
‭printf("%d ", i); // Output: 0 1 2 3 4‬
‭i++;‬
‭}‬

/‭/ 3. do-while Loop‬


‭// The do-while loop guarantees at least one iteration because the condition is checked‬
‭after the code block is executed.‬
‭do {‬
‭// code to execute‬
‭} while (condition);‬

/‭/ Example:‬
‭int i = 0;‬
‭do {‬
‭printf("%d ", i); // Output: 0 1 2 3 4‬
‭i++;‬
‭} while (i < 5);‬

/‭/ Summary:‬
‭// - for loop: Best when the number of iterations is known.‬
‭// - while loop: Best when the condition is checked before the loop starts.‬
‭// - do-while loop: Ensures at least one iteration regardless of the condition.‬

‭ 8. Explain the difference between entry-controlled and exit-controlled loops with a suitable‬
1
‭example. [BCA 2019]‬

‭// Entry-Controlled vs Exit-Controlled Loops‬

/‭/ 1. Entry-Controlled Loop‬


‭// In an entry-controlled loop, the condition is checked before the loop body is executed.‬
‭// If the condition is false initially, the loop body is not executed at all.‬

/‭/ Example: for loop and while loop are entry-controlled‬


‭for (initialization; condition; increment) {‬
‭// loop body‬
‭}‬

/‭/ Example:‬
‭int i = 0;‬
‭while (i < 5) {‬
‭printf("%d ", i); // Output: 0 1 2 3 4‬
‭i++;‬
‭}‬

/‭/ Here, the condition i < 5 is checked before the loop body is executed. If false initially, the loop‬
‭won't run.‬

/‭/ 2. Exit-Controlled Loop‬


‭// In an exit-controlled loop, the condition is checked after the loop body is executed.‬
‭// This ensures the loop body executes at least once, even if the condition is false initially.‬

/‭/ Example: do-while loop is exit-controlled‬


‭do {‬
‭// loop body‬
‭} while (condition);‬

/‭/ Example:‬
‭int i = 0;‬
‭do {‬
‭printf("%d ", i); // Output: 0 1 2 3 4‬
‭i++;‬
‭} while (i < 5);‬

/‭/ Here, the loop body is executed first, and then the condition i < 5 is checked after each‬
‭iteration.‬

/‭* Summary:‬
‭- Entry-Controlled Loop: The condition is checked before the loop starts (e.g., `for`, `while`).‬
‭- Exit-Controlled Loop: The condition is checked after the loop body is executed (e.g.,‬
‭̀do-while`).‬

I‭n an entry-controlled loop, the loop may not execute if the condition is false initially,‬
‭while in an exit-controlled loop, the loop will always execute at least once. */‬

‭19. What are jump statements? Explain. [BCA-2016,2017,2018]‬


‭// Jump Statements in C‬

/‭/ 1. break‬
‭// The break statement is used to exit from a loop or a switch statement prematurely.‬
‭for (int i = 0; i < 10; i++) {‬
‭if (i == 5) {‬
‭break; // Exits the loop when i equals 5‬
‭}‬
‭}‬

/‭/ 2. continue‬
‭// The continue statement skips the current iteration of a loop and moves to the next iteration.‬
‭for (int i = 0; i < 5; i++) {‬
‭if (i == 3) {‬
‭continue; // Skips the iteration when i equals 3‬
‭}‬
‭printf("%d ", i); // Output: 0 1 2 4‬
‭}‬

/‭/ 3. return‬
‭// The return statement is used to exit a function and optionally return a value.‬
‭int add(int a, int b) {‬
‭return a + b; // Exits the function and returns the result‬
‭}‬

/‭/ Summary:‬
‭// - break: Exits a loop or switch statement early.‬
‭// - continue: Skips the current loop iteration and moves to the next.‬
‭// - return: Exits from a function and optionally returns a value.‬

‭20. Write a program to check whether a number is perfect or not. [BCA-2018,2019]‬

‭Here's a C program to check whether a given number is a‬‭perfect number‬‭or not:‬

‭ ‬‭perfect number‬‭is a positive integer that is equal‬‭to the sum of its proper divisors, excluding‬
A
‭the number itself. For example, 6 is a perfect number because its divisors (excluding 6) are 1, 2,‬
‭and 3, and 1 + 2 + 3 = 6.‬

‭#include <stdio.h>‬

/‭/ Function to check if a number is perfect‬


‭int isPerfect(int num) {‬
‭int sum = 0;‬
/‭/ Find divisors and calculate the sum‬
‭for (int i = 1; i <= num / 2; i++) {‬
‭if (num % i == 0) {‬
‭sum += i;‬
‭}‬
‭}‬

/‭/ Check if sum of divisors equals the number‬


‭if (sum == num) {‬
‭return 1; // Perfect number‬
‭}‬
‭return 0; // Not a perfect number‬
‭}‬

‭int main() {‬
‭int num;‬

/‭/ Input number from the user‬


‭printf("Enter a number: ");‬
‭scanf("%d", &num);‬

/‭/ Check and output result‬


‭if (isPerfect(num)) {‬
‭printf("%d is a perfect number.\n", num);‬
‭} else {‬
‭printf("%d is not a perfect number.\n", num);‬
‭}‬

‭return 0;‬
‭}‬

‭Explanation:‬

‭●‬ T isPerfect(int num)‬‭calculates the sum‬‭of all divisors of the given‬


‭ he function‬‭
‭number (excluding the number itself).‬
num / 2‬
‭●‬ ‭It loops from 1 to‬‭ num‬‭without a remainder‬
‭, checking if each number‬‭divides‬‭
‭(‬‭
num % i == 0‬ ‭). If it does, the divisor is added to‬‭the sum.‬
‭‬ A
● ‭ fter the loop, if the sum of divisors equals the original number, it is a‬‭perfect number‬‭.‬
‭●‬ ‭The‬‭ main‬‭function prompts the user for input and displays‬‭whether the number is perfect‬
‭or not.‬

‭Example Output‬‭:‬
‭ nter a number: 6‬
E
‭6 is a perfect number.‬

‭ nter a number: 10‬


E
‭10 is not a perfect number.‬

‭21. Write a program to check whether a number is prime or not. [BCA 2016,2017]‬

‭Here is a C program to check whether a number is a‬‭prime number‬‭or not:‬

‭ ‬‭prime number‬‭is a number greater than 1 that has‬‭no divisors other than 1 and itself. For‬
A
‭example, 7 is a prime number because it can only be divided by 1 and 7.‬

‭C Program:‬
‭#include <stdio.h>‬

/‭/ Function to check if a number is prime‬


‭int isPrime(int num) {‬
‭// Handle edge cases for numbers less than 2‬
‭if (num <= 1) {‬
‭return 0; // Not a prime number‬
‭}‬

/‭/ Check for divisors from 2 to sqrt(num)‬


‭for (int i = 2; i * i <= num; i++) {‬
‭if (num % i == 0) {‬
‭return 0; // Not a prime number‬
‭}‬
‭}‬

‭return 1; // Prime number‬


‭}‬

‭int main() {‬
‭int num;‬

/‭/ Input number from the user‬


‭printf("Enter a number: ");‬
‭scanf("%d", &num);‬

/‭/ Check and output result‬


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

‭return 0;‬
‭}‬

‭Explanation:‬

isPrime(int num)‬‭checks if a number is‬‭prime.‬


‭●‬ ‭The function‬‭
0‬‭(not prime).‬
‭●‬ ‭For numbers less than or equal to 1, it returns‬‭
‭●‬ I‭t then checks if the number is divisible by any integer from 2 to‬‭ sqrt(num)‬‭(this‬
‭optimization reduces unnecessary checks).‬
‭●‬ ‭If the number has a divisor other than 1 and itself, it is not prime.‬
‭●‬ ‭The‬‭ main‬‭function reads input from the user and calls‬‭the‬‭
isPrime‬‭function to‬
‭determine whether the number is prime.‬

‭Here is a C program to check whether a number is a‬‭prime number‬‭or not:‬

‭ ‬‭prime number‬‭is a number greater than 1 that has‬‭no divisors other than 1 and itself. For‬
A
‭example, 7 is a prime number because it can only be divided by 1 and 7.‬

‭C Program:‬
#include <stdio.h>‬

// Function to check if a number is prime‬



int isPrime(int num) {‬

// Handle edge cases for numbers less than 2‬

if (num <= 1) {‬

return 0; // Not a prime number‬

}‬

// Check for divisors from 2 to sqrt(num)‬



for (int i = 2; i * i <= num; i++) {‬

if (num % i == 0) {‬

return 0; // Not a prime number‬

}‬

}‬

return 1; // Prime number‬

}‬

int main() {‬

int num;‬

// Input number from the user‬



printf("Enter a number: ");‬

scanf("%d", &num);‬

// Check and output result‬



if (isPrime(num)) {‬

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

} else {‬

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

}‬

return 0;‬

}‬

‭Explanation:‬

isPrime(int num)‬‭checks if a number is‬‭prime.‬


‭●‬ ‭The function‬‭
0‬‭(not prime).‬
‭●‬ ‭For numbers less than or equal to 1, it returns‬‭
‭●‬ I‭t then checks if the number is divisible by any integer from 2 to‬‭ sqrt(num)‬‭(this‬
‭optimization reduces unnecessary checks).‬
‭●‬ ‭If the number has a divisor other than 1 and itself, it is not prime.‬
‭●‬ ‭The‬‭ main‬‭function reads input from the user and calls‬‭the‬‭
isPrime‬‭function to‬
‭determine whether the number is prime.‬

‭Example Output:‬
‭ nter a number: 7‬
E
‭7 is a prime number.‬

‭ nter a number: 10‬


E
‭10 is not a prime number.‬

‭22. Write a program to find the factorial of a number.[BCA 2019]‬


‭#include <stdio.h>‬
/‭/ Function to find factorial of a number‬
‭int factorial(int num) {‬
‭int fact = 1;‬

/‭/ Calculate factorial‬


‭for (int i = 1; i <= num; i++) {‬
‭fact *= i;‬
‭}‬

‭return fact;‬
‭}‬

‭int main() {‬
‭int num;‬

/‭/ Input number from the user‬


‭printf("Enter a number: ");‬
‭scanf("%d", &num);‬

/‭/ Check for negative numbers‬


‭if (num < 0) {‬
‭printf("Factorial of a negative number doesn't exist.\n");‬
‭} else {‬
‭// Find and output factorial‬
‭printf("Factorial of %d is %d\n", num, factorial(num));‬
‭}‬

‭return 0;‬
‭}‬

‭Explanation:‬

‭●‬ T ‭ he‬‭ factorial(int num)‬‭function now returns an‬‭ int‬‭type. Since the‬‭ int‬
‭type is typically suitable for smaller factorial values (up to 12!), it's appropriate if‬
‭the user is working with relatively small numbers.‬
‭●‬ ‭If the number is negative, the program informs the user that the factorial of a‬
‭negative number doesn't exist.‬
‭●‬ ‭The program computes the factorial using a loop and returns the result as an‬
‭integer.‬

‭ xample Output‬‭:‬
E
‭Enter a number: 5‬
‭Factorial of 5 is 120‬

‭ nter a number: 7‬
E
‭Factorial of 7 is 5040‬

‭ nter a number: -3‬


E
‭Factorial of a negative number doesn't exist.‬

‭ 3. What is an Array? How is it different from an ordinary variable? Discuss rules to declare a‬
2
‭one-dimensional array. [BCA-2016]‬

‭Array in C‬

‭ n‬‭array‬‭in C is a collection of variables of the‬‭same type that are stored in contiguous memory‬
A
‭locations. Arrays allow you to store multiple values in a single variable, making it easier to‬
‭manage and manipulate related data. For example, you can store multiple integers, floats, or‬
‭characters in an array, rather than creating multiple variables for each value.‬

‭Difference Between an Array and an Ordinary Variable‬

‭1.‬ ‭Single vs. Multiple Values‬‭:‬


‭○‬ ‭An‬‭ordinary variable‬‭holds only‬‭one value‬‭of a specified‬‭type at a time (e.g., an‬
int‬‭can store only a single integer).‬

‭○‬ ‭An‬‭array‬‭holds‬‭multiple values‬‭of the same type, where‬‭each value is accessed‬
‭using an‬‭index‬‭.‬
‭2.‬ ‭Memory Allocation‬‭:‬
‭○‬ ‭An‬‭ordinary variable‬‭is allocated memory for one element.‬
‭○‬ ‭An‬‭array‬‭allocates memory for multiple elements, based‬‭on its size. Each‬
‭element is stored in contiguous memory locations.‬
‭3.‬ ‭Access‬‭:‬
‭○‬ ‭An‬‭ordinary variable‬‭is accessed directly by its name.‬
‭○‬ ‭An‬‭array‬‭is accessed using an index that specifies‬‭the position of the element‬
arr[0]‬
‭within the array (e.g.,‬‭ arr[1]‬
‭,‬‭ ‭).‬
‭4.‬ ‭Flexibility‬‭:‬
‭○‬ ‭An‬‭ordinary variable‬‭can only store one value at a‬‭time.‬
‭○‬ ‭An‬‭array‬‭can store many values, and those values can‬‭be accessed and‬
‭manipulated individually.‬

‭Declaring a One-Dimensional Array‬

‭ one-dimensional array is essentially a list of elements stored in contiguous memory. Here's‬


A
‭how to declare a one-dimensional array in C:‬
‭Syntax:‬
‭data_type array_name[array_size];‬

data_type‬
‭ int‬
‭: The type of data the array will hold (e.g.,‬‭ float‬
‭,‬‭ char‬
‭,‬‭ ‭).‬
array_name‬
‭ arr‬
‭: The name of the array (e.g.,‬‭ ‭).‬
‭rray_size‬
a ‭: The number of elements in the array (this should be a constant value or a‬
‭variable).‬

‭Rules for Declaring a One-Dimensional Array:‬

‭1.‬ T ‭ ype of Elements‬‭: All elements in an array must be‬‭of the same data type (e.g., all‬
‭integers, all floats).‬
‭2.‬ ‭Array Size‬‭: The size of the array must be specified‬‭during declaration (except in the‬
‭case of dynamic arrays where the size can be defined at runtime).‬
‭3.‬ ‭Indexing‬‭: The elements of the array are accessed using‬‭zero-based indexing (i.e., the‬
‭first element is at index‬‭0‬ 1‭,‬etc.).‬
‭, the second element at‬‭index‬‭
‭4.‬ ‭Memory Allocation‬‭: The size of the array determines‬‭how much memory will be‬
‭allocated to store its elements.‬

‭Example of One-Dimensional Array Declaration:‬


‭#include <stdio.h>‬

‭int main() {‬
‭// Declaring a one-dimensional array of integers with 5 elements‬
‭int arr[5];‬

/‭/ Initializing the array‬


‭arr[0] = 10;‬
‭arr[1] = 20;‬
‭arr[2] = 30;‬
‭arr[3] = 40;‬
‭arr[4] = 50;‬

/‭/ Accessing and printing array elements‬


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

‭return 0;‬
‭}‬
‭Explanation:‬

‭‬ i
● ‭nt arr[5];‬‭declares an integer array‬‭ arr‬‭with 5 elements.‬
‭●‬ ‭Each element of the array is assigned a value.‬
for‬l‭oop is used to print the elements of the array.‬
‭●‬ ‭A‬‭

‭Summary:‬

‭●‬ A ‭ n‬‭array‬‭is a collection of elements of the same type,‬‭stored in contiguous memory‬


‭locations.‬
‭●‬ ‭Unlike an‬‭ordinary variable‬‭, an array can store multiple‬‭values of the same type.‬
‭●‬ ‭The rules for declaring a one-dimensional array include specifying the type, name, and‬
‭size of the array.‬

‭ 4. What do you mean by an Array? What are the different types of Array? Explain the merits‬
2
‭and demerits of array.[BCA 2018, BCA MJ-1 2022]‬

‭Array in C (Short Summary)‬

‭ n‬‭array‬‭in C is a collection of variables of the‬‭same type stored in contiguous memory‬


A
‭locations. It allows you to store multiple values in a single variable and access them using an‬
‭index.‬

‭Types of Arrays:‬

‭1.‬ O ‭ ne-Dimensional Array (1D)‬‭: A list of elements of the same type.‬


‭int arr[5] = {1, 2, 3, 4, 5};‬
‭2.‬ ‭Two-Dimensional Array (2D)‬‭: A matrix with rows and columns.‬
‭int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};‬
‭3.‬ ‭Multi-Dimensional Array‬‭: Arrays with more than two dimensions.‬
‭4.‬ ‭Dynamic Array‬‭: Arrays whose size is determined at runtime.‬
‭int *arr = (int*) malloc(n * sizeof(int)); // Dynamic 1D array‬

‭Merits of Arrays:‬

‭ .‬
1 ‭ fficient Access‬‭: Fast access to elements via index.‬
E
‭2.‬ ‭Easy Use‬‭: Simplifies managing related data.‬
‭3.‬ ‭Memory Efficient‬‭: Fixed size can be memory-efficient.‬
‭4.‬ ‭Supports Multi-Dimensional Data‬‭: Useful for matrices,‬‭grids.‬
‭5.‬ ‭Easy Iteration‬‭: Simplifies operations like searching and sorting.‬
‭Demerits of Arrays:‬

‭ .‬
1 ‭ ixed Size‬‭: Size must be known at declaration time.‬
F
‭2.‬ ‭Memory Wastage‬‭: Extra space may be unused.‬
‭3.‬ ‭Difficult Insertion/Deletion‬‭: Operations can be inefficient.‬
‭4.‬ ‭Limited Flexibility‬‭: Not as flexible as dynamic structures‬‭(e.g., linked lists).‬
‭5.‬ ‭Risk of Overflow‬‭: Accessing out-of-bounds elements‬‭causes errors.‬

‭Arrays are essential in C but have limitations in flexibility and dynamic use.‬

‭ 5. What is a two-dimensional array? How it is different from a one-dimensional array? Give‬


2
‭Syntax. [BCA 2019]‬

‭Two-Dimensional Array in C‬

‭ ‬‭two-dimensional array‬‭is an array of arrays that‬‭represents data in a tabular or matrix form,‬


A
‭where data is organized in rows and columns. Each element in a 2D array is accessed using‬
‭two indices: one for the row and one for the column.‬

‭Difference Between One-Dimensional and Two-Dimensional Arrays‬


‭Aspect‬ ‭One-Dimensional Array‬ ‭Two-Dimensional Array‬

‭Structure‬ ‭Represents a list of elements.‬ ‭ epresents a table or matrix (rows &‬


R
‭columns).‬

‭Access‬ ‭ ccessed using a single index‬


A ‭ ccessed using two indices (e.g.,‬
A
arr[i]‬
‭(e.g.,‬‭ ‭).‬ arr[i][j]‬
‭ ‭).‬

‭ emory‬
M ‭ lements are stored in contiguous‬ R
E ‭ ows are stored as 1D arrays in‬
‭Layout‬ ‭memory.‬ ‭contiguous memory.‬

‭Example‬ int arr[5];‬‭(list of integers).‬


‭ ‭nt arr[2][3];‬‭(2 rows and 3‬
i
‭columns).‬

‭Syntax of a Two-Dimensional Array‬


‭‬
c
‭Copy code‬
data_type array_name[rows][columns];‬

‭●‬ ‭
data_type‬ int‬
‭: The type of data to be stored (e.g.,‬‭ float‬
‭,‬‭ char‬
‭,‬‭ ‭).‬
‭●‬ ‭
array_name‬
‭: The name of the array.‬
‭●‬ ‭
rows‬
‭: The number of rows in the array.‬
‭●‬ ‭
columns‬
‭: The number of columns in the array.‬

‭Example Program for 2D Array‬


‭#include <stdio.h>‬

‭int main() {‬
‭int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};‬

/‭/ Displaying elements of the 2D array‬


‭printf("Elements of the 2D array are:\n");‬
‭for (int i = 0; i < 2; i++) {‬
‭for (int j = 0; j < 3; j++) {‬
‭printf("%d ", arr[i][j]);‬
‭}‬
‭printf("\n");‬
‭}‬

‭return 0;‬
‭}‬

‭Explanation:‬

int arr[2][3];‬‭creates a 2D array with‬‭2 rows and 3 columns.‬


‭1.‬ ‭Declaration‬‭:‬‭
arr[2][3] = {{1, 2, 3}, {4, 5, 6}};‬‭initializes the array with‬
‭2.‬ I‭nitialization‬‭:‬‭
‭values.‬
arr[i][j]‬
‭3.‬ ‭Accessing Elements‬‭: Each element is accessed using‬‭ i‬‭is the row‬
‭, where‬‭
j‬‭is the column index.‬
‭index and‬‭

‭Output:‬
‭ lements of the 2D array are:‬
E
‭1 2 3‬
‭4 5 6‬

‭This demonstrates how to work with two-dimensional arrays in C.‬

‭ 6. Write a program to find the sum of left and right diagonal elements of a square matrix/2D‬
2
‭array.[BCA 2016,2018]‬
‭ ere’s a C program to find the sum of the left and right diagonal elements of a square matrix:‬
H
‭#include <stdio.h>‬

‭int main() {‬
‭int n;‬

/‭/ Input size of the square matrix‬


‭printf("Enter the size of the square matrix: ");‬
‭scanf("%d", &n);‬

i‭nt matrix[n][n];‬
‭int leftDiagonalSum = 0, rightDiagonalSum = 0;‬

/‭/ Input elements of the matrix‬


‭printf("Enter the elements of the %dx%d matrix:\n", n, n);‬
‭for (int i = 0; i < n; i++) {‬
‭for (int j = 0; j < n; j++) {‬
‭scanf("%d", &matrix[i][j]);‬
‭}‬
‭}‬

/‭/ Calculate the sums of the left and right diagonals‬


‭for (int i = 0; i < n; i++) {‬
‭leftDiagonalSum += matrix[i][i]; // Left diagonal: matrix[i][i]‬
‭rightDiagonalSum += matrix[i][n - i - 1]; // Right diagonal: matrix[i][n-i-1]‬
‭}‬

/‭/ Output the results‬


‭printf("Sum of left diagonal: %d\n", leftDiagonalSum);‬
‭printf("Sum of right diagonal: %d\n", rightDiagonalSum);‬

‭return 0;‬
‭}‬

‭Explanation:‬

‭1.‬ ‭Matrix Input‬‭:‬


‭○‬ ‭The user is prompted to enter the size of the square matrix (‬‭
n‭)‬.‬
‭○‬ ‭The elements of the‬‭ n x n‬‭matrix are input row by‬‭row.‬
‭2.‬ ‭Diagonal Calculations‬‭:‬
‭○‬ ‭Left Diagonal‬‭: The elements where the row index equals‬‭the column index‬
‭(‭
m
‬ atrix[i][i]‬ ‭).‬
‭○‬ R ‭ ight Diagonal‬‭: The elements where the row index and column index sum to‬
n-1‬‭(‭
‭ m
‬ atrix[i][n-i-1]‬ ‭).‬
‭3.‬ ‭Output‬‭:‬
‭○‬ ‭The program prints the sums of the left and right diagonals.‬

‭Example Input/Output:‬

‭Input:‬
‭ nter the size of the square matrix: 3‬
E
‭Enter the elements of the 3x3 matrix:‬
‭1 2 3‬
‭4 5 6‬
‭7 8 9‬

‭ utput‬‭:‬
O
‭Sum of left diagonal: 15‬
‭Sum of right diagonal: 15‬

‭This program handles square matrices and calculates the diagonal sums efficiently.‬

‭ 7. Write a program to find the transpose of a square matrix of 3x3 order. [BCA 2019]‬
2
‭Here’s a C program to find the transpose of a 3x3 square matrix:‬

‭#include <stdio.h>‬

‭int main() {‬
‭int matrix[3][3], transpose[3][3];‬

/‭/ Input the 3x3 matrix‬


‭printf("Enter the elements of the 3x3 matrix:\n");‬
‭for (int i = 0; i < 3; i++) {‬
‭for (int j = 0; j < 3; j++) {‬
‭scanf("%d", &matrix[i][j]);‬
‭}‬
‭}‬

/‭/ Calculate the transpose of the matrix‬


‭for (int i = 0; i < 3; i++) {‬
‭for (int j = 0; j < 3; j++) {‬
‭transpose[j][i] = matrix[i][j];‬
‭}‬
‭}‬

‭// Output the original matrix‬


‭ rintf("\nOriginal Matrix:\n");‬
p
‭for (int i = 0; i < 3; i++) {‬
‭for (int j = 0; j < 3; j++) {‬
‭printf("%d ", matrix[i][j]);‬
‭}‬
‭printf("\n");‬
‭}‬

/‭/ Output the transposed matrix‬


‭printf("\nTranspose of the Matrix:\n");‬
‭for (int i = 0; i < 3; i++) {‬
‭for (int j = 0; j < 3; j++) {‬
‭printf("%d ", transpose[i][j]);‬
‭}‬
‭printf("\n");‬
‭}‬

‭return 0;‬
‭}‬

‭Explanation:‬

‭1.‬ ‭Matrix Input‬‭:‬


‭○‬ ‭The user enters the elements of a 3x3 matrix, row by row.‬
‭2.‬ ‭Transpose Calculation‬‭:‬
‭○‬ ‭The transpose of a matrix is obtained by swapping rows and columns. For each‬
matrix[i][j]‬
‭element‬‭ ‭, the transposed element is stored‬‭as‬
‭ranspose[j][i]‬
t ‭.‬
‭3.‬ ‭Display Results‬‭:‬
‭○‬ ‭The original matrix is printed first, followed by the transposed matrix.‬

‭Example Input/Output:‬

‭Input:‬
‭ nter the elements of the 3x3 matrix:‬
E
‭1 2 3‬
‭4 5 6‬
‭7 8 9‬

‭ utput‬‭:‬
O
‭Original Matrix:‬
‭1 2 3‬
‭4 5 6‬
‭7 8 9‬
‭ ranspose of the Matrix:‬
T
‭1 4 7‬
‭2 5 8‬
‭3 6 9‬

‭This program efficiently computes and displays the transpose of a 3x3 matrix.‬

‭28. What is a string? Explain all types of string functions with examples.[BCA 2016,2017,2018]‬
‭What is a String in C?‬

I‭n C, a‬‭string‬‭is a sequence of characters terminated‬‭with a null character (‬‭


\0‬‭). Strings are‬
‭typically stored as arrays of characters. For example:‬

‭char str[] = "Hello";‬

str‬‭contains the characters‬‭


‭Here, the string‬‭ 'H'‬ 'e'‬
‭,‬‭ 'l'‬
‭,‬‭ 'l'‬
‭,‬‭ 'o'‬
‭,‬‭ ‭, and the null character‬
\0‬‭automatically added by the compiler.‬

‭Types of String Functions in C‬

<string.h>‬‭library. Below are some‬


‭ provides various functions to manipulate strings in the‬‭
C
‭commonly used string functions with examples:‬

strlen()‬‭- String Length‬


‭1.‬‭

‭‬ P
● ‭ urpose‬‭: Returns the length of a string (excluding‬‭the null character).‬
size_t strlen(const char *str);‬
‭●‬ ‭Syntax‬‭:‬‭
‭●‬ ‭Example‬:‭‬

‭ include <stdio.h>‬
#
‭#include <string.h>‬

‭int main() {‬
‭char str[] = "Hello";‬
‭printf("Length of string: %lu\n", strlen(str));‬
‭return 0;‬
‭}‬
‭Output‬‭:‬‭Length of string:‬‭ 5‬

strcpy()‬‭- String Copy‬


‭2.‬‭
‭‬ P
● ‭ urpose‬‭: Copies one string to another.‬
char *strcpy(char *dest, const char *src);‬
‭●‬ ‭Syntax‬‭:‬‭
‭●‬ ‭Example‬:‭‬

‭ include <stdio.h>‬
#
‭#include <string.h>‬

‭int main() {‬
‭char src[] = "World";‬
‭char dest[10];‬
‭strcpy(dest, src);‬
‭printf("Copied string: %s\n", dest);‬
‭return 0;‬
‭}‬
‭Output‬‭:‬‭ Copied string:‬‭ World‬

strcat()‬‭- String Concatenation‬


‭3.‬‭

‭‬ P
● ‭ urpose‬‭: Appends one string to another.‬
char *strcat(char *dest, const char *src);‬
‭●‬ ‭Syntax‬‭:‬‭
‭●‬ ‭Example‬:‭‬

‭ include <stdio.h>‬
#
‭#include <string.h>‬

‭int main() {‬
‭char str1[20] = "Hello, ";‬
‭char str2[] = "World!";‬
‭strcat(str1, str2);‬
‭printf("Concatenated string: %s\n", str1);‬
‭return 0;‬
‭}‬

Concatenated string: Hello, World!‬


‭Output‬‭:‬‭

strcmp()‬‭- String Comparison‬


‭4.‬‭

‭‬ P
● ‭ urpose‬‭: Compares two strings lexicographically.‬
int strcmp(const char *str1, const char *str2);‬
‭●‬ ‭Syntax‬‭:‬‭
‭●‬ ‭Example‬:‭‬
‭ include <stdio.h>‬
#
‭#include <string.h>‬

‭int main() {‬
‭char str1[] = "Hello";‬
‭char str2[] = "World";‬
‭if (strcmp(str1, str2) == 0)‬
‭printf("Strings are equal.\n");‬
‭else‬
‭printf("Strings are not equal.\n");‬
‭return 0;‬
‭}‬
‭Output‬‭:‬‭ Strings are‬‭ not equal.‬

strchr()‬‭- Find Character in String‬


‭5.‬‭

‭‬ P
● ‭ urpose‬‭: Finds the first occurrence of a character‬‭in a string.‬
char *strchr(const char *str, int c);‬
‭●‬ ‭Syntax‬‭:‬‭
‭●‬ ‭Example‬:‭‬

‭ include <stdio.h>‬
#
‭#include <string.h>‬

‭int main() {‬
‭char str[] = "Hello";‬
‭char *ptr = strchr(str, 'e');‬
‭if (ptr)‬
‭printf("Character found at position: %ld\n", ptr - str);‬
‭else‬
‭printf("Character not found.\n");‬
‭return 0;‬
‭}‬

Character found at position: 1‬


‭Output‬‭:‬‭

strstr()‬‭- Find Substring‬


‭6.‬‭

‭‬ P
● ‭ urpose‬‭: Finds the first occurrence of a substring in a string.‬
char *strstr(const char *haystack, const char‬‭
‭●‬ ‭Syntax‬‭:‬‭ *needle);‬
‭●‬ ‭Example‬:‭‬

‭ include <stdio.h>‬
#
‭#include <string.h>‬
‭int main() {‬
‭char str[] = "Hello, World!";‬
‭char *ptr = strstr(str, "World");‬
‭if (ptr)‬
‭printf("Substring found: %s\n", ptr);‬
‭else‬
‭printf("Substring not found.\n");‬
‭return 0;‬
‭}‬
‭Output‬‭:‬‭ Substring found: World!‬

strrev()‬‭- Reverse String (Non-Standard)‬


‭7.‬‭

‭‬ P
● <string.h>‬‭in standard C.)‬
‭ urpose‬‭: Reverses a string.‬‭(Note: Not part of‬‭
‭●‬ ‭Example‬‭:‬

‭ include <stdio.h>‬
#
‭#include <string.h>‬

‭void reverse(char *str) {‬


‭int len = strlen(str);‬
‭for (int i = 0; i < len / 2; i++) {‬
‭char temp = str[i];‬
‭str[i] = str[len - i - 1];‬
‭str[len - i - 1] = temp;‬
‭}‬
‭}‬

‭int main() {‬
‭char str[] = "Hello";‬
‭reverse(str);‬
‭printf("Reversed string: %s\n", str);‬
‭return 0;‬
‭}‬
‭Output‬‭:‬‭ Reversed string: olleH‬

‭Summary Table‬
‭Function‬ ‭Purpose‬ ‭Example Usage‬

strlen(‬ ‭Finds the length of a string.‬


‭ strlen(str)‬

)‬

strcpy(‬ ‭Copies one string to another.‬
‭ strcpy(dest, src)‬

)‬

strcat(‬ ‭Concatenates two strings.‬


‭ strcat(dest, src)‬

)‬

strcmp(‬ ‭Compares two strings.‬


‭ strcmp(str1, str2)‬

)‬

strchr(‬ ‭Finds a character in a string.‬


‭ strchr(str, 'a')‬

)‬

strstr(‬ ‭Finds a substring in a string.‬


‭ strstr(str, "hello")‬

)‬

strrev(‬ R
‭ ‭ everses a string‬ ‭Custom implementation required.‬
)‬
‭ ‭(non-standard).‬

‭These string functions are widely used in C for string manipulation tasks.‬

‭ 9. Write a program to check whether a string is Palindrome. [BCA 2018]‬


2
‭#include <stdio.h>‬
‭#include <string.h>‬

‭int main() {‬
‭char str[100];‬
‭int length, isPalindrome = 1;‬

/‭/ Input string from the user‬


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

/‭/ Find the length of the string‬


‭length = strlen(str);‬

/‭/ Check if the string is a palindrome‬


‭for (int i = 0; i < length / 2; i++) {‬
‭if (str[i] != str[length - i - 1]) {‬
‭isPalindrome = 0; // Not a palindrome‬
‭break;‬
‭}‬
‭}‬

‭// Output the result‬


‭if (isPalindrome)‬
‭printf("The string \"%s\" is a Palindrome.\n", str);‬
‭else‬
‭printf("The string \"%s\" is not a Palindrome.\n", str);‬

‭return 0;‬
‭}‬

‭Explanation:‬

‭1.‬ ‭Input‬‭:‬
‭○‬ ‭The program takes a string as input from the user.‬
str‬‭array.‬
‭○‬ ‭The input string is stored in the‬‭
‭2.‬ ‭Palindrome Check‬‭:‬
for‬‭loop, it compares characters from the‬‭beginning (‬‭
‭○‬ ‭Using a‬‭ str[i]‬
‭) with‬
‭corresponding characters from the end (‬‭
str[length‬‭
- i - 1]‬
‭).‬
‭○‬ I‭f any pair of characters do not match, the‬‭ isPalindrome‬‭flag is set to 0,‬
‭indicating the string is not a palindrome.‬
‭3.‬ ‭Output‬‭:‬
‭○‬ ‭If all characters match, the string is a palindrome.‬
‭○‬ ‭Otherwise, it is not.‬

‭Example Input/Output:‬

‭Input 1:‬
‭Enter a string: radar‬

‭ utput 1‬‭:‬
O
‭The string "radar" is a Palindrome.‬

I‭nput 2‬‭:‬
‭Enter a string: hello‬

‭ utput 2‬‭:‬
O
‭The string "hello" is not a Palindrome.‬

‭ 0. Write a program to check vowels, Consonants and white spaces in a given text/string. [BCA‬
3
‭2016,2017]‬
‭Here’s a C program to count the number of vowels, consonants, and white spaces in a given‬
‭text/string:‬
‭#include <stdio.h>‬
‭#include <ctype.h>‬
‭int main() {‬
‭char str[200];‬
‭int vowels = 0, consonants = 0, whiteSpaces = 0;‬

/‭/ Input the string‬


‭printf("Enter a string: ");‬
‭fgets(str, sizeof(str), stdin);‬

/‭/ Iterate through the string‬


‭for (int i = 0; str[i] != '\0'; i++) {‬
‭char ch = tolower(str[i]); // Convert character to lowercase for uniformity‬

‭if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {‬


‭vowels++;‬
‭} else if ((ch >= 'a' && ch <= 'z')) {‬
‭consonants++;‬
‭} else if (ch == ' ') {‬
‭whiteSpaces++;‬
‭}‬
‭}‬

/‭/ Output the counts‬


‭printf("Vowels: %d\n", vowels);‬
‭printf("Consonants: %d\n", consonants);‬
‭printf("White Spaces: %d\n", whiteSpaces);‬

‭return 0;‬
‭}‬

‭Explanation:‬

‭1.‬ ‭Input‬‭:‬
‭○‬ ‭The program uses‬‭ fgets()‬‭to read a string from the‬‭user, allowing spaces to be‬
‭included.‬
‭2.‬ ‭Processing‬‭:‬
for‬‭loop.‬
‭○‬ ‭Each character in the string is processed using a‬‭
‭‬ C
○ ‭ haracters are converted to lowercase using‬‭ tolower()‬‭for easy comparison.‬
‭○‬ ‭Conditions‬‭:‬
‭■‬ ‭If the character is a vowel (‬‭a, e, i, o, u‬ vowels‬‭counter is‬
‭), the‬‭
‭incremented.‬
‭■‬ ‭If the character is an alphabet (checked using ASCII values) but not a‬
‭vowel, it is counted as a consonant.‬
‭■‬ I‭f the character is a space (‬‭
' '‬ whiteSpaces‬‭counter is‬
‭), the‬‭
‭incremented.‬
‭3.‬ ‭Output‬‭:‬
‭○‬ ‭The program displays the counts of vowels, consonants, and white spaces.‬

‭31. Explain various functions used for reading and writing strings.‬
‭Functions for Reading and Writing Strings in C‬

‭ provides several functions for reading and writing strings. Here’s a summary of the commonly‬
C
‭used functions:‬

scanf()‬
‭1.‬‭

‭‬ P
● ‭ urpose‬‭: Reads a string input from the user.‬
‭●‬ ‭Syntax‬‭:‬‭ scanf("%s", str);‬
‭●‬ ‭Key Points‬‭:‬
‭○‬ ‭It stops reading at the first whitespace character.‬
‭○‬ ‭Does not allow spaces in input.‬
‭●‬ ‭Example‬‭:‬

‭#include <stdio.h>‬

‭int main() {‬
‭char str[50];‬
‭printf("Enter a string: ");‬
‭scanf("%s", str);‬
‭printf("You entered: %s\n", str);‬
‭return 0;‬
‭}‬

gets()‬‭(Deprecated in C99 and Removed in C11)‬


‭2.‬‭

‭‬ P
● ‭ urpose‬‭: Reads a line of text, including spaces.‬
‭●‬ ‭Syntax‬‭:‬‭ gets(str);‬
‭●‬ ‭Key Points‬‭:‬
‭○‬ ‭Vulnerable to buffer overflow, so its usage is discouraged.‬
‭●‬ ‭Example‬‭:‬

‭#include <stdio.h>‬

‭int main() {‬
‭char str[50];‬
‭ rintf("Enter a string: ");‬
p
‭gets(str); // Unsafe function‬
‭printf("You entered: %s\n", str);‬
‭return 0;‬
‭}‬

fgets()‬
‭3.‬‭

‭●‬ P ‭ urpose‬‭: Reads a string input from the user, including‬‭spaces, with buffer overflow‬
‭protection.‬
‭●‬ ‭Syntax‬‭:‬‭ fgets(str, size, stdin);‬
‭●‬ ‭Key Points‬‭:‬
‭○‬ ‭Stops reading after a newline (‬‭
\n‬‭) or when the buffer‬‭is full.‬
‭○‬ ‭Adds a newline character at the end of the string if not fully consumed.‬
‭●‬ ‭Example‬‭:‬

‭#include <stdio.h>‬

‭int main() {‬
‭char str[50];‬
‭printf("Enter a string: ");‬
‭fgets(str, sizeof(str), stdin);‬
‭printf("You entered: %s", str);‬
‭return 0;‬
‭}‬

printf()‬
‭4.‬‭

‭‬ P
● ‭ urpose‬‭: Prints a string to the console.‬
‭●‬ ‭Syntax‬‭:‬‭ printf("%s", str);‬
‭●‬ ‭Key Points‬‭:‬
‭○‬ ‭Prints the entire string until the null character (‬‭
\0‬
‭).‬
‭●‬ ‭Example‬‭:‬

‭#include <stdio.h>‬

‭int main() {‬
‭char str[] = "Hello, World!";‬
‭printf("String: %s\n", str);‬
‭return 0;‬
‭}‬
puts()‬
‭5.‬‭

‭●‬ ‭Purpose‬‭: Writes a string to the console and adds a‬‭newline (‬‭
\n‬
‭) at the end.‬
‭‬ S
● puts(str);‬
‭ yntax‬‭:‬‭
‭●‬ ‭Key Points‬‭:‬
printf()‬‭for strings.‬
‭○‬ ‭Safer and simpler alternative to‬‭
‭●‬ ‭Example‬‭:‬

‭#include <stdio.h>‬

‭int main() {‬
‭char str[] = "Hello, World!";‬
‭puts(str); // Automatically adds a newline‬
‭return 0;‬
‭}‬

fputs()‬
‭6.‬‭

‭‬ P
● ‭ urpose‬‭: Writes a string to a file or standard output‬‭without adding a newline.‬
‭●‬ ‭Syntax‬‭:‬‭ fputs(str, stream);‬
‭●‬ ‭Key Points‬‭:‬
‭○‬ ‭Does not append a newline like‬‭ puts()‬ ‭.‬
‭●‬ ‭Example‬‭:‬

‭#include <stdio.h>‬

‭int main() {‬
‭char str[] = "Hello, World!";‬
‭fputs(str, stdout); // Output to the console‬
‭return 0;‬
‭}‬

‭Comparison of String Functions‬


‭Function‬ ‭Purpose‬ ‭Allows‬ ‭Adds‬ ‭Safety‬
‭ paces‬
S ‭Newline‬

scanf()‬ R
‭ ‭ eads a single‬ ‭No‬ ‭No‬ ‭Moderate‬
‭word‬

gets()‬
‭ ‭Reads a line‬ ‭Yes‬ ‭No‬ ‭Unsafe‬
fgets()‬ ‭Reads a line‬
‭ ‭Yes‬ ‭No‬ ‭Safe‬

printf(‬ ‭Prints a string‬


‭ ‭N/A‬ ‭No‬ ‭Safe‬
)‬

puts()‬
‭ ‭Prints a string‬ ‭N/A‬ ‭Yes‬ ‭Safe‬

fputs()‬ ‭Writes a string‬


‭ ‭N/A‬ ‭No‬ ‭Safe‬

‭Key Notes:‬

fgets()‬‭for reading strings safely, especially‬‭when spaces are involved.‬


‭●‬ ‭Prefer‬‭
‭●‬ U puts()‬‭or‬‭
‭ se‬‭ printf()‬‭for output, depending on whether‬‭you want a newline to be‬
‭added automatically.‬

‭ 2. Write a program to find the length of a string.[BCA 2019]‬


3
‭#include <stdio.h>‬

‭int main() {‬
‭char str[100];‬
‭int length = 0;‬

/‭/ Input string from user‬


‭printf("Enter a string: ");‬
‭fgets(str, sizeof(str), stdin);‬

/‭/ Calculate string length manually‬


‭for (int i = 0; str[i] != '\0'; i++) {‬
‭if (str[i] != '\n') { // Exclude the newline character if present‬
‭length++;‬
‭}‬
‭}‬

/‭/ Print the length of the string‬


‭printf("The length of the string is: %d\n", length);‬

‭return 0;‬
‭}‬

‭Explanation:‬
‭1.‬ ‭Input‬‭:‬
‭○‬ ‭The program uses‬‭ fgets()‬‭to read a string from the‬‭user, allowing spaces and‬
‭limiting the input to the buffer size.‬
‭2.‬ ‭Processing‬‭:‬
‭○‬ ‭The‬‭ for‬‭loop iterates through each character of the‬‭string.‬
‭○‬ ‭It checks for the null terminator (‬‭
\0‬
‭) to determine‬‭the end of the string.‬
‭ ‬ ‭A condition ensures the newline character (‬‭
○ \n‬
‭) is‬‭not counted in the string length.‬
‭3.‬ ‭Output‬‭:‬
‭○‬ ‭The total number of valid characters is printed as the length of the string.‬

‭Example Input/Output:‬

‭Input:‬
‭Enter a string: Hello, World!‬

‭ utput‬‭:‬
O
‭The length of the string is: 13‬

‭ his program calculates the length of a string manually without using library functions like‬
T
strlen()‬
‭ ‭.‬

‭33. Write a program to compare two strings.‬

‭ include <stdio.h>‬
#
‭#include <string.h>‬

‭int main() {‬
‭char str1[100], str2[100];‬
‭int result;‬

/‭/ Input two strings from the user‬


‭printf("Enter the first string: ");‬
‭fgets(str1, sizeof(str1), stdin);‬

‭ rintf("Enter the second string: ");‬


p
‭fgets(str2, sizeof(str2), stdin);‬

/‭/ Remove newline characters (if any) from strings‬


‭str1[strcspn(str1, "\n")] = '\0';‬
‭str2[strcspn(str2, "\n")] = '\0';‬

/‭/ Compare the two strings‬


‭result = strcmp(str1, str2);‬
/‭/ Print the comparison result‬
‭if (result == 0) {‬
‭printf("The strings are equal.\n");‬
‭} else if (result < 0) {‬
‭printf("The first string is less than the second string.\n");‬
‭} else {‬
‭printf("The first string is greater than the second string.\n");‬
‭}‬

‭return 0;‬
‭}‬

‭Explanation:‬

‭1.‬ ‭Input‬‭:‬
fgets()‬‭to input two strings, allowing‬‭spaces in the input.‬
‭○‬ ‭The program uses‬‭
strcspn()‬‭function is used to remove the newline‬‭character (‬‭
‭○‬ ‭The‬‭ \n‬
‭) added by‬
‭gets()‬
f ‭.‬
‭2.‬ ‭String Comparison‬‭:‬
‭○‬ ‭The‬‭ strcmp()‬‭function is used to compare the two strings.‬
‭○‬ ‭Return Values‬‭:‬
‭■‬ ‭
0‭:‬Strings are equal.‬
‭■‬ ‭
< 0‬
‭: The first string is lexicographically smaller‬‭than the second.‬
‭■‬ ‭
> 0‬
‭: The first string is lexicographically greater‬‭than the second.‬
‭3.‬ ‭Output‬‭:‬
‭○‬ ‭The result of the comparison is displayed as a message indicating equality or‬
‭lexicographical order.‬

‭Example Input/Output:‬

‭Input 1:‬
‭ nter the first string: apple‬
E
‭Enter the second string: banana‬

‭ utput 1‬‭:‬
O
‭The first string is less than the second string.‬

I‭nput 2‬‭:‬
‭Enter the first string: hello‬
‭Enter the second string: hello‬
‭ utput 2‬‭:‬
O
‭The strings are equal.‬

strcmp()‬‭and‬‭handles edge cases such‬


‭ his program effectively compares two strings using‬‭
T
‭as trailing newline characters.‬

‭ 4. What is function? Explain the difference between user-defined and library (built-in) functions.‬
3
‭[BCA 2018, BCA MJ-1 2022]‬
‭What is a Function in C?‬

‭ function is a block of code that performs a specific task and can be reused multiple times.‬
A
‭Functions are used to break down large programs into smaller, manageable sections, promoting‬
‭modularity and code reuse.‬

‭Types of Functions in C‬

‭ .‬ L
1 ‭ ibrary (Built-in) Functions‬‭: Predefined functions‬‭provided by C libraries.‬
‭2.‬ ‭User-defined Functions‬‭: Functions created by the programmer.‬

‭Difference Between User-defined and Library Functions‬


‭Feature‬ ‭Library (Built-in) Functions‬ ‭User-defined Functions‬

‭Definition‬ ‭ redefined functions in C‬


P ‭Defined by the programmer.‬
‭libraries.‬

‭Location‬ ‭ ound in header files (e.g.,‬


F ‭Located in the source code.‬
stdio.h‬
‭ ‭).‬

‭Examples‬ printf()‬
‭ scanf()‬
‭,‬‭ ‭,‬ add()‬
‭Functions like‬‭ factorial()‬
‭,‬‭ ‭.‬
strlen()‬
‭ ‭.‬

‭ ode‬
C ‭Directly available for use.‬ ‭Reused only after being defined.‬
‭Reusability‬

‭Complexity‬ ‭Simple and ready to use.‬ ‭Requires logic, design, and definition.‬

‭Performance‬ ‭Optimized for efficiency.‬ ‭ erformance depends on‬


P
‭implementation.‬

‭Usage‬ ‭Used for common operations.‬ ‭ sed for specific, custom‬


U
‭requirements.‬

‭Portability‬ ‭Standardized across systems.‬ ‭Must be rewritten in other projects.‬


‭Example of a Library Function‬

‭ include <stdio.h>‬
#
‭#include <string.h>‬

‭int main() {‬
‭char str[] = "Hello";‬
‭printf("Length of string: %lu\n", strlen(str)); // Library function‬
‭return 0;‬
‭}‬

‭Example of a User-defined Function‬

‭#include <stdio.h>‬

/‭/ User-defined function to calculate the sum of two numbers‬


‭int add(int a, int b) {‬
‭return a + b;‬
‭}‬

‭int main() {‬
‭int result = add(10, 20);‬
‭printf("Sum: %d\n", result);‬
‭return 0;‬
‭}‬

‭Key Points‬

‭‬ L
● ‭ ibrary functions save time and effort for common operations.‬
‭●‬ ‭User-defined functions provide flexibility to meet custom requirements.‬

‭ 5. What is function? Explain at least two categories of function with examples. [BCA 2019]‬
3
‭Refer Question#34‬

‭ 6. What is a recursion/recursive function [BCA 2019, BCA MJ-1 2022]? Write a program to find‬
3
‭the factorial of a number using function recursion. [BCA 2016,2018]‬

‭What is Recursion?‬

‭ ecursion is a programming technique in which a function calls itself to solve a problem. The‬
R
‭function continues to call itself until a base case is reached, at which point the recursion stops,‬
‭and the results are combined or returned.‬
‭ ‬‭recursive function‬‭is a function that calls itself to perform a task. It generally consists of two‬
A
‭main components:‬

‭ .‬ B
1 ‭ ase Case‬‭: The condition that stops the recursion.‬
‭2.‬ ‭Recursive Case‬‭: The part where the function calls‬‭itself with a modified argument.‬

‭Example Program to Find the Factorial of a Number Using Recursion in C:‬

n‬‭is the product of all‬‭positive integers less than or equal to‬‭


‭The factorial of a number‬‭ n‬
‭:‬

‭●‬ ‭
n! = n * (n - 1) * (n - 2) * ... * 1‬
0! = 1‬
‭●‬ ‭Base case:‬‭

‭C Program:‬
‭#include <stdio.h>‬

/‭/ Recursive function to find the factorial of a number‬


‭int factorial(int n) {‬
‭if (n == 0 || n == 1) {‬
‭return 1; // Base case‬
‭} else {‬
‭return n * factorial(n - 1); // Recursive call‬
‭}‬
‭}‬

‭int main() {‬
‭int number, result;‬

/‭/ Input from the user‬


‭printf("Enter a number: ");‬
‭scanf("%d", &number);‬

/‭/ Check if the number is non-negative‬


‭if (number < 0) {‬
‭printf("Factorial is not defined for negative numbers.\n");‬
‭} else {‬
‭// Call the recursive function‬
‭result = factorial(number);‬
‭printf("Factorial of %d is: %d\n", number, result);‬
‭}‬

‭return 0;‬
‭}‬
‭Explanation:‬

‭1.‬ ‭Recursive Function‬‭:‬


factorial()‬‭is defined to compute the‬‭factorial of‬‭
‭○‬ ‭The function‬‭ n‬
‭.‬
n == 0‬‭or‬‭
‭○‬ ‭Base Case‬‭: If‬‭ n == 1‬ 1‬
‭, return‬‭ 0!‬‭and‬‭
‭, as‬‭ 1!‬‭are both defined as‬‭
1‬
‭.‬
‭○‬ R ‭ ecursive Case‬‭: If‬‭n > 1‬ n - 1‬‭and multiplies‬‭
‭, the function calls itself‬‭with‬‭ n‬
‭with the result of the recursive call.‬
‭2.‬ ‭Main Function‬‭:‬
‭○‬ ‭The program reads an integer from the user and checks if it's non-negative.‬
‭○‬ ‭It then calls the recursive function‬‭ factorial()‬‭to compute and print the‬
‭factorial.‬

‭Example Input/Output:‬

‭Input:‬
‭Enter a number: 5‬

‭ utput‬‭:‬
O
‭Factorial of 5 is: 120‬

‭ 7. Explain /Differentiate call by value and call reference with an example. [BCA‬
3
‭2016,2018,2019, MJ-1 2022]‬

‭Call by Value vs. Call by Reference in C‬

I‭n C, when a function is called, the arguments passed to the function can be handled in two‬
‭different ways:‬‭Call by Value‬‭and‬‭Call by Reference‬‭.‬

‭1. Call by Value:‬

‭●‬ I‭n‬‭Call by Value‬‭, a copy of the actual argument's‬‭value is passed to the function. The‬
‭function works on this copy, and any changes made to the parameter inside the function‬
‭do not affect the actual argument.‬
‭●‬ ‭Modifications‬‭made to the parameter inside the function‬‭do not affect‬‭the original‬
‭variable outside the function.‬

‭Example of Call by Value:‬


‭#include <stdio.h>‬

/‭/ Function to modify the value (Call by Value)‬


‭void modifyValue(int x) {‬
‭x = 10; // Changing the value of x‬
‭printf("Inside modifyValue: %d\n", x); // 10‬
‭}‬

‭int main() {‬
‭int num = 5;‬
‭printf("Before modifyValue: %d\n", num); // 5‬
‭modifyValue(num); // Call by Value‬
‭printf("After modifyValue: %d\n", num); // 5 (unchanged)‬
‭return 0;‬
‭}‬

‭Explanation:‬

num‬‭is passed to the‬‭


‭●‬ ‭The variable‬‭ modifyValue()‬‭function.‬‭However, only a copy of‬
num‬‭is passed.‬

x‬‭is modified, but it does not‬‭affect‬‭
‭●‬ ‭Inside the function,‬‭ num‬‭in the‬‭
main()‬‭function.‬
num‬‭in the main‬‭function remains unchanged.‬
‭●‬ ‭The output shows that the value of‬‭

‭Output:‬
‭ efore modifyValue: 5‬
B
‭Inside modifyValue: 10‬
‭After modifyValue: 5‬

‭2. Call by Reference:‬

‭●‬ I‭n‬‭Call by Reference‬‭, instead of passing a copy of‬‭the variable, the‬‭memory address‬
‭(reference) of the actual argument is passed to the function. This means the function‬
‭works directly with the original variable.‬
‭●‬ ‭Modifications‬‭made to the parameter inside the function‬‭affect the actual variable‬
‭outside the function.‬

‭Example of Call by Reference:‬


‭#include <stdio.h>‬

/‭/ Function to modify the value (Call by Reference)‬


‭void modifyValue(int *x) {‬
‭*x = 10; // Dereferencing to change the value at the address‬
‭printf("Inside modifyValue: %d\n", *x); // 10‬
‭}‬

‭int main() {‬
‭int num = 5;‬
‭ rintf("Before modifyValue: %d\n", num); // 5‬
p
‭modifyValue(&num); // Call by Reference (passing address of num)‬
‭printf("After modifyValue: %d\n", num); // 10 (modified)‬
‭return 0;‬
‭}‬

‭Explanation:‬

main()‬‭function, the address of‬‭


‭●‬ ‭In the‬‭ num‬‭is passed‬‭to the‬‭
modifyValue()‬‭function‬
‭using the address-of operator (‬‭
&‭)‬.‬
‭●‬ I‭nside the function, the pointer‬‭ x‬‭accesses the memory‬‭location of‬‭num‬‭and modifies its‬
‭value directly.‬
‭●‬ ‭The change to‬‭ num‬‭is reflected outside the function‬‭because the function works on the‬
‭actual variable.‬

‭Output:‬
‭ efore modifyValue: 5‬
B
‭Inside modifyValue: 10‬
‭After modifyValue: 10‬

‭Key Differences:‬
‭Feature‬ ‭Call by Value‬ ‭Call by Reference‬

‭ assing‬
P ‭ copy of the argument's value‬
A ‭ he address (reference) of the argument‬
T
‭Mechanism‬ ‭is passed.‬ ‭is passed.‬

‭ ffect on‬
E ‭ odifications inside the function‬ M
M ‭ odifications inside the function affect the‬
‭Original‬ ‭do not affect the original‬ ‭original variable.‬
‭variable.‬

‭ emory‬
M ‭ ses more memory (copies of‬
U ‭ ses less memory (only the address is‬
U
‭Usage‬ ‭variables are created).‬ ‭passed).‬

‭Use Cases‬ ‭ sed when the function does‬


U ‭ sed when the function needs to modify‬
U
‭not need to modify the original‬ ‭the original argument or when large data‬
‭argument.‬ ‭structures are passed.‬

‭Example‬ ‭odifyValue(x)‬‭(where‬‭
m x‬‭is‬ ‭odifyValue(&x)‬‭(where‬‭
m x‬‭is passed‬
‭passed by value)‬ ‭by reference)‬
‭Summary:‬

‭‬ C
● ‭ all by Value‬‭is safer because it prevents modification of the original data.‬
‭●‬ ‭Call by Reference‬‭is more efficient when working with‬‭large data structures or when you‬
‭need to modify the original variable in the calling function.‬

‭38. Explain the Scope, Visibility and Lifetime of a variable.[BCA 2019]‬

‭Scope, Visibility, and Lifetime of a Variable in C Language‬

I‭n C programming, variables have characteristics that define where they can be accessed, how‬
‭long they exist, and when they are valid. These characteristics are known as‬‭scope‬‭,‬‭visibility‬‭,‬
‭and‬‭lifetime‬‭of a variable. Let's discuss each one:‬

‭1. Scope of a Variable:‬

‭ he‬‭scope‬‭of a variable refers to the‬‭region of the‬‭program‬‭where the variable is accessible or‬


T
‭valid. It determines the part of the program in which the variable can be used.‬

‭●‬ L
‭ ocal Scope‬‭: A variable declared inside a function‬‭or block (enclosed by‬‭ {}‬‭) is‬‭locally‬
‭scoped‬‭. It can only be accessed within that function‬‭or block and is not visible to other‬
‭functions or blocks.‬

‭void function() {‬
‭int x = 5; // x has local scope to this function‬
‭printf("%d", x); // x can be accessed here‬
‭}‬

‭●‬ G
‭ lobal Scope‬‭: A variable declared outside all functions (at the top of the program,‬
main()‬
‭before‬‭ ‭) is‬‭globally scoped‬‭. It can be accessed from any function in the‬
‭program.‬

‭int x = 10; // x has global scope‬

‭void function() {‬
‭printf("%d", x); // x can be accessed here‬
‭}‬

‭int main() {‬
‭function(); // x is also accessible here‬
‭return 0;‬
‭}‬
‭●‬ B
‭ lock Scope‬‭: A variable declared inside a‬‭block‬‭(e.g., loops, if statements) has‬‭block‬
‭scope‬‭and is accessible only within that block.‬
‭if (1) {‬
‭int y = 20; // y has block scope‬
‭printf("%d", y); // y can be accessed here‬
‭}‬
‭// y is not accessible outside the block‬

‭2. Visibility of a Variable:‬

‭ he‬‭visibility‬‭of a variable is related to where the‬‭variable can be referenced in the program. A‬


T
‭variable is‬‭visible‬‭in the part of the program where‬‭its scope is valid.‬

‭●‬ L ‭ ocal Variables‬‭: Only visible inside the function‬‭or block where they are declared. They‬
‭cannot be accessed by other functions or blocks.‬
‭●‬ ‭Global Variables‬‭: Visible throughout the program after‬‭their declaration. Any function‬
‭can access a global variable after its declaration (unless shadowed by a local variable‬
‭with the same name).‬
‭●‬ ‭Extern Variables‬‭: A variable declared with the‬‭ extern‬‭keyword allows visibility across‬
‭different files in a multi-file program. It tells the compiler that the variable is defined‬
‭elsewhere (outside the current file).‬

‭Example of‬‭extern‬‭:‬

/‭/ file1.c‬
‭#include <stdio.h>‬

‭extern int x; // Declare the global variable x‬

‭int main() {‬
‭printf("%d", x); // x can be accessed here‬
‭return 0;‬
‭}‬

/‭/ file2.c‬
‭int x = 10; // Define the global variable x‬

‭3. Lifetime of a Variable:‬

‭ he‬‭lifetime‬‭of a variable refers to how long the‬‭variable‬‭exists‬‭in memory during the execution‬
T
‭of a program. The lifetime of a variable is determined by where and how it is declared.‬

‭●‬ ‭Automatic Variables‬‭(local variables):‬


‭○‬ L ‭ ifetime‬‭: They are created when the function or block in which they are declared‬
‭is called, and destroyed when the function or block exits.‬
‭○‬ ‭Example: A local variable inside a function exists only while that function is‬
‭executing.‬
‭○‬ ‭Default Storage Class‬‭:‬‭ auto‬‭(implicitly applied to‬‭local variables).‬
‭ ‬ ‭Static Variables‬‭:‬

‭○‬ ‭Lifetime‬‭: They exist throughout the program's execution.‬‭Even though they are‬
‭declared inside functions, they retain their values between function calls.‬
‭○‬ ‭Visibility‬‭: Static variables can be either local or‬‭global, but they are‬‭not visible‬
‭outside the scope‬‭of their declaration.‬

‭void function() {‬
‭static int count = 0; // Static variable‬
‭count++;‬
‭printf("%d\n", count);‬
‭}‬

‭int main() {‬
‭function(); // Outputs 1‬
‭function(); // Outputs 2‬
‭function(); // Outputs 3‬
‭return 0;‬
‭}‬
‭●‬ ‭Global Variables‬‭:‬
‭●‬ ‭Lifetime‬‭: They exist for the entire duration of the program. A global variable is‬
‭created when the program starts and is destroyed when the program terminates.‬
‭●‬ ‭Visibility‬‭: Global variables are visible throughout the program after their‬
‭declaration.‬
‭ ‬ ‭Dynamic Variables‬‭(using‬‭
● malloc‬ calloc‬
‭,‬‭ realloc‬
‭,‬‭ ‭):‬
‭●‬ L free()‬
‭ ifetime‬‭: They exist until explicitly freed using‬‭ ‭. The lifetime of‬
‭dynamically allocated memory is managed manually.‬

‭ xample of dynamic memory:‬


E
‭int *ptr = (int *)malloc(sizeof(int)); // Dynamically allocated memory‬
‭*ptr = 10; // Assign a value‬
‭free(ptr); // Manually free the memory when done‬
‭Summary of Scope, Visibility, and Lifetime:‬
‭Property‬ ‭Scope‬ ‭Visibility‬ ‭Lifetime‬

‭ ocal‬
L ‭ ccessible within the‬
A ‭ isible only within the‬
V ‭ xists as long as the‬
E
‭Variable‬ ‭function or block.‬ ‭function or block.‬ ‭function or block is‬
‭executing.‬

‭ lobal‬
G ‭ ccessible throughout‬
A ‭ isible throughout the‬
V ‭ xists for the entire‬
E
‭Variable‬ ‭the program.‬ ‭program after its‬ ‭program execution.‬
‭declaration.‬

‭ tatic‬
S ‭ an be local (within a‬
C ‭ isible only within the‬
V ‭ xists for the entire‬
E
‭Variable‬ ‭function) or global.‬ ‭function or file where‬ ‭program execution.‬
‭declared.‬

‭ ynamic‬
D ‭ ot tied to scope but‬
N ‭ isible through the‬
V ‭ xists until explicitly‬
E
‭Variable‬ ‭allocated using‬ ‭pointer used for‬ free()‬
‭freed by‬‭ ‭.‬
malloc()‬
‭ ‭, etc.‬ ‭allocation.‬

‭Key Points:‬

‭‬ S
● ‭ cope‬‭: Defines where a variable can be accessed in‬‭the program.‬
‭●‬ ‭Visibility‬‭: Determines where the variable can be referenced.‬
‭●‬ ‭Lifetime‬‭: Defines how long a variable exists in memory‬‭during the program execution.‬

‭ hese concepts are important in controlling how variables are used and managed in C‬
T
‭programs.‬

‭ 9. What is a pointer? How are they declared and initialized? [BCA MJ-1 2022] Write a program‬
3
‭to check prime numbers using a pointer. [BCA 2018,2019]‬

‭What is a Pointer in C?‬

‭ ‬‭pointer‬‭in C is a variable that stores the memory‬‭address of another variable. Pointers allow‬
A
‭indirect access to variables, enabling you to manipulate the value of variables indirectly through‬
‭their memory addresses. This feature is widely used for dynamic memory allocation, passing‬
malloc()‬
‭large structures or arrays to functions efficiently, and dealing with functions like‬‭ ‭,‬
free()‬
‭ ‭, etc.‬
‭Declaration and Initialization of Pointers:‬

‭1.‬ D *‬‭symbol before the pointer‬


‭ eclaration‬‭: A pointer is declared using the asterisk‬‭
‭variable name. The type of the pointer must match the type of the variable it will point to.‬

i‭nt *ptr; // Pointer to an integer‬


‭char *ch_ptr; // Pointer to a character‬

‭2.‬ I‭nitialization‬‭: A pointer can be initialized to point to a specific variable by using the‬
‭address-of operator‬‭ &‬
‭.‬
‭int x = 10;‬
‭int *ptr = &x; // Pointer ptr stores the address of variable x‬

‭Program to Check Prime Numbers Using a Pointer:‬

‭ he program below checks whether a given number is prime using pointers. It uses a pointer to‬
T
‭iterate through numbers to check divisibility.‬

‭#include <stdio.h>‬

/‭/ Function to check if a number is prime using a pointer‬


‭int isPrime(int *num) {‬
‭int i, flag = 1;‬

/‭/ A prime number is greater than 1‬


‭if (*num <= 1) {‬
‭return 0; // Not prime if less than or equal to 1‬
‭}‬

/‭/ Check divisibility from 2 to num-1‬


‭for (i = 2; i <= *num / 2; i++) {‬
‭if (*num % i == 0) {‬
‭flag = 0; // Not prime if divisible by any number other than 1 and itself‬
‭break;‬
‭}‬
‭}‬

‭return flag;‬
‭}‬

‭int main() {‬
‭int num;‬
‭int *ptr = &num; // Pointer to the integer num‬
/‭/ Input a number‬
‭printf("Enter a number: ");‬
‭scanf("%d", ptr); // Using pointer to store the input‬

/‭/ Check if the number is prime using pointer‬


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

‭return 0;‬
‭}‬

‭Explanation of the Program:‬

‭1.‬ ‭Pointer Declaration‬‭:‬


‭○‬ ‭
int *ptr;‬‭declares a pointer‬‭
ptr‬‭that will point to‬‭an integer.‬
‭‬ ‭
○ int *ptr = &num;‬‭initializes the pointer‬‭
ptr‬‭to store‬‭the address of‬‭
num‬
‭.‬
‭2.‬ ‭isPrime Function‬‭:‬
isPrime(int *num)‬‭takes a pointer to‬‭an integer as an‬
‭○‬ ‭The function‬‭
num‬
‭argument. This allows the function to work with the address of the variable‬‭ ‭.‬
*num‬‭(the value pointed to‬‭by‬‭
‭○‬ ‭The function checks if‬‭ ptr‬
‭) is divisible by any‬
*num / 2‬
i‭nteger between 2 and‬‭ ‭. If it is divisible,‬‭it's not prime.‬
‭3.‬ ‭Input Using Pointer‬‭:‬
main()‬‭function,‬‭
‭○‬ ‭In the‬‭ scanf("%d", ptr);‬‭is used‬‭to take input for‬‭ num‬
‭. The‬
ptr‬‭holds the address of‬‭
‭pointer‬‭ num‬
‭, so the input‬‭value is stored directly at the‬
‭ emory location of‬‭
m num‬
‭.‬
‭4.‬ ‭Output‬‭:‬
isPrime()‬‭function, the‬
‭○‬ ‭After checking whether the number is prime using the‬‭
‭result is printed.‬

‭Example Input/Output:‬

‭Input:‬
‭Enter a number: 17‬

‭ utput‬‭:‬
O
‭17 is a prime number.‬

I‭nput‬‭:‬
‭Enter a number: 20‬
‭ utput‬‭:‬
O
‭20 is not a prime number.‬

‭Summary of Pointers:‬

‭‬ A
● ‭ ‬‭pointer‬‭is a variable that stores the memory address‬‭of another variable.‬
‭●‬ ‭Pointers are declared with a‬‭ *‬‭symbol, and they are‬‭initialized using the address-of‬
&‬
‭operator‬‭‭.‬
‭●‬ I‭n the above program, we use pointers to pass the address of a variable to a function‬
‭and check whether the number is prime.‬

‭ 0. What is a pointer? What are its uses? Write a program to find the factorial of a number using‬
4
‭a pointer. [BCA 2016]‬

‭What is a Pointer in C?‬

‭ ‬‭pointer‬‭in C is a variable that stores the memory‬‭address of another variable. Instead of‬
A
‭holding a data value itself, a pointer holds the location of where the data is stored. Pointers‬
‭provide powerful features such as dynamic memory allocation, function arguments passing by‬
‭reference, and efficient handling of arrays and strings.‬

‭Uses of Pointers in C:‬

‭1.‬ D ‭ ynamic Memory Allocation‬‭: Pointers are used to allocate‬‭memory dynamically during‬
‭program execution using functions like‬‭ malloc()‬ calloc()‬
‭,‬‭ free()‬
‭,‬‭and‬‭ ‭.‬
‭2.‬ ‭Passing Arguments to Functions by Reference‬‭: By passing‬‭the address of a variable‬
‭to a function, you can modify the actual content of the variable, which is not possible with‬
‭call-by-value.‬
‭3.‬ ‭Efficient Array Handling‬‭: Pointers can be used to‬‭access and manipulate arrays, as‬
‭array names in C are essentially pointers.‬
‭4.‬ ‭Function Pointers‬‭: Pointers can be used to point to‬‭functions, enabling dynamic‬
‭function calls.‬
‭5.‬ ‭Linked Data Structures‬‭: Pointers are used in implementing‬‭dynamic data structures‬
‭like linked lists, stacks, queues, and trees.‬

‭Program to Find the Factorial of a Number Using a Pointer in C:‬

‭Below is a C program that calculates the factorial of a number using pointers.‬


‭#include <stdio.h>‬

/‭/ Function to calculate factorial using pointer‬


‭void calculateFactorial(int *n, int *fact) {‬
‭*fact = 1; // Initialize factorial to 1‬
‭for (int i = 1; i <= *n; i++) {‬
‭*fact *= i; // Multiply current value of fact by i‬
‭}‬
‭}‬

‭int main() {‬
‭int num, fact;‬
‭int *nPtr = &num; // Pointer to num‬
‭int *factPtr = &fact; // Pointer to fact‬

/‭/ Input number‬


‭printf("Enter a number: ");‬
‭scanf("%d", nPtr); // Input the number using pointer‬

/‭/ Calculate factorial using pointers‬


‭calculateFactorial(nPtr, factPtr);‬

/‭/ Output result‬


‭printf("Factorial of %d is %d\n", *nPtr, *factPtr); // Dereferencing pointers to print the result‬

‭return 0;‬
‭}‬

‭Explanation of the Program:‬

‭1.‬ ‭Pointer Declarations‬‭:‬


‭○‬ ‭
int *nPtr = &num;‬‭declares a pointer‬‭
nPtr‬‭and initializes‬‭it with the address‬
num‬
‭of‬‭ ‭.‬
‭○‬ ‭
int *factPtr = &fact;‬‭declares another pointer‬‭
factPtr‬‭to store the‬
fact‬
‭address of‬‭ ‭, where the calculated factorial will‬‭be stored.‬
calculateFactorial()‬
‭2.‬ ‭Function‬‭ ‭:‬
nPtr‬‭(pointer to‬‭the input number) and‬
‭○‬ ‭This function takes two pointers:‬‭
factPtr‬‭(pointer to the factorial).‬

1‬‭to‬‭the value stored at‬‭
‭○‬ ‭It calculates the factorial by iterating from‬‭ *nPtr‬‭(the‬
nPtr‬
‭dereferenced value of‬‭ ‭).‬
○ factPtr‬
‭ ‬ ‭The result is stored in the memory location pointed to by‬‭ ‭.‬
‭3.‬ ‭Input‬‭:‬
scanf("%d",‬
‭○‬ ‭The program asks the user to enter a number and reads it using‬‭
nPtr);‬
‭ num‬‭is passed to‬‭
‭. The address of‬‭ nPtr‬‭to store‬‭the value.‬
‭4.‬ ‭Output‬‭:‬
calculateFactorial()‬‭function‬‭and prints the result‬
‭○‬ ‭The program calls the‬‭
factPtr‬‭and‬‭
‭by dereferencing‬‭ nPtr‬
‭.‬

‭Example Input/Output:‬

‭Input:‬
‭Enter a number: 5‬

‭ utput‬‭:‬
O
‭Factorial of 5 is 120‬

‭Summary:‬

‭‬ P
● ‭ ointers‬‭are variables that hold the memory address‬‭of another variable.‬
‭●‬ ‭They are essential for tasks like dynamic memory allocation, passing data by reference,‬
‭and efficient array handling.‬
‭●‬ ‭The example program demonstrates calculating the factorial of a number using pointers.‬
‭The address of the input number is passed to the function, and the factorial is calculated‬
‭by manipulating the value stored at that address.‬

‭41. Explain the array of pointers. [BCA 2016]‬


‭Array of Pointers in C Language‬

‭ n‬‭array of pointers‬‭is an array where each element‬‭of the array is a pointer that holds the‬
A
‭memory address of a variable. Essentially, it’s an array whose elements are pointers, and each‬
‭pointer can point to a different data location.‬

‭ his concept is widely used in cases where you need to store addresses of different variables,‬
T
‭manage arrays of strings, or work with dynamic memory in an efficient way.‬

‭Syntax of Array of Pointers:‬

‭To declare an array of pointers, the syntax is:‬

‭<type> *<array_name>[size];‬

‭Here:‬
‭●‬ ‭
<type>‬‭is the type of data that the pointer will point to (e.g.,‬‭
int‬ char‬
‭,‬‭ ‭, etc.).‬
‭●‬ ‭
<array_name>‬‭is the name of the array.‬
‭●‬ ‭
size‬‭is the number of elements in the array.‬

‭For example:‬

‭int *arr[5]; // Array of 5 integer pointers‬

arr‬‭that can hold 5 pointers to integers.‬


‭This declares an array‬‭
‭Example: Array of Pointers‬

‭Here’s an example that demonstrates how an‬‭array of pointers‬‭works in C:‬

‭#include <stdio.h>‬

‭int main() {‬
‭int num1 = 10, num2 = 20, num3 = 30, num4 = 40;‬

/‭/ Declare an array of pointers to integers‬


‭int *arr[4];‬

/‭/ Assign the addresses of variables to the array elements‬


‭arr[0] = &num1;‬
‭arr[1] = &num2;‬
‭arr[2] = &num3;‬
‭arr[3] = &num4;‬

/‭/ Access values using the pointers in the array‬


‭printf("Value at arr[0]: %d\n", *arr[0]); // Dereference arr[0]‬
‭printf("Value at arr[1]: %d\n", *arr[1]); // Dereference arr[1]‬
‭printf("Value at arr[2]: %d\n", *arr[2]); // Dereference arr[2]‬
‭printf("Value at arr[3]: %d\n", *arr[3]); // Dereference arr[3]‬

‭return 0;‬
‭}‬

‭Explanation of the Program:‬

‭1.‬ ‭Declaration of Array of Pointers‬‭:‬

i‭nt *arr[4];‬
‭This creates an array of 4 pointers (‬‭
arr‬
‭), where each pointer is intended to point‬
‭to an integer.‬
‭2.‬ A
‭ ssigning Addresses to the Pointers‬‭:‬
‭arr[0] = &num1;‬
‭arr[1] = &num2;‬
‭arr[2] = &num3;‬
‭arr[3] = &num4;‬

‭3.‬ A
‭ ccessing Values Through Pointers‬‭:‬
‭printf("Value at arr[0]: %d\n", *arr[0]); // Dereference arr[0]‬

‭ y dereferencing the pointers in the array, we access and print the values of the‬
B
‭variables that the pointers point to.‬

‭ xample Output:‬
E
‭Value at arr[0]: 10‬
‭Value at arr[1]: 20‬
‭Value at arr[2]: 30‬
‭Value at arr[3]: 40‬

‭Applications of Array of Pointers:‬

‭1.‬ S ‭ toring Addresses of Multiple Variables‬‭: You can store‬‭the memory addresses of‬
‭multiple variables of the same type in an array of pointers.‬
‭2.‬ ‭Array of Strings‬‭: An array of pointers is often used to store strings in C because each‬
‭string is an array of characters, and you can store the addresses of these arrays in an‬
‭array of pointers.‬

‭Example:‬

‭ har *str[] = {"Hello", "World", "C", "Programming"};‬


c
‭for (int i = 0; i < 4; i++) {‬
‭printf("%s\n", str[i]); // Print each string‬
‭}‬

‭3.‬ D
‭ ynamic Memory Allocation‬‭: An array of pointers can be used to dynamically allocate‬
‭memory for an array of structures or other data types.‬

‭Key Points:‬

‭●‬ A ‭ rray of Pointers‬‭: It's an array where each element‬‭is a pointer to a specific type of‬
‭data (e.g., integers, characters).‬
‭●‬ ‭Use Case‬‭: It is commonly used for dynamic memory allocation,‬‭handling arrays of‬
‭strings, and managing multiple data locations.‬
‭●‬ ‭Dereferencing‬‭: The elements of the array are pointers,‬‭so you must dereference the‬
‭pointers to access the values they point to.‬
‭ his concept is helpful for managing and working with complex data structures and improving‬
T
‭memory management in C programs.‬

‭ 2. Write a program to create the structure of a student having fields Roll, name, and Marks.‬
4
‭Input records and display them. [BCA 2016,2018]‬

H Roll‬
‭ ere is a C program to create a structure for a student with fields‬‭ name‬
‭,‬‭ Marks‬
‭, and‬‭ ‭. The‬
‭program will input student records and display them:‬

‭ include <stdio.h>‬
#
‭#include <string.h>‬

/‭/ Define the structure‬


‭struct Student {‬
‭int roll; // Roll number‬
‭char name[50]; // Name of the student‬
‭float marks; // Marks of the student‬
‭};‬

‭int main() {‬
‭struct Student students[5]; // Array of 5 students‬
‭int i;‬

/‭/ Input student records‬


‭printf("Enter details of 5 students:\n");‬
‭for (i = 0; i < 5; i++) {‬
‭printf("\nEnter details for student %d:\n", i + 1);‬
‭printf("Roll Number: ");‬
‭scanf("%d", &students[i].roll);‬
‭printf("Name: ");‬
‭getchar(); // To consume any leftover newline character in the buffer‬
‭fgets(students[i].name, sizeof(students[i].name), stdin);‬
‭students[i].name[strcspn(students[i].name, "\n")] = '\0'; // Remove newline character‬
‭printf("Marks: ");‬
‭scanf("%f", &students[i].marks);‬
‭}‬

/‭/ Display student records‬


‭printf("\nDisplaying student records:\n");‬
‭for (i = 0; i < 5; i++) {‬
‭printf("\nStudent %d details:\n", i + 1);‬
‭printf("Roll Number: %d\n", students[i].roll);‬
‭ rintf("Name: %s\n", students[i].name);‬
p
‭printf("Marks: %.2f\n", students[i].marks);‬
‭}‬

‭return 0;‬
‭}‬

‭Explanation of the Program:‬

‭1.‬ ‭Structure Declaration‬‭:‬


Student‬‭is defined with three fields:‬
‭○‬ ‭The structure‬‭
‭■‬ ‭
roll‬
‭: An integer to store the roll number.‬
‭■‬ ‭
name‬
‭: A character array (string) to store the name‬‭of the student.‬
‭‬ ‭
■ marks‬‭: A floating-point number to store the marks‬‭of the student.‬
‭2.‬ ‭Input Data‬‭:‬
‭○‬ ‭The program uses a loop to input details for 5 students.‬
‭○‬ ‭
fgets()‬‭is used to read the name to allow spaces in‬‭the name. After reading‬
t‭he name, the newline character at the end is removed using‬‭ strcspn()‬ ‭.‬
‭3.‬ ‭Display Data‬‭:‬
‭○‬ ‭After inputting the details of the students, the program displays the stored‬
‭information for each student in a formatted manner.‬

‭Example Input/Output:‬

‭Input:‬
‭Enter details of 5 students:‬

‭ nter details for student 1:‬


E
‭Roll Number: 101‬
‭Name: John Doe‬
‭Marks: 75.5‬

‭ nter details for student 2:‬


E
‭Roll Number: 102‬
‭Name: Alice‬
‭Marks: 88.0‬

‭ nter details for student 3:‬


E
‭Roll Number: 103‬
‭Name: Bob Smith‬
‭Marks: 92.5‬
‭ nter details for student 4:‬
E
‭Roll Number: 104‬
‭Name: Charlie‬
‭Marks: 60.0‬

‭ nter details for student 5:‬


E
‭Roll Number: 105‬
‭Name: David‬
‭Marks: 78.5‬

‭ utput‬‭:‬
O
‭Displaying student records:‬

‭ tudent 1 details:‬
S
‭Roll Number: 101‬
‭Name: John Doe‬
‭Marks: 75.50‬

‭ tudent 2 details:‬
S
‭Roll Number: 102‬
‭Name: Alice‬
‭Marks: 88.00‬

‭ tudent 3 details:‬
S
‭Roll Number: 103‬
‭Name: Bob Smith‬
‭Marks: 92.50‬

‭ tudent 4 details:‬
S
‭Roll Number: 104‬
‭Name: Charlie‬
‭Marks: 60.00‬

‭ tudent 5 details:‬
S
‭Roll Number: 105‬
‭Name: David‬
‭Marks: 78.50‬
‭Key Points:‬

int‬
‭●‬ ‭Structure‬‭: A structure in C allows grouping different data types (such as‬‭ char[]‬
‭,‬‭ ‭,‬
float‬
‭ ‭) together to represent a single entity (in this‬‭case, a student).‬
scanf()‬‭for reading numbers and‬‭
‭●‬ I‭nput‬‭: The program uses‬‭ fgets()‬‭for reading‬
‭strings with spaces.‬
printf()‬‭to display the‬‭student records in a structured‬
‭●‬ ‭Display‬‭: The program uses‬‭
‭format.‬

‭43. What is a union? How is it different from structure? [BCA 2016,2018,2019]‬

‭What is a Union in C?‬

‭ ‬‭union‬‭in C is a special data type that allows storing‬‭different data types in the same memory‬
A
‭location. Unlike a structure, where each member has its own memory space, a union uses a‬
‭shared memory space for all its members. This means that at any point, only one of the union‬
‭members can hold a value, and the size of a union is determined by the size of its largest‬
‭member.‬

‭ yntax of Union‬‭:‬
S
‭union <union_name> {‬
‭<data_type> member1;‬
‭<data_type> member2;‬
‭<data_type> member3;‬
‭// more members‬
‭};‬

‭ xample of Union‬‭:‬
E
‭#include <stdio.h>‬

/‭/ Define a union‬


‭union Data {‬
‭int i;‬
‭float f;‬
‭char c;‬
‭};‬

‭int main() {‬
‭union Data data; // Declare a variable of type union Data‬

/‭/ Assign values to the members‬


‭data.i = 10;‬
‭printf("Data.i = %d\n", data.i);‬

‭ ata.f = 3.14;‬
d
‭printf("Data.f = %.2f\n", data.f);‬

‭ ata.c = 'A';‬
d
‭printf("Data.c = %c\n", data.c);‬

‭return 0;‬
‭}‬

‭Explanation of the Union Example:‬

‭1.‬ ‭Memory Sharing‬‭:‬


‭○‬ ‭The union‬‭ Data‬‭has three members:‬‭ i‬‭(integer),‬‭
f‬‭(float),‬‭and‬‭
c‬‭(char).‬
‭○‬ ‭All members share the same memory location, so when you assign a value to‬
‭one member (e.g.,‬‭ data.i = 10‬ ‭), it overwrites any‬‭previously stored value in‬
‭the union. Only the most recently assigned value is valid at any time.‬
‭2.‬ ‭Size of Union‬‭:‬
‭○‬ ‭The size of the union is determined by the largest member. In this case, if‬‭ int‬‭is‬
float‬‭is 4 bytes, and‬‭
‭ bytes,‬‭
4 char‬‭is 1 byte, the‬‭union will have a size of 4‬
‭bytes.‬

‭Key Points about Union:‬

‭●‬ M ‭ emory Efficiency‬‭: Unions save memory because they‬‭allow different types of data to‬
‭share the same memory location. However, only one member can store a value at a‬
‭time.‬
‭●‬ ‭Accessing Members‬‭: When you access a member, the value‬‭of the most recently‬
‭written member is accessible. All other members will contain garbage values.‬
‭●‬ ‭Size of Union‬‭: The size of a union is equal to the size of its largest member.‬

‭Difference Between Union and Structure:‬


‭Feature‬ ‭Union‬ ‭Structure‬

‭ emory‬
M ‭ ll members share the same memory‬ E
A ‭ ach member has its own memory‬
‭Allocation‬ ‭space. The size of the union is the‬ ‭space. The size of the structure is the‬
‭size of its largest member.‬ ‭sum of sizes of all its members.‬

‭Storage‬ ‭ nly one member can hold a value at‬ A


O ‭ ll members can hold values‬
‭any time.‬ ‭simultaneously.‬
‭Usage‬ ‭ sed when you need to store‬
U ‭ sed when you need to store different‬
U
‭different data types but only one‬ ‭data types and access them‬
‭value at a time (e.g., saving‬ ‭simultaneously.‬
‭memory).‬

‭Size‬ ‭ he size is the maximum size of the‬


T ‭ he size is the sum of the sizes of all‬
T
‭members.‬ ‭members.‬

‭ ccessing‬
A ‭ ccessing one member overwrites‬
A ‭ ll members are independent and can‬
A
‭Members‬ ‭the other members.‬ ‭be accessed at the same time.‬

‭Example‬ int‬
‭For a variable that can hold an‬‭ ‭,‬ name‬
‭For a record that stores‬‭ age‬
‭,‬‭ ‭,‬
‭loat‬
f char‬‭but not‬
‭, or‬‭ marks‬‭for a student.‬
‭and‬‭
‭simultaneously.‬

‭Summary:‬

‭●‬ U ‭ nion‬‭: A union allows multiple members of different‬‭data types to share the same‬
‭memory space. At any given time, only one member can store a value, and the union’s‬
‭size is the size of its largest member.‬
‭●‬ ‭Structure‬‭: A structure stores different data types‬‭in separate memory locations. Each‬
‭member of the structure holds its own value independently, and the total size of a‬
‭structure is the sum of the sizes of all its members.‬

‭ hile a‬‭union‬‭is used for memory efficiency when only‬‭one value is needed at a time, a‬
W
‭structure‬‭is used when you need to store multiple values of different types simultaneously.‬

‭ 4. How the structure is different from an array? Explain the terms ‘Array of Structure’ and‬
4
‭‘Nesting of structure’ with examples. [BCA 2019]‬

‭Difference Between Structure and Array in C‬

‭Structures and arrays are both used to store data, but they have some fundamental differences:‬

‭Feature‬ ‭Structure‬ ‭Array‬

‭Definition‬ ‭ structure is a user-defined data‬


A ‭ n array is a collection of elements of the‬
A
‭type that groups different types of‬ ‭same data type, stored in contiguous‬
‭data under a single name.‬ ‭memory locations.‬
‭Data Types‬ ‭ structure can hold elements of‬
A ‭ ll elements in an array must be of the‬
A
‭different data types (e.g., int, float,‬ ‭same data type.‬
‭char, etc.).‬

‭ emory‬
M ‭ ach member of a structure has its‬
E ‭ ll elements of an array occupy‬
A
‭Allocation‬ ‭own memory space. The size of a‬ ‭contiguous memory locations. The size of‬
‭structure is the sum of sizes of its‬ ‭the array is the number of elements‬
‭members.‬ ‭multiplied by the size of each element.‬

‭ ccessing‬
A ‭ ach member can be accessed‬
E ‭ rray elements are accessed using an‬
A
‭Members‬ ‭using a dot operator (e.g.,‬ array[index]‬
‭index (e.g.,‬‭ ‭).‬
struct.member‬
‭ ‭).‬

‭Usage‬ ‭ tructures are used to represent a‬


S ‭ rrays are used to store multiple‬
A
‭collection of related data of‬ ‭elements of the same type.‬
‭different types.‬

‭Array of Structures:‬

‭ n‬‭array of structures‬‭is a collection of structures‬‭where each element of the array is a‬


A
‭structure. It allows you to store multiple records of a type where each record may contain‬
‭different types of data.‬

‭Syntax:‬
‭struct <structure_name> array_name[size];‬

‭●‬ ‭
structure_name‬
‭: The name of the structure.‬
‭●‬ ‭
array_name‬
‭: The name of the array.‬
‭●‬ ‭
size‬
‭: The number of elements in the array.‬

‭ xample of Array of Structures‬‭:‬


E
‭#include <stdio.h>‬

/‭/ Define a structure‬


‭struct Student {‬
‭int roll;‬
‭char name[50];‬
‭float marks;‬
‭};‬

‭int main() {‬
‭// Declare an array of 3 structures‬
‭struct Student students[3];‬
/‭/ Input details for 3 students‬
‭for (int i = 0; i < 3; i++) {‬
‭printf("Enter roll number: ");‬
‭scanf("%d", &students[i].roll);‬
‭printf("Enter name: ");‬
‭getchar(); // To clear the newline character from the input buffer‬
‭fgets(students[i].name, sizeof(students[i].name), stdin);‬
‭printf("Enter marks: ");‬
‭scanf("%f", &students[i].marks);‬
‭}‬

/‭/ Display the records of the students‬


‭for (int i = 0; i < 3; i++) {‬
‭printf("\nStudent %d Details:\n", i + 1);‬
‭printf("Roll Number: %d\n", students[i].roll);‬
‭printf("Name: %s", students[i].name); // No need for newline since fgets() captures it‬
‭printf("Marks: %.2f\n", students[i].marks);‬
‭}‬

‭return 0;‬
‭}‬

‭Explanation:‬

‭●‬ A ‭ rray of Structures‬‭: In the example above,‬‭ students‬‭is an array of 3‬‭


Student‬
‭structures. Each structure stores information about a student (roll number, name, and‬
‭marks).‬
‭●‬ ‭Input‬‭: The program uses a loop to input the data for‬‭3 students.‬
‭●‬ ‭Display‬‭: It then displays the stored records of each student.‬

‭Nesting of Structures:‬

‭ esting of structures‬‭refers to the concept of having‬‭a structure as a member of another‬


N
‭structure. In other words, a structure can contain other structures as its members. This is useful‬
‭when you want to represent complex data where some members themselves are collections of‬
‭data.‬

‭Syntax:‬
‭struct <outer_structure> {‬
‭<structure_type> inner_structure;‬
‭// other members‬
‭};‬
‭ xample of Nesting of Structures‬‭:‬
E
‭#include <stdio.h>‬

/‭/ Define inner structure‬


‭struct Date {‬
‭int day;‬
‭int month;‬
‭int year;‬
‭};‬

/‭/ Define outer structure‬


‭struct Student {‬
‭int roll;‬
‭char name[50];‬
‭struct Date dob; // Nested structure‬
‭};‬

‭int main() {‬
‭struct Student student1;‬

/‭/ Input student details‬


‭printf("Enter roll number: ");‬
‭scanf("%d", &student1.roll);‬
‭printf("Enter name: ");‬
‭getchar(); // To clear the newline character‬
‭fgets(student1.name, sizeof(student1.name), stdin);‬

/‭/ Input Date of Birth (nested structure)‬


‭printf("Enter date of birth (day month year): ");‬
‭scanf("%d %d %d", &student1.dob.day, &student1.dob.month, &student1.dob.year);‬

/‭/ Display student details‬


‭printf("\nStudent Details:\n");‬
‭printf("Roll Number: %d\n", student1.roll);‬
‭printf("Name: %s", student1.name); // No need for newline since fgets() includes it‬
‭printf("Date of Birth: %d/%d/%d\n", student1.dob.day, student1.dob.month,‬
‭student1.dob.year);‬

‭return 0;‬
‭}‬
‭Explanation:‬

Student‬‭structure contains another‬


‭●‬ ‭Nesting of Structures‬‭: In the example, the‬‭
Date‬‭as a member. The‬‭
‭ tructure‬‭
s Date‬‭structure stores‬‭the student's birth date (day,‬
‭month, year).‬
‭●‬ ‭Input‬‭: The program inputs the roll number, name, and‬‭date of birth for the student.‬
‭ ‬ ‭Display‬‭: It then displays the student’s details, including the nested date of birth.‬

‭Key Differences:‬
‭Feature‬ ‭Array of Structures‬ ‭Nesting of Structures‬

‭Definition‬ ‭ n array of structures is a‬


A ‭ esting of structures is when one structure‬
N
‭collection of multiple structures.‬ ‭contains another structure as a member.‬

‭Usage‬ ‭ sed when you have multiple‬


U ‭ sed when a structure requires another‬
U
‭instances of a structure (e.g., an‬ ‭structure as part of its data (e.g., a student‬
‭array of students).‬ ‭with a date of birth).‬

‭ ccessing‬
A ‭ ccess each structure element‬
A ‭ ccess the nested structure members‬
A
‭Members‬ ‭by index and then use dot‬ ‭using the dot operator twice: once for the‬
‭operator to access members.‬ ‭outer and once for the inner structure.‬

‭Summary:‬

‭●‬ A ‭ rray of Structures‬‭: Allows you to store multiple‬‭instances of the same type of structure‬
‭in an array.‬
‭●‬ ‭Nesting of Structures‬‭: Allows you to define a structure‬‭within another structure to‬
‭represent more complex data relationships.‬

‭ oth concepts provide ways to organize and structure data efficiently in C programming,‬
B
‭enabling you to handle more complex data types.‬

‭45. Explain preprocessor directives. When do we use #define and #include? [BCA 2016,2017]‬

‭Preprocessor Directives in C‬

‭ reprocessor directives in C are commands that are processed by the preprocessor before the‬
P
‭compilation of the program begins. They are used to manipulate the source code, manage file‬
‭inclusion, define constants, and control conditional compilation.‬

‭ reprocessor directives are not C language statements; they are instructions for the‬
P
#‬‭symbol. The most‬‭commonly used preprocessor directives in‬
‭preprocessor that start with the‬‭
#define‬
‭C are‬‭ #include‬
‭,‬‭ #ifdef‬
‭,‬‭ #ifndef‬
‭,‬‭ #if‬
‭, and‬‭ ‭.‬
#define‬‭Directive:‬
‭1.‬‭

‭ he‬‭
T #define‬‭directive is used to define‬‭macros‬‭or‬‭constants‬‭that are used throughout the‬
‭program. These macros can represent values or expressions. When the preprocessor‬
‭encounters the macro, it replaces it with the defined value or expression.‬

‭Syntax:‬
‭#define NAME value‬

NAME‬‭is the identifier that will be replaced by‬‭


‭ value‬‭in the program wherever it is used.‬
‭ xample of‬‭
E #define‬‭:‬
‭#include <stdio.h>‬

‭ define PI 3.14159 // Defining a constant macro‬


#
‭#define AREA(r) (PI * (r) * (r)) // Defining a macro for calculating area of a circle‬

‭int main() {‬
‭float radius = 5.0;‬
‭printf("Area of the circle with radius %.2f is %.2f\n", radius, AREA(radius));‬
‭return 0;‬
‭}‬

#define‬
‭Explanation of‬‭ ‭:‬

‭●‬ T ‭ he‬‭ #define‬‭directive defines‬‭


PI‬‭as a constant value‬‭(3.14159), and‬‭AREA(r)‬‭as a‬
‭macro function that calculates the area of a circle.‬
‭●‬ ‭The preprocessor replaces all instances of‬‭ PI‬‭and‬‭AREA(r)‬‭with their respective values‬
‭during the precompilation stage.‬

#define‬
‭When to Use‬‭ ‭:‬

‭●‬ D #define‬‭to define constants‬‭that will remain unchanged‬


‭ efining Constants‬‭: Use‬‭
‭throughout the program.‬
‭●‬ ‭Creating Macros‬‭: Use‬‭#define‬‭to define reusable code‬‭snippets or expressions that‬
‭can be evaluated at compile-time.‬

#include‬‭Directive:‬
‭2.‬‭

‭ he‬‭
T #include‬‭directive is used to include header files‬‭into your C program. Header files‬
‭contain function declarations, macro definitions, and other declarations that are needed for a‬
‭program to work properly.‬
‭Syntax:‬
‭ include <filename> // For standard library header files‬
#
‭#include "filename" // For user-defined header files‬

<filename>‬‭is used for including standard library‬‭header files.‬



"filename"‬‭is used for including user-defined header files.‬

‭ xample of‬‭
E #include‬ ‭:‬
‭#include <stdio.h> // Including standard library header file for I/O functions‬
‭#include "myheader.h" // Including a user-defined header file‬

‭int main() {‬
‭printf("Hello, World!\n");‬
‭return 0;‬
‭}‬

#include‬
‭Explanation of‬‭ ‭:‬

#include <stdio.h>‬‭directive includes the standard‬‭input/output header file,‬


‭●‬ ‭The‬‭
printf()‬
‭which provides functions like‬‭ ‭.‬
#include "myheader.h"‬‭directive includes a user-defined‬‭header file (e.g.,‬
‭●‬ ‭The‬‭
myheader.h‬
‭ ‭), which might contain additional declarations‬‭or definitions for the program.‬

#include‬
‭When to Use‬‭ ‭:‬

#include‬‭to include standard‬‭library header files like‬


‭●‬ ‭Standard Libraries‬‭: Use‬‭
<stdio.h>‬
‭ <math.h>‬
‭,‬‭ ‭, etc., to use built-in functions.‬
‭●‬ U
‭ ser-Defined Header Files‬‭: Use‬‭#include "filename"‬‭to include your own custom‬
‭header files, which may contain function prototypes, constants, and macros.‬

#define‬‭and‬‭
‭Key Differences Between‬‭ #include‬
‭:‬
‭Directive‬ ‭Purpose‬ ‭When to Use‬

#define‬ D
‭ ‭ efines constants or macros that are‬ ‭ se‬‭
U #define‬‭to declare constants or‬
‭replaced by the preprocessor before‬ ‭create macros that are used throughout‬
‭compilation.‬ ‭the program.‬

#includ‬ I‭ncludes header files, either standard‬


‭ ‭ se‬‭
U #include‬‭to bring in function‬
e‬
‭ ‭library files or custom header files,‬ ‭prototypes and definitions from external‬
‭into the program.‬ ‭libraries or your own files.‬
‭ xample Program Using‬‭
E #define‬‭and‬‭ #include‬
‭:‬
‭#include <stdio.h> // Standard library for I/O‬
‭#define MAX 100 // Defining a constant macro‬

‭int main() {‬
‭int numbers[MAX]; // Array with size MAX (100)‬

/‭/ Assigning values‬


‭for (int i = 0; i < MAX; i++) {‬
‭numbers[i] = i + 1;‬
‭}‬

/‭/ Printing the numbers‬


‭printf("First 10 numbers in the array are:\n");‬
‭for (int i = 0; i < 10; i++) {‬
‭printf("%d ", numbers[i]);‬
‭}‬

‭return 0;‬
‭}‬

‭Explanation:‬

#include <stdio.h>‬‭directive is used to include‬‭the standard I/O functions.‬


‭●‬ ‭The‬‭
‭●‬ T #define MAX 100‬‭directive defines a constant‬‭
‭ he‬‭ MAX‬‭that is used to declare an‬
‭array of size 100.‬
‭●‬ ‭The array‬‭ numbers[MAX]‬‭is initialized with values, and the program prints the first 10‬
‭numbers.‬

‭Summary:‬

‭●‬ #‭define‬ ‭: Used to define constants or macros. It helps‬‭in making the code more‬
‭readable and reusable by substituting values and expressions at compile-time.‬
‭●‬ ‭#include‬ ‭: Used to include external files (standard‬‭or user-defined header files). It‬
‭allows you to use predefined functions, constants, and other structures from libraries in‬
‭your program.‬

#define‬‭and‬‭
‭ oth‬‭
B #include‬‭are essential preprocessor‬‭directives that help in making the‬
‭code more modular, maintainable, and efficient.‬

‭46. Explain Macros. [BCA 2016]‬


‭ efinition‬‭:‬
D
‭Macros in C are preprocessor directives used to define constants, expressions, or code‬
‭snippets that are replaced by the preprocessor before the compilation. They are defined using‬
#define‬‭directive.‬
‭the‬‭
‭Types of Macros:‬

‭1.‬ ‭Object-like Macros‬‭:‬

‭Simple macros that represent constant values or expressions.‬

‭ define PI 3.14159‬
#
‭#define MAX_SIZE 100‬

‭2.‬ F
‭ unction-like Macros‬‭:‬
‭Macros that take parameters and return expressions or values based on those‬
‭parameters.‬

‭ define SQUARE(x) ((x) * (x))‬


#
‭#define MAX(a, b) ((a) > (b) ? (a) : (b))‬

‭Advantages:‬

‭ .‬ C
1 ‭ ode Reusability‬‭: Reuse code or expressions without‬‭rewriting them.‬
‭2.‬ ‭Efficiency‬‭: Faster execution as they are replaced‬‭during preprocessing.‬
‭3.‬ ‭Readability‬:‭ Improves readability and maintainability by using meaningful names for‬
‭constants.‬

‭Disadvantages:‬

‭ .‬ D
1 ‭ ebugging‬‭: Difficult to debug due to lack of type‬‭checking and no runtime information.‬
‭2.‬ ‭Global Replacement‬‭: Macros are replaced throughout‬‭the program, which can cause‬
‭unexpected behavior.‬
‭3.‬ ‭No Type Safety‬‭: Macros do not check types, leading to potential errors in function-like‬
‭macros.‬

‭Example of Macros:‬
‭#include <stdio.h>‬

‭ define PI 3.14159
# // Object-like macro‬
‭#define SQUARE(x) ((x) * (x)) // Function-like macro‬
‭#define MAX(a, b) ((a) > (b) ? (a) : (b)) // Function-like macro‬
‭int main() {‬
‭float radius = 5.0;‬
‭float area = PI * SQUARE(radius); // Using macros‬

i‭nt a = 10, b = 20;‬


‭int max_value = MAX(a, b); // Using MAX macro‬

‭ rintf("Area of the circle: %.2f\n", area);‬


p
‭printf("Maximum value: %d\n", max_value);‬

‭return 0;‬
‭}‬

‭Key Points:‬

‭●‬ # ‭define‬‭is used to define both constants (object-like‬‭macros) and‬


‭expressions/functions (function-like macros).‬
‭●‬ ‭Parentheses‬‭are essential around parameters and the‬‭entire expression to avoid errors‬
‭in function-like macros.‬
‭●‬ ‭Macros are expanded at compile-time and do not have a scope, leading to potential‬
‭issues in larger programs.‬

‭47. Explain file handling functions. [BCA 2016,2018,2019]‬

‭File Handling Functions in C Language‬

‭ ile handling in C is performed using a set of library functions that allow reading from and‬
F
‭writing to files. These functions are part of the standard library (‬‭
stdio.h‬‭).‬

‭Common File Handling Functions in C:‬

fopen()‬
‭ ‭:‬

‭ sed to open a file in a specified mode (read, write, etc.).‬


U
‭Syntax‬‭:‬

‭FILE *fopen(const char *filename, const char *mode);‬

‭Modes‬‭:‬
‭●‬ ‭
"r"‬
‭: Read mode (file must exist).‬
‭●‬ ‭
"w"‬
‭: Write mode (creates file if it doesn't exist).‬
‭●‬ ‭
"a"‬
‭: Append mode (opens file for writing at the end).‬
‭●‬ ‭
"rb"‬ "wb"‬
‭,‬‭ ‭: Binary read/write modes.‬

‭Example‬‭:‬

‭FILE *file = fopen("example.txt", "r");‬

fclose()‬
‭ ‭:‬

‭Used to close an opened file.‬

‭Syntax‬‭:‬

‭int fclose(FILE *file);‬

‭ xample‬‭:‬
E
‭fclose(file);‬

fread()‬
‭ ‭:‬

‭Reads data from a file into a buffer.‬

‭ yntax‬‭:‬
S
‭size_t fread(void *buffer, size_t size, size_t count, FILE *file);‬

‭ xample‬‭:‬
E
‭char buffer[100];‬

‭fread(buffer, sizeof(char), 100, file);‬


fwrite()‬
‭ ‭:‬

‭Writes data from a buffer to a file.‬

‭ yntax‬‭:‬
S
‭size_t fwrite(const void *buffer, size_t size, size_t count, FILE *file);‬

‭ xample‬‭:‬
E
‭char data[] = "Hello, World!";‬

‭fwrite(data, sizeof(char), strlen(data), file);‬

fgetc()‬
‭ ‭:‬

‭Reads a single character from a file.‬

‭ yntax‬‭:‬
S
‭int fgetc(FILE *file);‬

‭ xample‬‭:‬
E
‭char ch = fgetc(file);‬

fputc()‬
‭ ‭:‬

‭Writes a single character to a file.‬

‭ yntax‬‭:‬
S
‭int fputc(int char, FILE *file);‬

‭ xample‬‭:‬
E
‭fputc('A', file);‬
fgets()‬
‭ ‭:‬

‭Reads a string from a file until a newline or the end-of-file is encountered.‬

‭ yntax‬‭:‬
S
‭char *fgets(char *str, int n, FILE *file);‬

‭ xample‬‭:‬
E
‭char line[100];‬

‭fgets(line, 100, file);‬

fputs()‬
‭ ‭:‬

‭Writes a string to a file.‬

‭ yntax‬‭:‬
S
‭int fputs(const char *str, FILE *file);‬

‭ xample‬‭:‬
E
‭fputs("Hello, World!", file);‬

feof()‬
‭ ‭:‬

‭Checks if the end of the file has been reached.‬

‭ yntax‬‭:‬
S
‭int feof(FILE *file);‬

‭ xample‬‭:‬
E
‭if (feof(file)) {‬

‭printf("End of file reached\n");‬

‭}‬
fseek()‬
‭ ‭:‬

‭Moves the file pointer to a specific location in the file.‬

‭ yntax‬‭:‬
S
‭int fseek(FILE *file, long int offset, int whence);‬

‭ xample‬‭:‬
E
‭fseek(file, 0, SEEK_SET); // Move to the beginning of the file‬

ftell()‬
‭ ‭:‬

‭Returns the current position of the file pointer.‬

‭ yntax‬‭:‬
S
‭long int ftell(FILE *file);‬

‭ xample‬‭:‬
E
‭long int position = ftell(file);‬

rewind()‬
‭ ‭:‬

‭Resets the file pointer to the beginning of the file.‬

‭ yntax‬‭:‬
S
‭void rewind(FILE *file);‬

‭ xample‬‭:‬
E
‭rewind(file); // Move file pointer to the beginning‬
‭ xample Program‬‭:‬
E
‭#include <stdio.h>‬

‭int main() {‬

‭FILE *file;‬

‭char text[] = "Hello, file handling in C!";‬

‭// Opening file for writing‬

‭file = fopen("example.txt", "w");‬

‭if (file == NULL) {‬

‭printf("Unable to open file\n");‬

‭return 1;‬

‭}‬

‭// Writing to the file‬

‭fwrite(text, sizeof(char), strlen(text), file);‬

‭// Closing the file‬

‭fclose(file);‬

‭// Reopening file for reading‬

‭file = fopen("example.txt", "r");‬

‭if (file == NULL) {‬

‭printf("Unable to open file\n");‬

‭return 1;‬
‭}‬

‭char ch;‬

‭while ((ch = fgetc(file)) != EOF) {‬

‭putchar(ch); // Printing the content to console‬

‭}‬

‭// Closing the file‬

‭fclose(file);‬

‭return 0;‬

‭}‬

‭Conclusion:‬

‭ ile handling in C provides several functions for performing input and output operations on files.‬
F
‭These functions allow you to read, write, and manipulate data in files, providing a way to persist‬
‭data beyond the program’s execution.‬

‭48. Explain Dynamic Memory Allocation. [BCA MJ-1 2022]‬

‭Dynamic Memory Allocation in C Language‬

‭ ynamic memory allocation in C allows the allocation of memory at runtime (as opposed to‬
D
‭static memory allocation, which occurs at compile-time). This gives the programmer flexibility to‬
‭allocate memory as needed, freeing memory once it's no longer in use.‬

‭Functions for Dynamic Memory Allocation:‬

<stdlib.h>‬‭header.‬
‭These functions are defined in the‬‭

malloc()‬‭(Memory Allocation):‬

‭‬ A
○ ‭ llocates a block of memory of a specified size.‬
‭○‬ ‭Returns a pointer to the first byte of the allocated memory.‬
NULL‬
‭○‬ ‭If allocation fails, returns‬‭ ‭.‬

‭ yntax‬‭:‬
S
‭void *malloc(size_t size);‬

‭ xample‬‭:‬
E
‭int *ptr = (int *)malloc(sizeof(int) * 5); // Allocates memory for 5 integers‬

calloc()‬‭(Contiguous Allocation):‬

‭‬ A
● ‭ llocates memory for an array of elements, initializing all elements to zero.‬
‭●‬ ‭Returns a pointer to the allocated memory.‬

‭Syntax‬‭:‬

‭void *calloc(size_t num_elements, size_t size);‬

‭ xample‬‭:‬
E
‭int *ptr = (int *)calloc(5, sizeof(int)); // Allocates memory for 5 integers, initialized to 0‬

realloc()‬‭(Reallocation):‬

‭‬ R
● ‭ esizes a previously allocated memory block.‬
‭●‬ ‭If the new size is larger, the new memory is uninitialized. If smaller, extra memory is‬
‭freed.‬
‭●‬ ‭Returns a pointer to the new memory block, or‬‭NULL‬‭if allocation fails.‬

‭Syntax‬‭:‬

‭void *realloc(void *ptr, size_t new_size);‬

‭ xample‬‭:‬
E
‭ptr = (int *)realloc(ptr, sizeof(int) * 10); // Resizes the memory block to hold 10 integers‬
free()‬
‭ ‭:‬

‭ ‬ ‭Deallocates previously allocated memory, making it available for reuse.‬



‭●‬ ‭It's crucial to free memory after it’s no longer needed to prevent memory leaks.‬

‭Syntax‬‭:‬

‭void free(void *ptr);‬

‭ xample‬‭:‬
E
‭free(ptr); // Frees the memory pointed by ptr‬

‭Key Points:‬

‭●‬ ‭
malloc()‬
‭: Allocates memory without initialization.‬
‭●‬ ‭
calloc()‬
‭: Allocates memory and initializes it to zero.‬
‭●‬ ‭
realloc()‬
‭: Changes the size of an allocated memory block.‬
‭●‬ ‭
free()‬
‭: Deallocates memory to avoid memory leaks.‬

‭ xample Program‬‭:‬
E
‭#include <stdio.h>‬

‭#include <stdlib.h>‬

‭int main() {‬

‭int *arr;‬

‭int i;‬

‭// Allocating memory dynamically for an array of 5 integers‬

‭arr = (int *)malloc(5 * sizeof(int));‬

‭if (arr == NULL) {‬

‭printf("Memory allocation failed\n");‬

‭return 1;‬
‭}‬

‭// Initializing values‬

‭for (i = 0; i < 5; i++) {‬

‭arr[i] = i + 1;‬

‭}‬

‭// Printing values‬

‭for (i = 0; i < 5; i++) {‬

‭printf("%d ", arr[i]);‬

‭}‬

‭// Reallocating memory to hold 10 integers‬

‭arr = (int *)realloc(arr, 10 * sizeof(int));‬

‭if (arr == NULL) {‬

‭printf("Reallocation failed\n");‬

‭return 1;‬

‭}‬

‭// Printing the updated values‬

‭for (i = 0; i < 10; i++) {‬

‭printf("%d ", arr[i]);‬

‭}‬
‭// Freeing allocated memory‬

‭free(arr);‬

‭return 0;‬

‭}‬

‭Conclusion:‬

‭ ynamic memory allocation allows flexibility in memory management during runtime. It's‬
D
‭essential to manage memory properly using‬‭ malloc()‬ calloc()‬
‭,‬‭ realloc()‬
‭,‬‭ free()‬
‭, and‬‭
‭to prevent memory leaks and optimize resource use.‬

‭49. Explain Storage classes. (static, extern, auto, register). [BCA MJ-1 2022]‬

‭Storage Classes in C‬

I‭n C, storage classes define the scope, lifetime, and visibility of variables and functions. There‬
auto‬
‭are four primary storage classes in C:‬‭ register‬
‭,‬‭ static‬
‭,‬‭ extern‬
‭, and‬‭ ‭. These affect‬
‭how variables are stored, accessed, and initialized.‬

auto‬‭Storage Class:‬

‭‬ D
● ‭ efault‬‭storage class for local variables.‬
‭●‬ ‭Variables declared with‬‭ auto‬‭are local to the function/block‬‭and have automatic storage‬
‭duration.‬
‭●‬ ‭Memory is allocated when the block is entered and deallocated when it exits.‬
auto‬‭keyword is optional as local variables‬‭are automatically considered‬
‭●‬ ‭Typically, the‬‭
auto‬
‭ ‭.‬

‭Syntax‬‭:‬

‭auto int x = 5;‬

‭ xample‬‭:‬
E
‭void function() {‬
‭auto int num = 10; // num is local to function‬
‭}‬

register‬‭Storage Class:‬

‭●‬ U ‭ sed for variables that are heavily accessed, typically used for loop counters or‬
‭frequently accessed variables.‬
‭●‬ ‭Requests the compiler to store the variable in a CPU register rather than RAM (if‬
‭possible), making it faster to access.‬
‭●‬ ‭The variable cannot be accessed by the address operator (‬‭ &‭)‬, since it may not be stored‬
‭in memory.‬

‭Syntax‬‭:‬

‭register int x;‬

‭ xample‬‭:‬
E
‭void function() {‬
‭register int i; // i may be stored in a register‬
‭for(i = 0; i < 10; i++) {‬
‭printf("%d\n", i);‬
‭}‬
‭}‬

static‬‭Storage Class:‬

‭‬ U
● ‭ sed to retain the value of a variable across function calls.‬
‭●‬ ‭Local static variables‬‭retain their value between‬‭function calls, but they are not visible‬
‭outside the function.‬
‭●‬ ‭Global static variables‬‭are restricted to the file‬‭in which they are declared (cannot be‬
‭accessed from other files).‬

‭Syntax‬‭:‬

‭static int x = 5;‬

‭ xample‬‭:‬
E
‭void counter() {‬
‭static int count = 0; // retains its value between calls‬
‭count++;‬
‭printf("%d\n", count);‬
‭}‬
‭int main() {‬
‭counter(); // Output: 1‬
‭counter(); // Output: 2‬
‭}‬

extern‬‭Storage Class:‬

‭●‬ U ‭ sed to declare a variable or function that is defined outside the current file, in another‬
‭file.‬
‭●‬ ‭Global variable‬‭declared with‬‭ extern‬‭allows access‬‭to it across multiple files.‬
‭●‬ ‭It doesn't allocate memory, just refers to an existing variable/function declared‬
‭elsewhere.‬

‭Syntax‬‭:‬

‭extern int x;‬

‭ xample‬‭:‬
E
‭// File1.c‬
‭int num = 10; // Definition of the variable‬

/‭/ File2.c‬
‭extern int num; // Reference to the variable in another file‬

‭Summary Table:‬
‭Storage‬ ‭Scope‬ ‭Lifetime‬ ‭Default Value‬
‭Class‬

‭auto‬ ‭Local to function/block‬ ‭Until the block ends‬ ‭Garbage value‬

‭register‬ ‭Local to function/block‬ ‭Until the block ends‬ ‭Garbage value‬

‭static‬ ‭ ocal (function scope) or Global‬


L ‭ or the lifetime of the‬
F ‭ ero (if‬
Z
‭(file scope)‬ ‭program‬ ‭uninitialized)‬

‭extern‬ ‭Global (accessible across files)‬ ‭ or the lifetime of the‬


F ‭ ero (if‬
Z
‭program‬ ‭uninitialized)‬
‭Conclusion:‬

‭ torage classes in C help determine the‬‭visibility‬‭,‬‭lifetime‬‭, and‬‭memory location‬‭of variables‬


S
‭and functions. Using the appropriate storage class can optimize the performance and‬
‭organization of your program.‬

‭50. Write a program to display the Fibonacci series. [ BCA MJ-1 2022]‬

‭#include <stdio.h>‬

‭void fibonacci(int n) {‬
‭int first = 0, second = 1, next;‬

‭printf("Fibonacci Series up to %d terms:\n", n);‬

‭for (int i = 0; i < n; i++) {‬


‭if (i <= 1) {‬
‭next = i; // First two terms are 0 and 1‬
‭} else {‬
‭next = first + second; // Next term is the sum of previous two‬
‭first = second; // Move to next term‬
‭second = next; // Move to next term‬
‭}‬
‭printf("%d ", next); // Print the current term‬
‭}‬
‭printf("\n");‬
‭}‬

‭int main() {‬
‭int terms;‬

/‭/ Input number of terms‬


‭printf("Enter the number of terms for Fibonacci series: ");‬
‭scanf("%d", &terms);‬

/‭/ Call the function to display Fibonacci series‬


‭fibonacci(terms);‬

‭return 0;‬
‭}‬
‭Explanation:‬

‭1.‬ ‭
fibonacci()‬‭function‬‭:‬
‭‬ T
○ n‬‭(the number of terms to display).‬
‭ akes an integer‬‭
‭○‬ ‭It uses a loop to calculate and print each term in the Fibonacci sequence.‬
‭○‬ ‭The first two terms are‬‭ 0‬‭and‬‭
1‬
‭, and subsequent terms‬‭are the sum of the‬
‭previous two.‬
‭2.‬ ‭Main function‬‭:‬
‭○‬ ‭Prompts the user to input the number of terms.‬
fibonacci()‬‭function to display the series.‬
‭○‬ ‭Calls the‬‭

‭Example Output:‬
‭ nter the number of terms for Fibonacci series: 10‬
E
‭Fibonacci Series up to 10 terms:‬
‭0 1 1 2 3 5 8 13 21 34‬

You might also like