CLanguageNotes
CLanguageNotes
[BCA-2016,2018,2019]
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.
#include
1. Preprocessor Directives: Includes header files andmacros (e.g.,
stdio.h>
< ).
.
2 Global Declarations: Defines global variables andfunction prototypes.
3. Main Function: The entry point of the program ( intmain() ), where execution
starts.
.
4 Variable Declarations: Declares variables and initializesthem as needed.
5. Statements and Logic: Contains the main logic, includingloops, conditional
statements, and function calls.
6. Functions: User-defined or library functions to organizeand reuse code.
1. W rite the Code: Create a C program using a text editor(e.g., Notepad, VS
Code) and save the file with a .cextension (e.g.,
program.c ).
2. Compile the Code: Use a C compiler likeGCC(GNU CompilerCollection) 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 thenecessary libraries and
program
produces an executable file (e.g., ).
4. Execute the Program: Run the compiled executable fromthe terminal or
command prompt.
program.exe
hese steps will compile and execute your C program, displaying the output on
T
the screen.
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:
In C, atokenis the smallest unit of a program thathas 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
, ).
. Identifiers: 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 enclosedin double quotes (e.g.,
"Hello, World!"
).
9. Explain the term variable and constants. Explain the types of constants. [BCA 2017,2019]
ariable:
V
Avariableis a named storage location in memory thatcan 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
Aconstantis a value that cannot be modified duringprogram 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 insingle quotes (e.g., ,
1'
' ).
4. String Constants: Sequences of characters enclosedin 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]
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.
ata Type:
D
Adata typein 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.
hese data types allow C programs to store and manipulate various types of data
T
efficiently.
perator:
O
Anoperatorin 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.
// Example:
printf("Hello, World!\n");
// Example:
putchar('A');
// Example:
puts("Hello, World!");
// Example:
scanf("%d", &age);
// 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]
// continue - Skips the current iteration of a loop and continues to the next
continue;
5. Explain Decision Making or Control Statement. [BCA 2018] Explain difference between
1
if-else and switch case statement.
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.
if-elseand
Difference between switch-case
:
Aspect if-elseStatement
switch-caseStatement
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).
xecution
E xecutes multiple statements for
E xecutes only one expression based
E
Flow each condition. on the condition.
Key Differences:
● if-elseis used for more complex conditions and multiplestatements.
● Ternary operatoris a more compact way of writingsimpleif-elselogic in a single line.
if-elsefor more
In summary, use theternary operatorfor 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.
// Example:
for (int i = 0; i < 5; i++) {
printf("%d ", i); // Output: 0 1 2 3 4
}
// Example:
int i = 0;
while (i < 5) {
printf("%d ", i); // Output: 0 1 2 3 4
i++;
}
// 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]
// 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.
// 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`).
In 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. */
// 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.
perfect numberis a positive integer that is equalto 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>
int main() {
int num;
return 0;
}
Explanation:
Example Output:
nter a number: 6
E
6 is a perfect number.
21. Write a program to check whether a number is prime or not. [BCA 2016,2017]
prime numberis a number greater than 1 that hasno 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>
int main() {
int num;
return 0;
}
Explanation:
prime numberis a number greater than 1 that hasno 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>
int main() {
int num;
return 0;
}
Explanation:
Example Output:
nter a number: 7
E
7 is a prime number.
return fact;
}
int main() {
int num;
return 0;
}
Explanation:
● T he factorial(int num)function now returns an inttype. 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
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
narrayin C is a collection of variables of thesame 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.
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).
1. T ype of Elements: All elements in an array must beof the same data type (e.g., all
integers, all floats).
2. Array Size: The size of the array must be specifiedduring 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 usingzero-based indexing (i.e., the
first element is at index0 1,etc.).
, the second element atindex
4. Memory Allocation: The size of the array determineshow much memory will be
allocated to store its elements.
int main() {
// Declaring a one-dimensional array of integers with 5 elements
int arr[5];
return 0;
}
Explanation:
i
● nt arr[5];declares an integer array arrwith 5 elements.
● Each element of the array is assigned a value.
forloop is used to print the elements of the array.
● A
Summary:
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]
Types of Arrays:
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 elementscauses errors.
Arrays are essential in C but have limitations in flexibility and dynamic use.
Two-Dimensional Array in C
emory
M lements are stored in contiguous R
E ows are stored as 1D arrays in
Layout memory. contiguous memory.
●
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.
int main() {
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
return 0;
}
Explanation:
Output:
lements of the 2D array are:
E
1 2 3
4 5 6
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;
int matrix[n][n];
int leftDiagonalSum = 0, rightDiagonalSum = 0;
return 0;
}
Explanation:
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];
return 0;
}
Explanation:
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?
P
● urpose: Returns the length of a string (excludingthe 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
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
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;
}
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.
P
● urpose: Finds the first occurrence of a characterin 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;
}
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!
P
● <string.h>in standard C.)
urpose: Reverses a string.(Note: Not part of
● Example:
include <stdio.h>
#
#include <string.h>
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
strrev( R
everses a string Custom implementation required.
)
(non-standard).
These string functions are widely used in C for string manipulation tasks.
int main() {
char str[100];
int length, isPalindrome = 1;
return 0;
}
Explanation:
1. Input:
○ The program takes a string as input from the user.
strarray.
○ The input string is stored in the
2. Palindrome Check:
forloop, it compares characters from thebeginning (
○ Using a str[i]
) with
corresponding characters from the end (
str[length
- i - 1]
).
○ If any pair of characters do not match, the isPalindromeflag 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.
Input 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;
return 0;
}
Explanation:
1. Input:
○ The program uses fgets()to read a string from theuser, allowing spaces to be
included.
2. Processing:
forloop.
○ 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 vowelscounter is
), the
incremented.
■ If the character is an alphabet (checked using ASCII values) but not a
vowel, it is counted as a consonant.
■ If the character is a space (
' ' whiteSpacescounter 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;
}
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, includingspaces, with buffer overflow
protection.
● Syntax: fgets(str, size, stdin);
● Key Points:
○ Stops reading after a newline (
\n) or when the bufferis 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 anewline (
\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 outputwithout 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;
}
scanf() R
eads a single No No Moderate
word
gets()
Reads a line Yes No Unsafe
fgets() Reads a line
Yes No Safe
puts()
Prints a string N/A Yes Safe
Key Notes:
int main() {
char str[100];
int length = 0;
return 0;
}
Explanation:
1. Input:
○ The program uses fgets()to read a string from theuser, allowing spaces and
limiting the input to the buffer size.
2. Processing:
○ The forloop iterates through each character of thestring.
○ It checks for the null terminator (
\0
) to determinethe end of the string.
A condition ensures the newline character (
○ \n
) isnot 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()
.
include <stdio.h>
#
#include <string.h>
int main() {
char str1[100], str2[100];
int result;
return 0;
}
Explanation:
1. Input:
fgets()to input two strings, allowingspaces in the input.
○ The program uses
strcspn()function is used to remove the newlinecharacter (
○ 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 smallerthan the second.
■
> 0
: The first string is lexicographically greaterthan 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.
Input 2:
Enter the first string: hello
Enter the second string: hello
utput 2:
O
The strings are equal.
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 functionsprovided by C libraries.
2. User-defined Functions: Functions created by the programmer.
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.
include <stdio.h>
#
#include <string.h>
int main() {
char str[] = "Hello";
printf("Length of string: %lu\n", strlen(str)); // Library function
return 0;
}
#include <stdio.h>
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 functionis 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 callsitself with a modified argument.
●
n! = n * (n - 1) * (n - 2) * ... * 1
0! = 1
● Base case:
C Program:
#include <stdio.h>
int main() {
int number, result;
return 0;
}
Explanation:
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]
In C, when a function is called, the arguments passed to the function can be handled in two
different ways:Call by ValueandCall by Reference.
● InCall by Value, a copy of the actual argument'svalue 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.
● Modificationsmade to the parameter inside the functiondo not affectthe original
variable outside the function.
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:
Output:
efore modifyValue: 5
B
Inside modifyValue: 10
After modifyValue: 5
● InCall by Reference, instead of passing a copy ofthe variable, thememory address
(reference) of the actual argument is passed to the function. This means the function
works directly with the original variable.
● Modificationsmade to the parameter inside the functionaffect the actual variable
outside the function.
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:
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).
Example odifyValue(x)(where
m xis odifyValue(&x)(where
m xis passed
passed by value) by reference)
Summary:
C
● all by Valueis safer because it prevents modification of the original data.
● Call by Referenceis more efficient when working withlarge data structures or when you
need to modify the original variable in the calling function.
In 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 asscope,visibility,
andlifetimeof a variable. Let's discuss each one:
● L
ocal Scope: A variable declared inside a functionor block (enclosed by {}) islocally
scoped. It can only be accessed within that functionor 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 ) isglobally scoped. It can be accessed from any function in the
program.
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 ablock(e.g., loops, if statements) hasblock
scopeand 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
● L ocal Variables: Only visible inside the functionor block where they are declared. They
cannot be accessed by other functions or blocks.
● Global Variables: Visible throughout the program aftertheir 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 externkeyword 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 ofextern:
// file1.c
#include <stdio.h>
int main() {
printf("%d", x); // x can be accessed here
return 0;
}
// file2.c
int x = 10; // Define the global variable x
helifetimeof a variable refers to how long thevariableexistsin memory during the execution
T
of a program. The lifetime of a variable is determined by where and how it is declared.
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.
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 inthe program.
● Visibility: Determines where the variable can be referenced.
● Lifetime: Defines how long a variable exists in memoryduring 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]
pointerin C is a variable that stores the memoryaddress 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:
2. Initialization: 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
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>
return flag;
}
int main() {
int num;
int *ptr = # // Pointer to the integer num
// Input a number
printf("Enter a number: ");
scanf("%d", ptr); // Using pointer to store the input
return 0;
}
Example Input/Output:
Input:
Enter a number: 17
utput:
O
17 is a prime number.
Input:
Enter a number: 20
utput:
O
20 is not a prime number.
Summary of Pointers:
A
● pointeris a variable that stores the memory addressof another variable.
● Pointers are declared with a *symbol, and they areinitialized using the address-of
&
operator.
● In 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]
pointerin C is a variable that stores the memoryaddress 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.
1. D ynamic Memory Allocation: Pointers are used to allocatememory dynamically during
program execution using functions like malloc() calloc()
, free()
,and .
2. Passing Arguments to Functions by Reference: By passingthe 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 toaccess and manipulate arrays, as
array names in C are essentially pointers.
4. Function Pointers: Pointers can be used to point tofunctions, enabling dynamic
function calls.
5. Linked Data Structures: Pointers are used in implementingdynamic data structures
like linked lists, stacks, queues, and trees.
int main() {
int num, fact;
int *nPtr = # // Pointer to num
int *factPtr = &fact; // Pointer to fact
return 0;
}
Example Input/Output:
Input:
Enter a number: 5
utput:
O
Factorial of 5 is 120
Summary:
P
● ointersare variables that hold the memory addressof 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.
narray of pointersis an array where each elementof 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.
<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.
●
sizeis the number of elements in the array.
For example:
#include <stdio.h>
int main() {
int num1 = 10, num2 = 20, num3 = 30, num4 = 40;
return 0;
}
int *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
1. S toring Addresses of Multiple Variables: You can storethe 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:
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 elementis 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>
int main() {
struct Student students[5]; // Array of 5 students
int i;
return 0;
}
Example Input/Output:
Input:
Enter details of 5 students:
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 thiscase, a student).
scanf()for reading numbers and
● Input: The program uses fgets()for reading
strings with spaces.
printf()to display thestudent records in a structured
● Display: The program uses
format.
unionin C is a special data type that allows storingdifferent 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>
int main() {
union Data data; // Declare a variable of type union Data
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;
}
● M emory Efficiency: Unions save memory because theyallow 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 valueof 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.
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.
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 charbut not
, or marksfor a student.
and
simultaneously.
Summary:
● U nion: A union allows multiple members of differentdata 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 typesin 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 aunionis used for memory efficiency when onlyone value is needed at a time, a
W
structureis 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]
Structures and arrays are both used to store data, but they have some fundamental differences:
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
).
Array of Structures:
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.
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);
}
return 0;
}
Explanation:
Nesting of Structures:
Syntax:
struct <outer_structure> {
<structure_type> inner_structure;
// other members
};
xample of Nesting of Structures:
E
#include <stdio.h>
int main() {
struct Student student1;
return 0;
}
Explanation:
Key Differences:
Feature Array of Structures Nesting of Structures
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 multipleinstances of the same type of structure
in an array.
● Nesting of Structures: Allows you to define a structurewithin 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 mostcommonly used preprocessor directives in
preprocessor that start with the
#define
C are #include
, #ifdef
, #ifndef
, #if
, and .
#defineDirective:
1.
he
T #definedirective is used to definemacrosorconstantsthat 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
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 :
#define
When to Use :
#includeDirective:
2.
he
T #includedirective is used to include header filesinto 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
int main() {
printf("Hello, World!\n");
return 0;
}
#include
Explanation of :
#include
When to Use :
#defineand
Key Differences Between #include
:
Directive Purpose When to Use
#define D
efines constants or macros that are se
U #defineto declare constants or
replaced by the preprocessor before create macros that are used throughout
compilation. the program.
int main() {
int numbers[MAX]; // Array with size MAX (100)
return 0;
}
Explanation:
Summary:
● #define : Used to define constants or macros. It helpsin making the code more
readable and reusable by substituting values and expressions at compile-time.
● #include : Used to include external files (standardor user-defined header files). It
allows you to use predefined functions, constants, and other structures from libraries in
your program.
#defineand
oth
B #includeare essential preprocessordirectives that help in making the
code more modular, maintainable, and efficient.
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.
Advantages:
. C
1 ode Reusability: Reuse code or expressions withoutrewriting them.
2. Efficiency: Faster execution as they are replacedduring preprocessing.
3. Readability: Improves readability and maintainability by using meaningful names for
constants.
Disadvantages:
. D
1 ebugging: Difficult to debug due to lack of typechecking and no runtime information.
2. Global Replacement: Macros are replaced throughoutthe 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
return 0;
}
Key Points:
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).
fopen()
:
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:
fclose()
:
Syntax:
xample:
E
fclose(file);
fread()
:
yntax:
S
size_t fread(void *buffer, size_t size, size_t count, FILE *file);
xample:
E
char buffer[100];
yntax:
S
size_t fwrite(const void *buffer, size_t size, size_t count, FILE *file);
xample:
E
char data[] = "Hello, World!";
fgetc()
:
yntax:
S
int fgetc(FILE *file);
xample:
E
char ch = fgetc(file);
fputc()
:
yntax:
S
int fputc(int char, FILE *file);
xample:
E
fputc('A', file);
fgets()
:
yntax:
S
char *fgets(char *str, int n, FILE *file);
xample:
E
char line[100];
fputs()
:
yntax:
S
int fputs(const char *str, FILE *file);
xample:
E
fputs("Hello, World!", file);
feof()
:
yntax:
S
int feof(FILE *file);
xample:
E
if (feof(file)) {
}
fseek()
:
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()
:
yntax:
S
long int ftell(FILE *file);
xample:
E
long int position = ftell(file);
rewind()
:
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;
return 1;
}
fclose(file);
return 1;
}
char ch;
}
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.
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.
<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:
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, orNULLif allocation fails.
Syntax:
xample:
E
ptr = (int *)realloc(ptr, sizeof(int) * 10); // Resizes the memory block to hold 10 integers
free()
:
Syntax:
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;
return 1;
}
arr[i] = i + 1;
}
}
printf("Reallocation failed\n");
return 1;
}
}
// 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
In 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.
autoStorage Class:
D
● efaultstorage class for local variables.
● Variables declared with autoare local to the function/blockand have automatic storage
duration.
● Memory is allocated when the block is entered and deallocated when it exits.
autokeyword is optional as local variablesare automatically considered
● Typically, the
auto
.
Syntax:
xample:
E
void function() {
auto int num = 10; // num is local to function
}
registerStorage 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:
xample:
E
void function() {
register int i; // i may be stored in a register
for(i = 0; i < 10; i++) {
printf("%d\n", i);
}
}
staticStorage Class:
U
● sed to retain the value of a variable across function calls.
● Local static variablesretain their value betweenfunction calls, but they are not visible
outside the function.
● Global static variablesare restricted to the filein which they are declared (cannot be
accessed from other files).
Syntax:
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
}
externStorage Class:
● U sed to declare a variable or function that is defined outside the current file, in another
file.
● Global variabledeclared with externallows accessto it across multiple files.
● It doesn't allocate memory, just refers to an existing variable/function declared
elsewhere.
Syntax:
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
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;
int main() {
int 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 0and
1
, and subsequent termsare 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