IP Question Bank With Answers (2024-2025)
IP Question Bank With Answers (2024-2025)
2 MARKS
1. Define Identifier
2. Define Keyword.
3. What Are Data Types?
4. List Out Any Ten Data Types.
5. What Is Meant By Constants?
6. Define Variables.
7. What Is Meant By Expressions?
8. Define Statements? What Is Meant By Operators?
9. What Is Meant By Linking Process?
10. Define Void?
2MARKS
5 MARKS
2 MARKS
1. What Is An Array? How A Single Dimension And Two Dimension Arrays Are Declared
And Initialized?
2. Define String ? Discuss The Various String Handling Functions In C ?
3. Write A Program To Find Given String Is Palindrome Or Not.?
4. Write A Program To Multiply Two Matrices Of Order ‘Mxn’ And ‘Nxl’ ?
5. Explain The Memory Model Of Two Dimensional Array?
6. Write A Program To Perform Addition Of Two Matrices ?
7. Write A Program To Perform Linear Search?
5 MARKS
5 MARKS
1. Demonstrate The Use Of Fread( ) And Fscanf( ) For Reading Sequentially From A Disk.
2. Write A Program To Open A File And Read The File And Print The File Contents .
3. Explain About The Functions For Reading And Writing Data From A File.
4. Write A C Program To Print File Contents In Reverse Order.
5. Discuss in detail about pointer arithmetic. Support the answer with appropriate examples.
6. Define a pointer. How to initialize and declare pointer variables? Explain the same with
examples.
7. Elaborate the importance of dynamic memory allocation with example.
8. How pointers are used to declare single and multi-dimension arrays with examples?
9. What is pointer? Explain array of pointers with example.?
Unit-1
12. Explain in detail the structure of C Program and procedure to create, compile and run
the C program.
structure of C Program:
The program written in C language follows this basic structure. The sequence of sections should beas
they are in the basic structure. A C program should have one or more sections but the sequence of
sections is to be followed.
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section
5. Main function section
{
Declaration
section
Executable
section
}
6. Sub program or function section
1. Documentation Section:-
This comes first and is used to document the use of logic or reasons in your program. It
can be used to write the program's objective, developer and logic details. The
documentation is done in Clanguage with /* and */. Whatever is written between these two
are calledcomments.
2. Linking Section:-
This section tells the compiler to link the certain occurrences of keywords or functions in
your program to the header files specified in this section.
e.g. #include <stdio.h>
3. Definition Section:-
It is used to declare some constants and assign them some value.
e.g. #define MAX 25
Here #define is a compiler directive which tells the compiler whenever MAX is
found inthe program, replace it with 25.
Here the variables which are used throughout the program (including main and
other functions)are declared so as to make them global(i.e accessible to all parts of
program)
e.g. int i; (before main())
4. Main Function Section :-
This has all the sub programs or the functions which our program needs.
* Dereference Operator
12 || Logical OR Left-to-Right
= Assignment
o Efficiency: C allows for direct memory manipulation and low-level access to system resources.
This results in highly efficient code execution.
o Portability: C code can be easily ported to different platforms without major modifications,
thanks to its wide availability of compilers and libraries.
o Speed: C is known for its fast execution speed, making it suitable for developing performance-
critical applications.
o Control: C gives programmers fine-grained control over memory management and system
resources.
Compatibility: C code can be easily integrated with code written in other languages like C++,
Java and etc
Variables
□ Variables are containers for storing data values, like numbers and characters.
□ Variable is a name given to memory location that holds a value.
□ variable is a name of the memory location. It is used to store data. Its value can be
changed, and itcan be reused many times.
Variable decleration:
Syntax :
datatype
Eg: int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
Variable initialization
Datatype variable_name= value;
putchar() :
The putchar() writes the character type data to the output file stdout(screen). It is used to
print one character at a time.
Syntax:
Putchar(Variable_name);
gets ( )
The gets() is used to read string from standard input file stdin and places it into some
buffer which the programmer must provide. The gets() stops reading when an enter key is
pressed or EOF is reached.
Syntax:
gets(variablename);
puts () :
The puts() is used to send the string to the output file stdout, until it finds a NULL end of
string marker. The NULL is not written, instead the newline character is written to the
output stdout.
Syntax:
puts(variablename);
Example:
int x;
float y;
scanf (“%d % f “, &x, &y);
Control string
It tells the function the type of data being Input and uses the same control sequences as the printf()
function.
It enclosed with double quotes (“ “).
It specifies the type of values that have to be read from keyboard. Control string consists of
format specification.
Example:
Integer - %d Float - %f double - %lf long double - %Lf char - %c
scanf() reads the characters from standard input and interprets them according to the
format string specification. It stops reading when it encounters a space or when some
input fails to match with the conversion specification.
2. . printf() :
The printf() prints all types of data value to the standard output(typically the screen). It
requires a conversion symbol and variable name to print the data. The printf() is part of
every C compiler. Its header file is stdio.h.
Syntax:
The first argument is the format string which is composed of ordinary characters and
conversion specification. This is followed by zero or more optional arguments.
Control String
1. Format Specifier given in the form of % specifier.
2. Escape sequence characters such as \n (new line) \t(tab).
3. It can have a string that must be printed on the monitor.
The format of numbers displayed by printf() can be controlled by field with specifiers included as
part of each conversion control sequence.
printf(“sum of %.3d and %4d is %5d”,6,15,21);
Output: sum of 6 and 5 is 21
The value of a = 10
148
Float point
%5.2f – 42.30
%5.2f – 142.36
%10.3f – 25.670
Format Modifier (modifiers for printf formats)
A format specification can also include “modifiers” that can control how much of the item’s
values is printed and how much space it gets.
The modifiers come between the % and the format control letter.
Justification
It controls the placement of a value when it is shorter than the specified width.
Justification can be left or right. The format modifier (-) minus is used.
Left Justification
A format specification has (-) minus sign used before the width modifier says to left justify the
argument within its specified width.
Example: printf(“%-10d”,59);
Output: 59
Output:
right
left
abcd
abcd
Usually the format string is enclosed with the double quotation marks in both scanf ()
and printf().
4. Discuss about the Various operators with example program. Operators:
Operators can be defined as the symbols that help us to perform specific mathematical, relational,
bitwise, conditional, or logical computations on operands. In other words, we can say that an operator
operates the operands.
For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands. The addition
operator tells the compiler to add both of the operands ‘a’ and ‘b’. The functionality of the C
programming language is incomplete without the use of operators.
1. Arithmetic operators
2. Increment and decrement operators
3. Relational operators
4. Logical operators
5. Bitwise operators
6. Assignment operators
7. Conditional operators
8. Special operators
1. Arithmetic Operators : The C language supports all the basic arithmetic operators suchas
addition, subtraction, multiplication, division, etc.
Output:
Addition of a and b = 73
Subtraction of a and b = 27
Multiplication of a and b = 1150
Division of a and b = 2
modulus of a and b = 4
When we use the increment and decrement operator as a prefix (means before the operand), then,
first the increment operation is done and that value is used, like in the first two printf() functions,
we get the updated values of a and b.
Whereas when we use the increment and decrement operators as postfix (means after the
operand), then, first the larger expression is evaluated which is printf() in this case and then the
value of the operand is updated.
#include <stdio.h>
int main()
{
return 0;
Output:
Incrementing value of a = 11
Decrementing value of b = 19
Decrementing value of a = 11
Value of a = 10
Incrementing value of b = 19
Value of b = 20
The relational operators (or comparison operators) are used to check the relationship between two
operands.
It checks whether two operands are equal or not equal or less than or greater than, etc.
It returns 1 if the relationship checks pass, otherwise, it returns 0.
When we use relational operators, we get the output based on the result of the comparison.
If it's true, then the output is 1 and if it's false, then the output is 0.
Example
Operator Description (a and b, where a = 10 and b =
11)
#include <stdio.h>
int main()
{
int a = 10, b = 20, result;
// Equal
result = (a==b);
printf("(a == b) = %d \n",result);
// less than
result = (a<b);
printf("(a < b) = %d \n",result);
return 0;
Output:
(a == b) = 0
(a < b) = 1
(a > b) = 0
(a <= b) = 1
4. Logical Operators :
Example
Operator Description
(a and b, where a = 1 and b = 0)
|| Logical OR a || b, returns 1
These operators are used to perform logical operations and are used with conditional statements like if
else.
1. With the AND operator, only if both operands are true, the result is true.
2. With the OR operator, if a single operand is true, then the result will be true.
3. The NOT operator changes true to false, and false to true.
#include <stdio.h>
int main() {
int a = 1, b = 0, result;
// And
result = (a && b);
printf("a && b = %d \n",result);
// Or
result = (a || b);
printf("a || b = %d \n",result);
// Not
result = !a;
printf("!a = %d \n",result);
return 0;
Output:
a && b = 0
a || b = 1
!a = 0
5. Bitwise operators:
Bitwise operators perform manipulations of data at the bit level.
These operators also perform the shifting of bits from right to left.
Bitwise operators are not applied to float or double, long double, void, etc.
There are 6 bitwise operators in C programming.The
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
~ One’s complement
>> Shift Right
<< Shift Left
we have a truth table for showing how these operators work with different values.
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Bitwise operators can produce any arbitrary value as a result. It is not mandatory that the result will either
be 0 or 1.
The bitwise shift operator shifts the bit value, either to the left or right.
The left operand specifies the value to be shifted and the right operand specifies the number of
positions that the bits in the value have to be shifted.
Both operands have the same precedence.
Understand, how bits shift from left to right and vice versa.
a = 00010000
b=2
a << b = 01000000
a >> b = 00000100
In case of a << b, 2 bits are shifted to left in 00010000 and additional zeros are added to the opposite end,
that is right, hence the value becomes 01000000
And for a >> b, 2 bits are shifted from the right, hence two zeros are removed from the right and two are
added on the left, hence the value becomes 00000100
Please note, shift doesn't work like rotating, which means, the bits shifted are not added at the other end.
The bits that are shifted are lost.
#include <stdio.h>
int main()
{
int a = 0001000, b = 2, result;
// <<
result = a<<b;
printf("a << b = %d \n",result);
// >>
result = a>>b;
printf("a >> b = %d \n",result);
return 0;
}
Output:
a << b = 2048
a >> b = 128
6. Assignment Operators:
The assignment operators are used to assign value to a variable.
For example, if we want to assign a value 10 to a variable x then we can do this by using the
assignment operator like: x = 10; Here, = (equal to) operator is used to assign the value.
In the C language, the = (equal to) operator is used for assignment however it has several other
variants such as +=, -= to combine two operations in a single statement.
Example
Operator Description (a and b are two variables, with
where a=10 and b=5)
When we combine the arithmetic operators with the assignment operator =, then we getthe
shorthand form of all the arthmetic operators.
#include <stdio.h>
int main()
{
int a = 10,b=30,c=10;
// += operator
a += 20;
printf("result = %d \n",a);
// -= operator
b -= 5;
printf("result = %d \n",b);
// *= operator
c *= 10;
printf("result = %d \n",c);
return 0;
}
Output:
result = 30
result = 25
result = 100
#include <stdio.h>
int main()
{
printf("result = %d",result);
return 0;
}
Output:
result = 40
sizeof operator is used to find size of any entity(variable, array, etc.), & operator to find the address of a
variable, etc. You can see a list of such operators in the below table.
#include <stdio.h>
int main()
{
int a = 20;
char b = 'B';
double c = 17349494.249324;
// sizeof operator
printf("Size of a is: %d \n", sizeof(a));
printf("Size of b is: %d \n", sizeof(b));
printf("Size of c is: %d \n", sizeof(c));
// & operator
printf("Memory address of a: %d \n", &a);
return 0;
}
Output:
Size of a is: 4
Size of b is: 1
Size of c is: 8
Memory address of a: -1254020756
Data Types:
Atype defines a setofvalues and a setofoperations that can be applied onthose values.
The data type specifies the size and type of information the variable will store.
The integer datatype in C is used to store the integer numbers(any number including positive, negative
and zero without decimal part). Octal values, hexadecimal values, and decimal values can be stored in
int data type in C.
The storage size of int data type is 2 or 4 or 8 byte.
It varies depend upon the processor in the cpu that we use.
If we are using 16 bitprocessor, 2 byte(16 bit) of memory will be allocated for int data type.
like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memoryfor 64 bit
processor is allocated for int datatype.
int (2 byte) can store values from -32,768 to +32,767
int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
Syntax of Integer
We use int keyword to declare the integer variable:
int var_name;
1. unsigned int: Unsigned int data type in C is used to store the data values from zero to positive
numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768 to 32,767.
3. long int: Larger version of the int datatype so can store values greater than int.
4. unsigned short int: Similar in relationship with short int as unsigned int with int.
Program:
#include <stdio.h>
int main()
{
Output:
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998
Syntax of char
The char keyword is used to declare the variable of character type:
char var_name;
program:
#include <stdio.h>
int main()
{
char a = 'a';
char c ;
a++;
printf("Value of a after increment is: %c\n", a);
/*c is assigned ASCII value which corresponds to the character 'c' , a-->97 b-->98 c-->99 here c will
be printed.*/
c = 99;
return 0;
}
Output
Value of a: a
Value of a after increment is: b
Value of c: c
Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;
program:
#include <stdio.h>
int main()
{
float a = 9.0f;
float b = 2.5f;
// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);
return 0;
}
Output
9.000000
2.500000
0.000200
4.Double Data Type
A Double data type in C is used to store decimal numbers (numbers with floating point values) with
double precision.
It is used to define numeric values which hold numbers with decimal values in C.
□ Range: 1.7E-308 to 1.7E+308
□ Size: 8 bytes
□ Format Specifier: %lf
Syntax of Double:
The variable can be declared as double precision floating point using the double keyword:
double var_name;
printf("%lf\n", a);
int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;
printf("%lf\n", b);
printf("%lf", c);
return 0;
}
Output:
123123123.000000
12.293123
2312312312.123123
float 4 %f
1.2E-38 to 3.4E+38
double 8 %lf
1.7E-308 to 1.7E+308
1. Integer constants:
Decimal Constants:
A whole number represented in base 10 is known as a decimal constant. It has digits that range
from 0 to 9. Declaring a decimal constant has a simple syntax that just requires the value to be written.
Example:
#include <stdio.h>
int main()
{
int decimal = 42;
printf("The decimal constant is: %d\n", decimal);
return 0;
}
Output:
A base 8 value is represented by an octal constant. It is prefixed with a '0' (zero) to show that it is an
octal constant and has digits ranging from 0 to 7.
Example:
#include <stdio.h>
int main()
{
int octal = 052; // Octal representation of decimal 42
printf("The octal constant is: %o\n", octal);
return 0;
}
Output:
Example:
#include <stdio.h>
int main()
{
int hexadecimal = 0x2A; // Hexadecimal representation of decimal 42
printf("The hexadecimal constant is: %x\n", hexadecimal);
return 0;
}
Output:
#include <stdio.h>
int main()
{
float real = 3.14;
printf("The real constant is: %f\n", real);
return 0;
}
Output:
2. Character Constant:
Example:
#include <stdio.h>
int main()
{
char character = 'A';
printf("The character constant is: %c\n", character);
return 0;
}
Output:
A sequence of zero or more characters wrapped in double quotes is represented by a string constant. It
is a character array that ends with the null character \0.
Example:
“ “ // a null string
“h”
“computer”
“wide characters”
Example:
#include <stdio.h>
int main()
{
char string[] = "Hello, World!";
printf("The string constant is: %s\n", string);
return 0;
}
Output:
The string constant is: Hello, World!
To define constant in C:
There are two ways to define constant in C programming.
1. const keyword
2. #define preprocessor
Syntax:
eg: const float PI=3.14; // Now, the value of PI variable can't be changed.
Program:
#include<stdio.h>
Output:
If you try to change the the value of PI, it will render compile time error.
#include<stdio.h>
int main()
{
const float PI=3.14;
PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
Compile Time Error: Cannot modify a const object
Syntax:
Example program:
#include <stdio.h>
#define PI 3.14
int main()
{
printf("%f",PI);
return 0;
}
Output:
3.140000
□ Decision Diamond symbol represents a decision point. Decision based operations such as
yes/no question or true/false are indicated by diamond in flowchart.
□ Connectors: Whenever flowchart becomes complex or it spreads over more than one page,
it is useful to use connectors to avoid any confusions. It is represented by a circle.
□ Flow lines: Flow lines indicate the exact sequence in which instructions are executed.
Arrows represent the direction of flow of control and relationship among different symbols
of flowchart.
Disadvantages of Flowchart:
□ It is difficult to draw flowcharts for large and complex programs.
□ There is no standard to determine the amount of detail.
□ Difficult to reproduce the flowcharts.
□ It is very difficult to modify the Flowchart.
□ Making a flowchart is costly.
□ Some developer thinks that it is waste of time.
□ It makes software processes low.
□ If changes are done in software, then the flowchart must be redrawn
Example : Draw a flowchart to input two numbers from the user and display thelargest
Totally it takes '4n+4' units of time to complete its execution and it is Linear Time Complexity.
If the amount of time required by an algorithm is increased with the increase of input value then that
time complexity is said to be Linear Time Complexity.
Space complexity is usually referred to as the amount of memory consumed by the algorithm.
When we design an algorithm to solve a problem, it needs some computer memory to complete its
execution. For any algorithm, memory is required for the following purposes...
Total amount of computer memory required by an algorithm to complete its execution is called as space
complexity of that algorithm.
To calculate the space complexity, we must know the memory required to store different datatype values
(according to the compiler).
1. 2 bytes to store Integer value.
2. 4 bytes to store Floating Point value.
3. 1 byte to store Character value.
4. 6 (OR) 8 bytes to store double value.
If the amount of space required by an algorithm is increased with the increase of input value, then that
space complexity is said to be Linear Space Complexity.
Memory Unit:
Memory Unit is an essential part of the computer system which is used to store data and instructions
before and after processing.
There are two types of memory units:
1. Primary memory/Main memory
2. Secondary memory/Auxiliary memory
Primary Memory: Primary memory cannot store a vast amount of data.
The data stored in the primary memory is temporary. The data will be lost if they are disconnected from
the power supply.
Primary-storage is a fast-memory that operates at electronic-speed. Programs must be stored in the memory while they
are being executed.
Primary memory is also known as the Main Memory or temporary memory. Random Access Memory
(RAM) is an example of Primary memory.
Secondary Memory:
Secondary memory is also known as the Auxiliary Memory or permanent storage.
Secondary-storage is used when large amounts of data & many programs have to be stored.
The data stored in the secondary memory is safe even when there is a power failure or no power supply.
Hard Disk is usually considered a secondary memory.
Eg: Magnetic disks and optical disks(CD-ROMs).
2 MARKS
1. Naming rules:
o Must start with a letter (A-Z or a-z) or an underscore (_).
o Can contain letters, digits (0-9), and underscores.
o Cannot start with a digit.
o Cannot be a reserved keyword (e.g., if, while, class).
2. Case-sensitive:
o Identifiers are case-sensitive in most programming languages (e.g., myVariable and
myvariable would be considered different).
3. Descriptive:
o Good identifiers typically reflect the purpose of the variable or function, such as
totalAmount or calculateSum.
1. Start with a letter or an underscore: An identifier must begin with either a letter (A-Z, a-z)
or an underscore (_).
o Example: total, _count, sum
2. Contain letters, digits, and underscores: After the first character, the identifier can contain
letters, digits (0-9), and underscores.
o Example: total_amount, age2
3. Cannot start with a digit: Identifiers cannot begin with a digit.
o Example: 2ndName is invalid.
4. Cannot be a reserved keyword: Identifiers cannot be names of C's reserved keywords like int,
float, if, while, etc.
5. Case-sensitive: C is case-sensitive, meaning Total and total would be treated as different
identifiers.
6. Length: Although the standard allows identifiers to be quite long, only the first 31 characters
are significant in some older compilers. However, modern compilers generally support longer
identifiers.
In C programming, a keyword is a reserved word that has a predefined meaning and purpose
in the language. Keywords are part of the syntax of the language and cannot be used as
identifiers (such as variable names, function names, etc.). They are the building blocks of the
C programming language and are used to define the structure of a program.
Characteristics of Keywords in C:
1. Predefined meaning: Each keyword has a specific function, such as defining data types,
controlling program flow, and declaring functions or variables.
2. Reserved words: Keywords are reserved, meaning they cannot be redefined or used as
identifiers (e.g., variable or function names).
3. Case-sensitive: Keywords are always lowercase in C, and using uppercase (or a mix) will
result in a syntax error.
#include <stdio.h>
int main() {
int num = 10; // 'int' is a keyword for declaring integer variables
if (num > 5) { // 'if' is a keyword for conditional statements
printf("Number is greater than 5\n");
}
return 0; // 'return' is a keyword to return a value from a function
}
In C programming, data types define the type of data that a variable can hold. They specify
the size, range, and operations that can be performed on the data stored in a variable. Data
Example:
int x = 5; // 4 bytes
short y = 10; // 2 bytes
long z = 1000; // 4 or 8 bytes
long long w = 1000000; // 8 bytes
Floating-Point Types: Used to represent real numbers (numbers with decimal points).
o float: Single-precision floating-point (usually 4 bytes).
o double: Double-precision floating-point (usually 8 bytes).
o long double: Extended precision floating-point (typically 12 or 16 bytes).
Example:
Example:
o unsigned versions of these data types are available, where the values can only be non-
negative. For example, unsigned int, unsigned char, unsigned long.
These are types that are derived from the basic data types. They include:
c
Copy code
int a = 10;
int *ptr = &a; // Pointer to an integer
Structures: A user-defined data type that groups different types of data together.
c
Copy code
struct Person {
char name[50];
int age;
};
Unions: Similar to structures, but they allow storing different data types in the same
memory location.
union Data {
int i;
float f;
char str[20];
};
These data types are created by the programmer using the typedef keyword, structures, unions,
or enums. They allow more flexibility and organization in code.
The void data type represents the absence of a value. It is used in functions that do not return a
value (i.e., void functions), or to indicate that a pointer can point to any data type (void *).
Example:
void printMessage() {
printf("Hello, World!\n");
}
These are just a few examples. C has more variations and combinations of data types, like
pointers, arrays, structures, and unions, that extend its flexibility.
In C programming, constants refer to fixed values that cannot be altered during the execution
of a program. Once a constant is assigned a value, it remains unchanged throughout the
In C programming, a variable is a name given to a memory location that holds data which can
be modified during the execution of the program. Variables are used to store values that can be
changed as the program runs, such as numbers, characters, or more complex data structures.
1. Data Type: Every variable has a specific data type that defines what kind of data it can store
(e.g., int, float, char).
2. Name: A variable is identified by a name, which follows the rules of identifiers in C (e.g., it
cannot start with a number and cannot be a keyword).
3. Value: A variable holds a value, which can be changed during the program execution.
A variable in C is declared by specifying its data type followed by its name (and optionally
initializing it with a value). The syntax for declaring a variable is:
data_type variable_name;
or
1. Local Variables: Variables that are declared inside a function or a block (e.g., within
curly braces {}). They are only accessible within that function or block.
o Example:
void myFunction() {
int x = 5; // 'x' is a local variable, only accessible inside myFunction
}
2. Global Variables: Variables declared outside of all functions, usually at the top of the
program. They are accessible by all functions in the program.
o Example:
void myFunction() {
printf("%d", globalVar); // 'globalVar' can be accessed here
}
3. Static Variables: Variables declared using the static keyword, which retain their value
between function calls. They have a local scope but are not destroyed when the
function ends.
void counter() {
static int count = 0; // Static variable, retains its value
count++;
printf("%d\n", count); // Prints 1, 2, 3, etc. on subsequent calls
}
4. External Variables: These are variables that are declared in another file or outside of
the current file, typically with the extern keyword.
o Example:
// In another file:
extern int x;
When you declare a variable, you can initialize it (i.e., assign a value to it) either at the time of
declaration or later in the program.
int a;
a = 10; // 'a' is assigned the value 10 later
Variable Scope and Lifetime:
Scope refers to the region of the program where a variable is accessible. Local variables are
only accessible within the function they are declared in, while global variables are accessible
throughout the program.
Lifetime refers to the duration a variable exists in memory during the execution of the program.
Local variables are created and destroyed each time a function is called, while global and static
variables persist for the entire program runtime.
Example Program:
#include <stdio.h>
void display() {
int localVar = 50; // Local variable
printf("Local variable: %d\n", localVar);
printf("Global variable: %d\n", globalVar);
}
int main() {
display();
return 0;
}
In this example:
Conclusion:
Variables are essential in C programming because they hold values that can change as the
program runs. Understanding how to declare, initialize, and use variables is fundamental to
writing functional programs in C.
Evaluated to a value: An expression always results in a value of a specific data type (such as
int, float, char, etc.).
Involves operators and operands: Operators are symbols that specify the operation (like +, -,
*, etc.), and operands are the values or variables that the operators act on.
Types of Expressions in C:
Example:
int x = 10, y = 5;
int result = x + y; // result = 15
Common operators:
o + (Addition)
o - (Subtraction)
o * (Multiplication)
o / (Division)
o % (Modulus – remainder of division)
int a = 5, b = 3;
int result = (a * b) + (a - b); // result = 5*3 + (5-3) = 15 + 2 = 17
Example:
int a = 10, b = 5;
if (a > b) {
printf("a is greater than b\n"); // This will print as a > b is true
}
3. Logical Expressions: Logical expressions are used to perform logical operations and
combine multiple conditions.
Example:
Example:
int a = 5;
a += 3; // Equivalent to a = a + 3; a is now 8
Example:
Syntax:
Example:
int a = 10, b = 5;
int result = (a > b) ? a : b; // result = 10 (since a > b)
Example:
int x = 5;
x++; // x is now 6
x--; // x is now 5 again
Example:
int a = 10;
int *ptr = &a; // Pointer expression: 'ptr' stores the address of 'a'
printf("%d", *ptr); // Dereferencing the pointer prints the value of 'a', which is 10
Example of an Expression in a C Program:
#include <stdio.h>
int main() {
int a = 10, b = 20;
int sum = a + b; // Arithmetic expression: addition
int product = a * b; // Arithmetic expression: multiplication
// Relational expression:
if (a < b) {
printf("a is less than b\n"); // Output: a is less than b
}
// Logical expression:
if (a > 5 && b < 30) {
printf("Both conditions are true\n"); // Output: Both conditions are true
}
// Ternary expression:
int max = (a > b) ? a : b; // max is assigned the larger of a and b
printf("Maximum: %d\n", max); // Output: Maximum: 20
return 0;
A statement in C is a complete instruction that tells the program to perform a specific action.
Each statement in C is typically followed by a semicolon ( ;), which marks the end of the
statement.
Statements control the flow of the program and represent different operations or actions. There
are various types of statements in C, such as expression statements, declaration statements,
control flow statements, etc.
Types of Statements in C:
2. Control Flow Statements: These control the flow of the program based on conditions
or loops.
o if statement: Conditional branching.
if (x > 10) {
printf("x is greater than 10\n");
}
3. Jump Statements: These are used to alter the normal flow of control.
o break: Exits from a loop or switch case.
while (1) {
if (x == 10) break; // Exit loop when x equals 10
}
o continue: Skips the rest of the current iteration of a loop and moves to the next iteration.
4. Declaration Statements: These statements declare variables and specify their data
types.
o Example:
if (x > 0) {
printf("Positive\n");
x--;
}
Example Program with Different Statements:
#include <stdio.h>
int main() {
int x = 5; // Declaration statement
if (x > 0) { // Control flow statement (if)
printf("x is positive\n"); // Expression statement
}
// Loop statement
for (int i = 0; i < 3; i++) {
printf("Iteration %d\n", i); // Expression statement
}
return 0; // Return statement
}
2. Operators in C:
Types of Operators in C:
Example:
2. Relational Operators: These operators are used to compare two values. The result is a
boolean value (true or false).
o == (Equal to)
o != (Not equal to)
o > (Greater than)
o < (Less than)
o >= (Greater than or equal to)
o <= (Less than or equal to)
Example:
int x = 10, y = 5;
if (x > y) {
printf("x is greater than y\n");
}
3. Logical Operators: These operators are used to perform logical operations, usually in
conditions.
o && (Logical AND)
o || (Logical OR)
o ! (Logical NOT)
Example:
int x = 10, y = 5, z = 3;
if ((x > y) && (y > z)) {
printf("Both conditions are true\n");
}
Example:
int x = 5;
x += 3; // Equivalent to x = x + 3; x is now 8
5. Increment and Decrement Operators: These operators increase or decrease the value
of a variable by 1.
o ++ (Increment)
o -- (Decrement)
Example:
int x = 5;
x++; // x becomes 6
x--; // x becomes 5 again
Example:
Example:
int x = 10, y = 5;
int max = (x > y) ? x : y; // max is assigned the larger of x and y
Example:
int x = 10;
int *ptr = &x; // & operator gives the address of x
printf("%d", *ptr); // * operator dereferences the pointer, printing 10
Conclusion:
Statements in C are complete instructions that perform specific actions, such as assignments,
function calls, or control flow changes. Every action in C is represented as a statement.
Operators are symbols that perform operations on variables and values, such as arithmetic,
comparison, logical, and bitwise operations. They are essential for manipulating data and
controlling program logic in C.
The linking process in C is a crucial step in the process of converting source code written in C
into an executable program. It is the final phase of the program compilation process, following
compilation. Linking is the process of combining various pieces of code and data into a single
executable file.
In C, a program often consists of multiple source files and libraries. The linker is the tool
responsible for linking these various pieces together to create a unified executable.
Linking Phases:
1. Compilation Phase:
o The source code (.c files) is compiled into object files (.o files) by the compiler.
2. Linking Phase:
o The linker takes over after compilation.
o The linker combines all object files into a single executable file, resolving references
and symbol addresses.
Types of Linking:
1. Static Linking:
o The code from libraries is directly embedded into the executable during the linking
phase.
Example:
2. Dynamic Linking:
o Libraries are not embedded into the executable. Instead, the operating system loads the
necessary libraries at runtime when the program is executed.
o This reduces the size of the executable and allows libraries to be shared among
different programs.
Example:
// File1.c
void foo();
int main() {
foo(); // Calling an undefined function
return 0;
}
This will result in a linker error because foo is referenced but not defined anywhere.
2. Multiple Definitions:
o This happens when the linker finds multiple definitions of the same function or
variable in different object files, leading to ambiguity.
o Example:
// File1.c
int x = 10;
// File2.c
int x = 20; // Multiple definition of variable 'x'
3. Missing Libraries:
o If a program references functions or symbols from external libraries (e.g., libm for
math functions), and the library is not provided to the linker, a linking error will occur.
int main() {
greet(); // Calling the function
return 0;
}
// file2.c
#include <stdio.h>
Compilation:
Linking: 3. gcc file1.o file2.o -o myprogram → The linker combines the object files ( file1.o, file2.o)
and resolves the external reference to greet(), producing the executable myprogram.
Conclusion:
The linking process in C is the step where multiple object files and libraries are combined to
create a final executable. It involves resolving references to functions, variables, and other
symbols, and it can be either static or dynamic. Proper linking ensures that the program runs
correctly by ensuring all dependencies are resolved before execution.
the void keyword is used in several contexts, and it serves different purposes depending on
where it is used. It can represent the absence of a value or type, and it is an important concept
in C programming. Below are the primary uses of void:
When a function does not return any value, it is declared with the void return type. This
indicates that the function performs some action but does not return any data to the calling
function.
Example:
#include <stdio.h>
int main() {
greet(); // Calling the function
return 0;
}
In the example above, the greet() function is declared with the return type void, meaning it does
not return any value.
A void pointer (void *) is a special type of pointer that can point to any data type. It is used
when the type of the data being pointed to is not known in advance or when writing generic
functions that can handle different data types.
A void * pointer can be used to store the address of any variable, and it can be cast to another
pointer type as needed.
Void pointers cannot be dereferenced directly because the compiler doesn't know what type
of data the pointer points to.
Example:
#include <stdio.h>
int main() {
int x = 10;
float y = 5.5;
return 0;
}
In the example above, the printValue function uses a void * pointer to accept both int and float
values. The pointer is cast to the appropriate type before dereferencing.
A function can accept void as a parameter type to indicate that the function does not take any
arguments. This is typically used when defining functions that do not require any input
parameters.
Example:
#include <stdio.h>
int main() {
sayHello(); // Calling the function with no arguments
return 0;
}
In this example, the sayHello function explicitly specifies void as its parameter, indicating that it
does not take any arguments.
In some cases, void can be used in a typedef to create pointers or references to unspecified
types. This is less common but still a valid use.
Example:
#include <stdio.h>
typedef void (*FunctionPointer)(int); // Typedef for a function pointer that takes an int and returns void
void myFunction(int x) {
printf("Value: %d\n", x);
}
int main() {
FunctionPointer ptr = myFunction; // Assigning function to the pointer
ptr(5); // Calling function through pointer
return 0;
}
Here, typedef void (*FunctionPointer)(int) defines a pointer to a function that takes an int and
returns void. The function myFunction is assigned to this pointer and then called using ptr.
1. Void as a return type: Indicates that a function does not return any value.
void myFunction() { }
2. Void pointer (void *): A generic pointer that can point to any data type. Requires
typecasting to dereference.
void *ptr;
3. Void as function parameters: Indicates that a function does not take any arguments.
void myFunction(void) { }
Conclusion:
UNIT-II(CONTROL STRUCTURES)
Unit-2
2-Marks
1. Define Decision Making Statement.?
Decision-making statements are the statements that are used to verify a given condition and decide
whether a block of statements gets executed or not based on the condition result.
In the c programming language, there are two decision-making statements they are as follows.
1. if statement
2. switch statement
The looping statements are used to execute a single statement or block of statements repeatedly until
while statement
do-while statement
for statement
These control statements are called as unconditional control statements. C programming language
break
continue
goto
void main(){
clrscr() ;
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
getch() ;
}
Output:
Syntax:
exit(status);
□ 0 indicates successful program termination.
□ A non-zero value indicates an error or abnormal termination
Common Use Cases:
getchar() is a standard input function used to read a single character from the
standard input (usually the keyboard). It is part of the stdio.h library.
int main() {
char ch;
return 0;
}
Enter a character: A
You entered: A
putchar() is a standard output function used to write a single character to the standard output
(usually the console). It is part of the stdio.h library.
int main() {
char ch = 'A';
printf("Output character: ");
putchar(ch);
putchar('\n');
return 0;
}
Output:
Output character: A
5-MARKS:
7. Explain the Conditional statements with example?
1. if statement
1.1. Simple if statement :
if is a one way selection .
Simple if statement is used to verify the given condition and executes the block of statements based
on the condition result.
The simple if statement evaluates specified condition. If it is TRUE, it executes the block of
statements. If the condition is FALSE, it skips (ignores)the block of statements
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;
else
printf("Given number is ODD\n") ;
}
Output
1:
Output 2:
The nested if statement can be defined using any combination of simple if & if-else statements.
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}
Output 2:
void main(){
int a, b, c ;
else
printf("%d is the largest number", c) ;
}
Output:
2. 'switch' statement :
Consider a situation in which we have many options out of which we need to select only one option that is
to be executed. Such kind of problems can be solved using nested if statement. But as the number of options
increases, the complexity of the program also gets increased. This type of problem can be solved very easily
The switch statement has the following syntax and execution flow diagram.
void main(){
int n ;
clrscr() ;
switch( n )
{
case 0: printf("ZERO") ;
break ;
case 1: printf("ONE") ;
break ;
case 2: printf("TWO") ;
break ;
case 3: printf("THREE") ;
break ;
case 4: printf("FOUR") ;
break ;
case 5: printf("FIVE") ;
Output 1:
The looping statements are used to execute a single statement or block of statements repeatedly until
while statement
do-while statement
for statement
1.while Statement
The while statement is used to execute a single statement or block of statements repeatedly as long
statement.
while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
} getch() ;
}
Output:
9. 'do-while' statement :
The do-while statement is used to execute a single statement or block of statements repeatedly as long as
given the condition is TRUE. The do-while statement is also known as the Exit control looping statement.
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;
Output:
3. 'for' statement :
The for statement is used to execute a single statement or a block of statements repeatedly as long as the
The for statement has the following syntax and execution flow diagram...
void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
for( n = 0 ; n <= 10 ; n++ )
{
if( n%2 == 0)
Output:
While loops
for loop
1. while loop:
The while statement is used to execute a single statement or block of statements repeatedly as long
as the given condition is TRUE. The while statement is also known as Entry control looping
statement.
while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
} getch() ;
}
Output:
'for' loop :
The for statement is used to execute a single statement or a block of statements repeatedly as long as the
The for statement has the following syntax and execution flow diagram...
void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
for( n = 0 ; n <= 10 ; n++ )
{
if( n%2 == 0)
Output:
do while loops
1. 'do-while'loop :
The do-while statement is used to execute a single statement or block of statements repeatedly as long as
given the condition is TRUE. The do-while statement is also known as the Exit control looping statement.
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;
getch() ;
}
Output:
to be executed. Such kind of problems can be solved using nested if statement. But as the number of options
increases, the complexity of the program also gets increased. This type of problem can be solved very easily
The switch statement has the following syntax and execution flow diagram.
void main(){
int n ;
clrscr() ;
switch( n )
{
case 0: printf("ZERO") ;
break ;
case 1: printf("ONE") ;
break ;
case 2: printf("TWO") ;
break ;
case 3: printf("THREE") ;
break ;
case 4: printf("FOUR") ;
break ;
case 5: printf("FIVE") ;
break ;
case 6: printf("SIX") ;
break ;
case 7: printf("SEVEN") ;
break ;
case 8: printf("EIGHT") ;
break ;
case 9: printf("NINE") ;
break ;
default: printf("Not a Digit") ;
}
getch() ;
}
Output 1:
These control statements are called as unconditional control statements. C programming language
break
continue
goto
The above three statements do not need any condition to control the program execution flow.
break statement
In C, the break statement is used to perform the following two things...
When a break statement is encountered inside the switch case statement, the execution control moves out of
the switch statement directly. For example, consider the following program.
void main(){
int number1, number2, result ;
char operator;
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &number1, &number2) ;
printf("Please enter any arithmetic operator: ");
operator = getchar();
switch(operator)
{
case '+': result = number1 + number2 ;
printf("Addition = %d", result) ;
break;
Output:
When the break statement is encountered inside the looping statement, the execution control moves out of
the looping statements. The break statement execution is as shown in the following figure.
void main(){
char ch ;
clrscr() ;
do
{
printf("Enter Y / N : ") ;
scanf("%c", &ch) ;
if(ch == 'Y')
{
printf("Okay!!! Repeat again !!!\n") ;
}
else
{
printf("Okay !!! Breaking the loop !!!") ;
break ;
}
} while( 1 ) ;
getch() ;
}
Output:
continue statement
The continue statement is used to move the program execution control to the beginning of the looping
statement. When the continue statement is encountered in a looping statement, the execution control skips
the rest of the statements in the looping block and directly jumps to the beginning of the loop.
The continue statement can be used with looping statements like while, do-while and for.
When we use continue statement with while and do-while statements the execution control directly jumps
to the condition. When we use continue statement with for statement the execution control directly jumps
to the modification portion (increment/decrement/any modification) of the for loop. The continue statement
execution is as shown in the following figure.
void main(){
int number ;
clrscr() ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
if(number%2 == 0)
{
printf("Entered number is EVEN!!! Try another number!!!\n") ;
continue ;
}
else
{
printf("You have entered ODD number!!! Bye!!!") ;
exit(0) ;
}
}
getch() ;
}
Output:
void main(){
clrscr() ;
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
getch() ;
}
Output:
Here’s a simple C program to implement a basic calculator using a switch case. The program
performs addition, subtraction, multiplication, and division based on the user's input.
int main() {
char operator;
double num1, num2, result;
return 0;
}
Sample Output
Case 1: Addition
arduino
Copy code
Enter an operator (+, -, *, /): +
Enter two numbers: 5.5 2.3
5.50 + 2.30 = 7.80
Case 2: Division by Zero
vbnet
Copy code
Enter an operator (+, -, *, /): /
Enter two numbers: 8 0
Error! Division by zero is not allowed.
Case 3: Invalid Operator
kotlin
2 MARKS
Array Indexing:
Arrays in C are indexed starting at 0 to size-1.The index of the first element of the array
is starts with 0 , the second element is 1, the third element is 2 , and The index to the
last value in the arrayis the array size minus one.
Memory Diagram
5 MARKS
1. What Is An Array? How A Single Dimension And Two Dimension Arrays Are Declared
And Initialized?
Arrays:
An array is defined as the collection of elements of similar data type which are
stored atcontiguousmemory locations.
Arrays can store the primitive type of data such as int, char, double, float, etc.
It alsohasthe capability to store the derived data types, such as pointers,
structure, etc.
Syntax for declaring array:
Types of Arrays:
One-dimensional array – array having only one subscript variable is
called one-dimensional array.
Multi-dimensional array (2D,3D..etc) - array having more than one subscript
variable iscalled multi- dimensional arrays.
Example:
int a[5] = { 20, 40, 30, 60, 70 }
It represented in memory location as:
v
20 10 30 50 40
The size of the above arrays is 5 which is automatically deduced by the compiler.
2.Array Initialization (at Runtime) after Declaration (Using Loops):
We initialize the array after the declaration by assigning the initial value to each
element individually. We can use for loop, while loop, or do-while loop to assign
the value to eachelement of the array.
Ex: int a[100]; n-no. of elements in an array
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
Memory Diagram
{
char ch[20]={'p', 'r', 'o', 'g', 'r', 'a', 'm', ‘m’, 'i', 'n', 'g', '\0'};
printf("Length of string is: %d", strlen(ch));
return 0;
}
Output :Length of string is 11
1) char a[50];
strcpy (“Hello”,a);
o/p: error
2) char a[50];
strcpy ( a,”hello”);
o/p: a= “Hello”
Example:
#include<stdio.h>
#include<string.h>
Int main()
{
char s1[20]={'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '\0'};
char s2[20];
strcpy(s2,s1);
printf("Value of second string
is: %s",s2);return 0;
}
Output:
Value of second string is: helloworld
Example:2
#include<stdio.h>
#include<string.h>
Int main()
{
char a[30]= “Hello”;
char b[20] = "Good Morning";
strcat(a,b,4);
a [9] = '\0';
printf("Concatenated string is: %s", a);
return 0;
}
Output:
Concatenated string is: Hello Good.
3. Compare String: strcmp():
This function compares 2 strings.
It returns the ASCII difference of the first two non – matching characters in
both thestrings The strcmp(first_string, second_string) function compares
two string and returns 0 if bothstrings are equal.
//If the difference is equal to zero, then string1 = string2
//If the difference is positive, then string1 > string2
//If the difference is negative, then string1 < string2
Output:
Enter 2 strings:hello world
hello is (alphabetically) less than world
5.Reverse String: strrev():
The strrev(string) function returns reverse of
the given string.The reversed string will be
stored in the same string.
This function converts a string to lowercase. Note, this function is not included in the Standard
Library.
Syntax:
char *strlwr(char *str);
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "GEEKSFORGEEKS IS THE BEST";
return 0;
}
Output:
geeksforgeeks is the best
#include<stdio.h>
#include <string.h>
int main()
{
char str[] = "CompuTer ScienCe PoRTAl fOr geeKS";
return 0;
}
Output:
Given string is: CompuTer ScienCe PoRTAl fOr geeKS
String after converting to the lowercase is: computer science portal for geeks
This function converts a string to uppercase. Note, this function is not included in the Standard
Library.
The strupr( ) function is used to converts a given string to uppercase.
Syntax:
char *strupr(char *str);
Example:
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "geeksforgeeks is the best";
//converting the given string into uppercase.
printf("%s\n", strupr (str));
return 0;
}
Output:
GEEKSFORGEEKS IS THE BEST
#include<stdio.h>
#include <string.h>
int main()
{
char str[] = "CompuTer ScienCe PoRTAl fOr geeKS";
int main() {
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: ");
scanf("%s", string1);
length = strlen(string1);
for (i = 0; i < length / 2; i++) {
if (string1[i] != string1[length - i - 1]) {
return 0;
}
Output:
Enter a string :WOW
Wow is a Palimdrome
return 0;
}
Output:
Result Matrix:
30 24 18
84 69 54
Here, the base address is the address of the multidimensional array or the address of the first
object stored in the multidimensional array. The memory address increases by 4 bytes (the
size of the int data type).
Below is the Implementation of the above concept:
// in multidimensional array
#include <stdio.h>
#include <stdlib.h>
int main()
// 2-Dimension array
int row = 3;
int col = 3;
int k = 1;
*(arr + i * col + j) = k;
k++;
printf("\n");
return 0;
Output
123
456
return 0;
}
Run Code
Output
Enter the number of rows (between 1 and 100): 2
Enter the number of columns (between 1 and 100): 3
10 8 6
// Linear Search in C
#include <stdio.h>
int main() {
int array[] = {2, 4, 0, 1, 9};
int x = 1;
int n = sizeof(array) / sizeof(array[0]);
(result == -1) ? printf("Element not found") : printf("Element found at index: %d", result);
}
Output:
Element found at index: 3
Unit-4
2marks:
1. Define Functions in c.
ANS:
A function is a self – contained block or a sub program which contains a group
of statements that performs a required task when called.
A called function receives control from a calling function. When the called
function completes its task, it returns control to the calling function.
From the above figure we can see that main() calls function named function1().
Main() is known as calling function and function1() is known as called function.
7. What Is Union?
The Union is a user-defined data type in C language that can contain elements
of the different data types just like structure. But unlike structures, all the
members in the C union are stored in the same memory location. Due to this,
only one member can store data at the given instance.
5marks
1.How to declare and initialize structures? Explain with examples?
Automatic variables are local variables that are automatically created when a function is called
and destroyed
when the function returns. These variables are created using the auto keyword (though it’s
implicit and rarely
used explicitly).
Automatic variables only exist during the function’s execution, and their values do not persist
between function
calls.
Characteristics:
Created when the function starts.
Destroyed when the function ends.
They do not retain their values between function calls.
Stored in the stack.
Example:
#include <stdio.h>
void exampleFunction() {
int localVar = 10; // Automatic variable
printf("Local Variable: %d\n", localVar);
} // localVar is destroyed here
int main() {
exampleFunction(); // localVar is created and destroyed during the function call
return 0;
}
Explanation:
In the example, localVar is an automatic variable that is created when exampleFunction() is
called and destroyed
when the function returns.
Example
#include <stdio.h>
void countCalls() {
static int count = 0; // Static variable initialized once
count++;
printf("Function called %d times\n", count);
}
int main() {
countCalls(); // Function called 1st time
countCalls(); // Function called 2nd time
countCalls(); // Function called 3rd time
return 0;
}
Explanation:
In the example, the count variable is a static variable. It is initialized only once, and its value is
retained across
multiple calls to countCalls(). Each time the function is called, count is incremented, and
its value persists.
The scope of the automatic variables is limited to the block in which they are
Static
o The variables defined as static specifier can hold their value between the
multiple function calls.
o Static local variables are visible only to the function or the block in which they
are defined.
o A same static variable can be declared many times but can be assigned at only
one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variableis limited to the file in which it has
declared.
o The keyword used to define static variable is static.
Register
o The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator
for the register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the
CPU register.
o We can store pointers into the register, i.e., a register can store the address of a
variable.
o Static variables can not be stored into the register since we can not use more
than one storage specifier for the same variable.
External
o The external storage class is used to tell the compiler that the variable defined
as extern is declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only
declaration and intended to specify that the variable is declared elsewhere in the
1. Define Pointers?
A pointer is a variable that stores the memory address of another variable. Instead of holding
a direct data value like an integer or a float, a pointer holds the address of where the data is
located in memory.
For example:
int x = 10;
int *p = &x; // p holds the address of x
To declare a pointer, you use the * symbol to indicate it is a pointer. Initialization is done
using the address-of operator (&), which gives the memory address of a variable.
Declaration:
Initialization:
int x = 10;
int *p = &x; // p points to the address of x
Pointer arithmetic refers to the operations that can be performed on pointers, such as
incrementing, decrementing, or adding/subtracting integers to/from pointers. These
operations affect the memory addresses the pointers point to.
For example:
Incrementing a pointer moves it to the next memory location based on its data type.
Pointer subtraction is meaningful and valid. When subtracting two pointers, the
result is the number of elements between them, not the raw difference in their
memory addresses.
int arr[5];
int *p1 = &arr[0];
int *p2 = &arr[4];
int diff = p2 - p1; // diff = 4, since there are 4 elements between
p1 and p2
User-defined data types in C allow you to create custom data types, which are defined by the
user, to suit specific needs in a program. Some examples include:
struct Person {
char name[50];
int age;
};
Union: Similar to a struct but all members share the same memory location.
union Data {
int i;
float f;
};
The dereferencing operator (*) is used to access the value at the memory address that a
pointer is pointing to. It is used to obtain the value stored at the address the pointer holds.
Example:
int x = 10;
int *p = &x;
printf("%d", *p); // Dereferencing p, output will be 10
7. What Is The Need of Pointers?
Example:
fscanf(): A function used to read formatted input from a file. It works like scanf(),
but the input is read from a file stream.
Example:
fopen(): A function used to open a file in a specified mode (read, write, append,
etc.). It returns a file pointer if the file is opened successfully, or NULL if it fails.
Example:
fclose(): A function used to close a file that was opened using fopen(). It ensures
that any data buffered in memory is written to the file and frees any resources used.
Example:
Here’s how each can be used for sequential reading from a disk file:
Using fread()
fread() is used to read binary data from a file in chunks. It is particularly useful when you
need to read data that is stored in a binary format.
Syntax of fread():
c
Copy code
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
Let's assume we have a binary file containing an array of integers. The program below reads
and prints the integers sequentially.
#include <stdio.h>
int main() {
FILE *file;
int num;
size_t readSize;
return 0;
}
In this example:
Using fscanf()
fscanf() is used to read formatted input from a file, similar to how scanf() reads from the
standard input. It is useful when the data in the file is stored in a text format (e.g., numbers,
strings, etc.).
Syntax of fscanf():
int fscanf(FILE *stream, const char *format, ...);
Let's assume we have a text file (data.txt) containing a list of integers, one per line. The
program below reads the integers sequentially and prints them.
#include <stdio.h>
int main() {
FILE *file;
int num;
return 0;
}
In this example:
We open the file data.txt in text read mode ("r").
We use fscanf() to read one integer at a time from the file, specifying the format "%d" to
read integers.
We use EOF (End of File) as the termination condition, which fscanf() returns when no
more data can be read.
1. Data Format:
o fread() is used to read binary data, and it reads raw bytes from a file into a buffer.
It does not interpret the data.
o fscanf() is used for formatted text input and parses the data according to the
provided format specifiers (e.g., %d, %f, %s).
2. Reading Mechanism:
o fread() reads a specified number of bytes from the file into memory.
o fscanf() reads data from the file and converts it based on the format specifiers.
3. File Type:
o fread() is typically used for binary files.
o fscanf() is typically used for text files.
Conclusion:
Use fread() when dealing with binary files or when you need to read large chunks of raw
data in one go (e.g., an array of integers).
Use fscanf() when reading text files that contain data in a specific format (e.g., integers,
floats, strings).
int main() {
FILE *file; // Declare file pointer
char ch; // Variable to store each character read from the
file
return 0;
}
Explanation:
1. Opening the File: The program uses fopen() to open the file in read mode ("r").
You should replace "example.txt" with the path to your actual file.
2. Checking for File Open Success: If fopen() fails to open the file (for example, if
the file doesn't exist), it will return NULL. In this case, the program prints an error
message and exits.
3. Reading the File: The program uses fgetc(file) to read one character at a time
from the file. The fgetc() function returns each character in the file until it
encounters the end-of-file marker (EOF), which signals that there is no more data to
read.
4. Printing the File Content: Each character read is passed to putchar(ch) to print it
to the console.
5. Closing the File: After reading the file, the program calls fclose(file) to close the
file and release any resources associated with it.
Output:
Hello, this is a test file.
It contains some text data.
Notes:
Make sure the file example.txt exists in the directory from which you are running
the program, or provide the full path to the file.
This example assumes you are reading text data from the file. If you are working with
binary data, you would use fread() instead of fgetc().
3. Explain About The Functions For Reading And Writing Data
From A File.
In C, there are several functions for reading from and writing to files. These functions are part
of the standard C library (stdio.h) and provide various ways to interact with files. Below is
a detailed explanation of the most commonly used file I/O functions in C:
Before reading from or writing to a file, it is necessary to open the file using the fopen()
function.
fopen()
FILE *fopen(const char *filename, const char *mode);
Purpose: Opens a file and returns a file pointer (FILE *), which will be used in subsequent
operations.
Parameters:
o filename: The name of the file to be opened (could be a relative or absolute path).
o mode: Specifies the file access mode (e.g., "r" for reading, "w" for writing).
Modes:
o "r": Open for reading. The file must exist.
o "w": Open for writing. If the file exists, it is truncated to zero length. If it doesn't
exist, it is created.
o "a": Open for appending. Data will be written to the end of the file.
o "rb", "wb", "ab": Open for binary reading, writing, or appending (for binary files).
Example:
Once a file is opened, data can be read using different functions depending on the type and
format of data.
fgetc()
Purpose: Reads a line of text from a file, including spaces, until a newline character is
encountered or num - 1 characters are read, whichever comes first.
Returns: A pointer to the string (str), or NULL if an error occurs or end of file is reached.
Example:
char buffer[100];
fgets(buffer, 100, file); // Read a line from the file
fread()
Purpose: Reads a block of data from a file into memory. It is often used for reading binary
data.
Parameters:
o ptr: Pointer to a buffer where the data will be stored.
o size: Size of each element to read.
o count: Number of elements to read.
Returns: The number of elements successfully read (which may be less than count if end-of-
file is reached).
Example:
int arr[5];
fread(arr, sizeof(int), 5, file); // Read 5 integers from the file
fscanf()
int num;
fscanf(file, "%d", &num); // Read an integer from the file
After opening the file in a mode that allows writing, you can use the following functions to
write data to the file.
fputc()
int fputc(int character, FILE *stream);
fputs()
fwrite()
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
Purpose: Writes a block of data to a file. It is commonly used for writing binary data.
Parameters:
o ptr: Pointer to the data to be written.
o size: Size of each element to write.
o count: Number of elements to write.
Returns: The number of elements successfully written (which may be less than count if an
error occurs).
Example:
fprintf()
int fprintf(FILE *stream, const char *format, ...);
After performing file I/O operations, it's important to close the file using the fclose()
function.
fclose()
int fclose(FILE *stream);
Purpose: Closes the file and releases any resources associated with it.
Returns: 0 on success, EOF if an error occurs.
Example:
Here's a simple C program that demonstrates opening a file, reading its contents, and writing
to another file.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *inputFile, *outputFile;
char ch;
Summary
Reading: You can read from a file using functions like fgetc(), fgets(), fread(), and
fscanf().
Writing: You can write to a file using functions like fputc(), fputs(), fwrite(), and
fprintf().
File Handling: Always open the file with fopen() and close it with fclose() after the
operations are complete.
4.Write A C Program To Print File Contents In Reverse Order.
Certainly! Here's a C program that opens a file, reads its contents, and prints the contents in
reverse order. The program reads the file character by character, stores them in a stack-like
manner (using an array or dynamically allocated memory), and then prints them in reverse.
int main() {
FILE *file;
char *buffer;
long fileSize;
size_t bytesRead;
return 0;
}
Explanation:
1. Opening the File: The program uses fopen() to open the file "example.txt" in
read mode ("r"). You should replace "example.txt" with the actual path to your
file.
2. Getting the File Size:
o The program uses fseek() and ftell() to determine the size of the file.
o fseek(file, 0, SEEK_END) moves the file pointer to the end of the file.
o ftell(file) returns the current position of the file pointer, which is the size
of the file in bytes.
o After obtaining the size, rewind(file) is called to move the file pointer back
to the beginning of the file.
3. Reading the File:
o The program allocates memory (malloc()) to store the contents of the file.
o fread() is used to read the entire file into the buffer. The number of bytes
read is stored in bytesRead.
4. Printing in Reverse:
o The program loops backward from the end of the buffer to the beginning and
prints each character using putchar().
5. Cleanup:
o After the file contents have been printed, the program frees the dynamically
allocated memory and closes the file using free() and fclose().
Example:
Output:
.esrever ni detnirp eb lliw elif sihT
.elif tset a si siht ,olleH
Definition of a Pointer in C
A pointer in C is a variable that stores the memory address of another variable. Rather than
holding a data value itself, a pointer holds the address where the data is located in memory.
Pointers are often used in C to work with dynamic memory allocation, arrays, functions, and
other advanced programming techniques.
data_type *pointer_name;
data_type: This specifies the type of data the pointer will point to (e.g., int, float, char).
*: The asterisk (*) indicates that the variable is a pointer.
pointer_name: This is the name of the pointer variable.
1. Declaring a Pointer:
When declaring a pointer, you specify the data type it will point to. For example:
2. Initializing a Pointer:
Here, &num gives the address of the variable num, and this address is stored in the
pointer ptr.
1. Integer Pointer
#include <stdio.h>
int main() {
int num = 10; // Integer variable
int *ptr = # // Pointer to int, initialized to the address of num
return 0;
}
Explanation:
2. Float Pointer
#include <stdio.h>
int main() {
float pi = 3.14;
float *fptr = π // Pointer to float, initialized to the address of
pi
return 0;
}
Explanation:
3. Character Pointer
#include <stdio.h>
int main() {
char letter = 'A';
char *cptr = &letter; // Pointer to char, initialized to the address
of letter
return 0;
}
Explanation:
Example:
int var = 5;
int *ptr = &var; // ptr stores the address of var
Example:
3. NULL Pointers:
o A pointer can be initialized to NULL (a special constant representing an invalid
memory address) to indicate that it doesn't point to a valid memory location yet.
Example:
4. Pointer to Pointer:
o You can have a pointer that points to another pointer, known as a pointer to
pointer.
Example:
Pointer arithmetic in C refers to the operations that can be performed on pointers to navigate
through memory locations in an array or other data structures. It allows programmers to
perform calculations involving memory addresses efficiently.
In C, pointers are variables that store memory addresses. They can be manipulated using
arithmetic operations, such as addition, subtraction, and comparison. These operations are
performed based on the size of the data type that the pointer is pointing to.
When a pointer is incremented, it moves to the next element in the array, not just the next
byte. For example, if a pointer points to an integer and is incremented, it moves to the next
integer in memory (typically 4 bytes forward on most systems).
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Pointer to the first element of arr
return 0;
}
Explanation: When ptr++ is executed, it moves from pointing to the first element (arr[0])
to the second element (arr[1]), because an int is typically 4 bytes on most systems.
Similar to incrementing, pointer decrement moves the pointer backward to the previous
element in the array.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = &arr[3]; // Pointer to the last element of arr
return 0;
}
Explanation: After ptr--, the pointer moves backward from arr[3] to arr[2].
When you add an integer to a pointer, it moves forward by that integer multiplied by the size
of the type it points to. For example, if you add 2 to an int pointer, it moves forward by 2 *
sizeof(int) bytes.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Pointer to the first element of arr
return 0;
}
Explanation: ptr + 2 moves the pointer two elements forward in the array. It points to
arr[2] (the third element), because each increment steps forward by the size of the type
(sizeof(int)).
Pointer subtraction works similarly to addition. If you subtract an integer from a pointer, it
moves backward by that integer multiplied by the size of the type the pointer is referencing.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = &arr[3]; // Pointer to the last element of arr
return 0;
}
Explanation: ptr - 2 moves the pointer two positions backward in the array. It now points
to arr[1] (the second element).
5. Pointer Comparison
Pointers can also be compared with each other or with NULL. This is useful, for example,
when traversing arrays or linked lists.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr1 = arr;
int *ptr2 = &arr[3];
return 0;
}
Explanation: We compare ptr1 (which points to the first element of the array) and ptr2
(which points to the last element of the array). Since ptr2 points to a higher memory
address than ptr1, the condition ptr2 > ptr1 is true.
In C, arrays and pointers are closely related. The name of an array is a pointer to its first
element. Hence, pointer arithmetic can be used to navigate through array elements.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Pointer to the first element of arr
Explanation: The expression *(ptr + n) accesses the nth element of the array, because
ptr is a pointer to the first element of the array. The pointer arithmetic moves the pointer n
elements forward.
1. Pointer Bounds: You should not perform arithmetic that moves the pointer beyond
the bounds of an array or allocated memory. Accessing memory outside of the
allocated range results in undefined behavior.
2. Pointer Arithmetic and Data Types: Pointer arithmetic is always performed based
on the size of the type the pointer points to. For example, if you have a pointer to a
char (which is 1 byte) and you increment it, it moves 1 byte forward. If it points to an
int (typically 4 bytes), the pointer will move by 4 bytes when incremented.
3. Pointer Differences: You can subtract two pointers that point to elements within the
same array. The result is the difference in the number of elements between them (not
the byte difference).
int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Pointer to the first element of arr
return 0;
}
Explanation: In this example, *(ptr + i) accesses each element of the array arr using
pointer arithmetic.
Conclusion
Pointer arithmetic is a powerful feature in C that allows you to efficiently navigate through
arrays, structures, and other memory regions. It is essential for low-level memory
manipulation, such as when dealing with arrays, buffers, or dynamically allocated memory.
However, pointer arithmetic should be used carefully to avoid undefined behavior, especially
when accessing memory outside the bounds of an array.
Dynamic memory allocation refers to the process of allocating memory at runtime, rather
than at compile-time. This is done using specific functions provided in C, which allow
programmers to request memory from the heap (a region of memory reserved for dynamic
memory allocation) rather than from the stack (which is automatically managed by the
compiler).
Dynamic memory allocation is important because it enables the creation of flexible programs
that can handle varying amounts of data, and it provides more efficient use of memory
resources compared to static memory allocation.
1. Flexibility:
o Memory can be allocated during program execution, allowing the program to adjust
based on the requirements at runtime. This is especially useful for situations where
the amount of memory required is not known in advance.
2. Efficient Memory Usage:
o Dynamic memory allocation enables you to request only the memory you need, and
release it when it’s no longer required, preventing memory wastage.
3. Handling Large Data:
o It allows programs to handle large datasets (e.g., reading from files, processing user
input, or working with large arrays) that might not fit into the stack space.
4. Memory Reusability:
o You can allocate and deallocate memory at will, giving you the ability to reuse
memory, which is important in large programs or long-running systems.
5. Creating Complex Data Structures:
o Complex data structures like linked lists, trees, graphs, and dynamic arrays depend
on dynamic memory allocation to grow and shrink during the program's execution.
In C, dynamic memory is allocated using the following functions from the standard library
(<stdlib.h>):
Let’s demonstrate dynamic memory allocation by using the malloc() function to create an
array of integers. We will also use free() to release the memory when we’re done.
int main() {
int *arr; // Pointer to int
int size, i;
return 0;
}
int main() {
int *arr;
int size, i;
return 0;
}
1. Flexibility:
o You can allocate and deallocate memory as needed during the program’s execution,
allowing the program to adapt to changing requirements.
2. Handling Large Data Structures:
o It is particularly useful for working with large data structures that may not fit into
the stack, such as large arrays, lists, or trees.
3. Memory Efficiency:
o Memory is allocated only when required and freed when it’s no longer needed,
reducing memory waste.
4. Scalability:
o Dynamic memory allocation allows for creating data structures whose size can grow
or shrink as the program runs. This is useful for applications like databases, memory
buffers, or dynamic arrays.
1. Memory Leaks:
o If dynamically allocated memory is not properly freed using free(), it can lead to
memory leaks, where memory is not returned to the system, causing the program to
consume more and more memory over time.
2. Fragmentation:
o Over time, if memory is frequently allocated and deallocated, it can lead to
fragmentation of the heap, where memory is divided into small, non-contiguous
blocks, making it harder to allocate large blocks of memory.
3. Complexity:
o Handling dynamic memory requires careful management of memory allocation and
deallocation to avoid errors like accessing freed memory or failing to release
memory.
8. How pointers are used to declare single and multi-dimension
arrays with examples?
In C, arrays and pointers are closely related concepts. While an array is a collection of
elements of the same type, a pointer is a variable that stores the memory address of another
variable (in this case, the first element of an array).
To declare and access a single-dimensional array using a pointer, we typically use the
following approach:
1. Array Declaration:
2. Pointer Initialization:
The pointer can be initialized to point to the first element of the array (since the array name is
a pointer to the first element of the array).
ptr = arr; // Pointer ptr now points to the first element of the
array
You can access array elements using the pointer and pointer arithmetic, like this:
int main() {
int arr[5]; // Declaring a single-dimensional array of size 5
int *ptr = arr; // Pointer initialized to point to the first
element of arr
return 0;
}
2. Pointer Initialization:
We can initialize the pointer to point to the first row of the array:
ptr = arr; // Pointer ptr points to the first row of the 2D array
To access elements of the 2D array using pointers, you can use pointer arithmetic. In a 2D
array, each row can be treated as a pointer to the first element of that row.
int main() {
int arr[3][4]; // 2D array with 3 rows and 4 columns
int (*ptr)[4] = arr; // Pointer to an array of 4 integers (each row
has 4 elements)
return 0;
}
We can dynamically allocate memory for multi-dimensional arrays using pointers. For
example, you can allocate a 2D array using malloc() or calloc() to allocate memory on the
heap at runtime.
Example: Dynamic Memory Allocation for a 2D Array
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3, cols = 4;
int **arr; // Declare a pointer to pointer (2D array)
return 0;
}
arr = (int **)malloc(rows * sizeof(int *));: Allocates memory for the array of
pointers (for rows).
arr[i] = (int *)malloc(cols * sizeof(int));: Allocates memory for each row,
where each row has cols number of integers.
free(): Releases the dynamically allocated memory after use to avoid memory leaks.
Conclusion
Single-dimensional arrays can be accessed and manipulated using pointers with pointer
arithmetic.
Multi-dimensional arrays (such as 2D arrays) can also be handled using pointers, and
pointer arithmetic can help traverse the array's rows and columns.
Dynamic memory allocation using pointers allows for the creation of arrays whose size is
determined at runtime, making programs more flexible and efficient in terms of memory
management.
What is a Pointer?
A pointer in C is a variable that stores the memory address of another variable. Instead of
holding a direct value, like an integer or a character, a pointer contains the address where the
data is located in memory. Pointers are essential in C because they allow direct memory
access, enabling efficient manipulation of data, dynamic memory allocation, and the creation
of complex data structures such as linked lists and trees.
Pointer Declaration
A pointer is declared by specifying the type of data it points to, followed by an asterisk ( *).
For example:
Here, ptr is a pointer that holds the address of an integer, and str is a pointer that holds the
address of a character.
Dereferencing a Pointer: Dereferencing a pointer means accessing the value stored at the
address the pointer is pointing to. This is done using the asterisk (*).
Pointer Assignment: You can assign a pointer to the address of a variable using the address-
of operator (&).
An array of pointers is an array where each element is a pointer that points to some data.
The data that the pointers point to can be of any type, and each pointer in the array can point
to a different variable. This is particularly useful when working with dynamic memory
allocation or arrays of strings.
In this example, each element of the array is a pointer that points to an integer variable.
#include <stdio.h>
int main() {
int num1 = 10, num2 = 20, num3 = 30;
int *arr[3]; // Array of 3 integer pointers
return 0;
}
Another common example is using an array of pointers to hold a list of strings. Since strings
are arrays of characters, each pointer in the array can point to the first character of a string.
#include <stdio.h>
int main() {
// Array of pointers to strings (array of string literals)
char *arr[] = {"Hello", "World", "Array", "of", "Pointers"};
return 0;
}
Here’s an example where we use an array of pointers to dynamically allocate memory for
integers at runtime:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr[3]; // Array of 3 pointers
return 0;
}
Explanation: