0% found this document useful (0 votes)
158 views156 pages

IP Question Bank With Answers (2024-2025)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
158 views156 pages

IP Question Bank With Answers (2024-2025)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 156

SIR C R REDDY COLLEGE OF ENGINEERING,ELURU (AUTONOMOUS)

I/IV B.Tech, I Semester


Program: B.Tech (Common to All Branches)
COURSE:INTRODUCTION TO PROGRAMMING(24CS1102)

UNIT-I:Introduction to programming and problem solving


5 MARKS

1. Explain in detail the structure of C Program and procedure to create,


compile and run the C program.
2. What is Operator Precedence and Associativity in Expression
Evaluation?
3. Discuss about the Importance of C. Write down the rules for declaring
the variables.
4. Define I/O functions.Discuss Various I/O functions in c.?
5. Discuss about the Various operators with example program.
6. Discuss about the Data types in C.
7. Discuss about Constants in C.
8. Define Algorithm?Explain the characterstics of Algorithm with
example?Define Flowchart?What are the symbols used in
Flowchart?Explain with example?
9. What is Type Conversion and Type Casting .Explain in detail?
10. Write a short note on Time and Space Complexity?
11. Explain the Block Diagram of Computer Organization?

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?

INTRODUCTION TO PROGRAMMING QUESTION BANK


UNIT-II:Control Structures

2MARKS

1. Define Decision Making Statement


2. Define Looping Statement
3. Define Unconditional Statement
4. Define Simple If Statement
5. Define Switch Statement
6. Define For Statement
7. Define Goto Statement
8. Define Break Statement
9. Define Exit Statement
10. What Is Getchar()
11. Define Putchar()

5 MARKS

1. Explain the Conditional statements with example?


2. Explain Looping (or) Iterative Statements with example?(For,While,Do-While)
3. Explain Pre-Tested and Post Tested Loops with example?
4. Expalin Multidecision Making Statements with example?(Switch)
5. Write a short notes on Break, Continue, Goto Statements?
6. Write a C program on calculator using switch case?

UNIT-III:Arrays and Strings

2 MARKS

1. Define Array ? What Is An Index Of An Array?


2. What Is Two Dimensional Array ?
3. What Is String ?
4. Write Syntax For The Following
5. A.Gets() B. Getch() C. Putchar() D.Puts()
6. What Is The Need Of Arrays In C?
7. Discuss Any Two String Handling Functions?

INTRODUCTION TO PROGRAMMING QUESTION BANK


5 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?

Unit-IV:Pointers and User Defined Datatypes


2 MARKS
1. Define Functions in c.
2. What is the difference between function declaration and definition.
3. What is Function call.
4. Define Return types, arguments in c
5. What is scope and lifetime of variables
6. Define Strucures?
7. What Is Union?
8. Differentiate Structures And Unions?

5 MARKS

1. How to declare and initialize structures? Explain with examples


2. Is nesting of structures valid? Justify your answer with an example.
3. Difference Between Call By Value And Call By Reference.
4. Explain Recursion With The Help Of A Program.
5. Explain Local Static Variables And What Is Their Use?
6. What Are The Different Storage Class Specifiers In C?
7. Explain Functions With Arrays As Arguments.

INTRODUCTION TO PROGRAMMING QUESTION BANK


UNIT-V:Functions and File Handling
2 MARKS
1. Define Pointers?
2. How You Declare And Initialize A Pointer?
3. What Is Pointer Arithmatic?
4. Do We Perform Subtraction Or Multiplication Of Two Pointers?Discuss The Reason?
5. What Is User Defined Datatypes?
6. Define Dereferencing Operator?
7. What Is The Need Of Pointers?
8. Define fprintf(),fscanf().
9. What is fopen(),fclose().

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.?

INTRODUCTION TO PROGRAMMING QUESTION BANK


Answers
UNIT-I:Introduction to programming and problem solving

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


4. Global Declaration Section:-

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 :-

It tells the compiler where to start the


execution from.main()
{
point from where execution starts
}
main function has two sections
1. Declaration section: In this, the variables and their data types are declared.
2. Executable section: This has the part of program which actually
performs the task weneed.

5. Sub Program Or Function Section:-

This has all the sub programs or the functions which our program needs.

INTRODUCTION TO PROGRAMMING QUESTION BANK


2. What is Operator Precedence and Associativity in Expression Evaluation?

The concept of operator precedence and associativity in C helps in determining


which operators will be given priority when there are multiple operators in the
expression. It is very common to have multiple operators in C language and the
compiler first evaluates the operater with higher precedence. It helps to maintain the
ambiguity of the expression and helps us in avoiding unnecessary use of parenthesis.
Operator Precedence and Associativity Table
The following tables list the C operator precedence from highest to lowest and the
associativity for each of the operators:
Operator
Precedence Description Associativity

() Parentheses (function call)

[] Array Subscript (Square Brackets)

1 . Dot Operator Left-to-Right

-> Structure Pointer Operator

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement

+/– Unary plus, minus

!,~ Logical NOT, Bitwise complement

2 (type) Cast Operator Right-to-Left

* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

INTRODUCTION TO PROGRAMMING QUESTION BANK


Operator
Precedence Description Associativity

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

Relational less than, less than or equal


< , <=
to
6 Left-to-Right
Relational greater than, greater than or
> , >=
equal to

7 == , != Relational is equal to, is not equal to Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment

*= , /= Multiplication, division assignment


14 Right-to-Left
%= , &= Modulus, bitwise AND assignment

Bitwise exclusive, inclusive OR


^= , |=
assignment

<<=, >>= Bitwise shift left, right assignment

15 , comma (expression separator) Left-to-Right

INTRODUCTION TO PROGRAMMING QUESTION BANK


3. Discuss about the Importance of C. Write down the rules for declaring the variables.
C programming language offers several advantages over other programming languages, including:

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.

Rules for defining a variables:

□ A variable can have alphabets, digits, and underscore.


□ A variable name can start with the alphabet, and underscore only. It can't start with a digit.
□ No whitespace is allowed within the variable name.
□ A variable name must not be any reserved word or keyword, e.g. int, float, etc.

valid names: invalid names:


int a; int 2;
int _ab; int var name;
int a30; int long;

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;

INTRODUCTION TO PROGRAMMING QUESTION BANK


We can also provide values while declaring the variables as given below:

int a=10,b=20; //declaring 2 variable of integer type


float f=20.8;
char c='A';

3. Define I/O functions.Discuss Various I/O functions in c.?


Basic Input/output
Standard input-- used to take the input from the device such as
Keyboard. Standard output--used to send output to a device such as
monitor or screen.Type s o f Inp ut Out put :
There are 2 kinds of I/O functions as given below.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Unformatted I/ O Functions
getchar() :
The getchar() reads character type data from input file stdin. It reads one character at a
time t ill the user pressses the enter key. The getchar() returns a character type. It reads
next character in the input file.
Syntax:
Variablename= getchar();

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);

//getchar putchar example:


#include<stdio.h>
int main()
{
char a;
printf("enter a character \n");
a = getchar();
printf("you entered character is \t");
putchar(a);
return 0;
}
Output:
enter a character
A
you entered character is A

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);

INTRODUCTION TO PROGRAMMING QUESTION BANK


//gets puts example
#include<stdio.h>
int main()
{
char ch[20];
printf("Enter the text: ");
gets(ch);
puts(ch);
return(0);
}
Output:
Enter the text: welcome
welcome

Formatted I nput Output F unctions:


1. . scanf () :
 The scanf() reads all types of data values given by the user and these values are
assigned to the variables. It requires the conversion specification (such as % s and %d )
to identify the type of data to be read during the program execution.
 You need to pass the address of the variable to the scanf function along with other
arguments so that the read values can be assigned to the correct destination.

Syntax: scanf(“control string”, address list);


(or)
scanf(“format specifiers”, &variable1,&variable2…);

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


Addresses list
 It contain addresses of i/o variables proceed the addresses are specified by before the variable by
ampersand (&) operator.

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:

printf(“Format control string”, data_value1, data_value2, . . . , data_valuen);

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

Example program using scanf() and printf() functions:


#include<stdio.h>
int main()
{
int a;
printf("Enter the value of a = ");
scanf("%d",&a);
printf("\nThe value of a = %d",a);
return(0);
}
Output:
Enter the value of a = 10

The value of a = 10

INTRODUCTION TO PROGRAMMING QUESTION BANK


//Example program using field width in print statement
#include<stdio.h>
int main()
{
printf("\n%3d",6);
printf("\n%3d",18);
printf("\n%3d",124);
printf("\n ---- ");
printf("\n%9d",6+18+124);
return 0;
}
Output:
6
18
124

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


Right Justification + format modifier (or) explicit sign display
 The positive sign is used before the width modifier, says to right justify the argument with its
specified width.
Example: printf(“%+10d”,59);
Output: 59
printf() using left and right justification
#include<stdio.h>
int main()
{
printf("%+10s\n","right");
printf("%-10s\n","left");
printf("%+10s\n","abcd");
printf("%-10s\n","abcd");
return 0;
}

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Types of Operators in C:
C operators can be classified into the following types:

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.

Example(where a and b are


variables with some integer
Operator Description value)

+ adds two operands (values) a+b

- subtract second operands from first a-b

* multiply two operands a*b

divide the numerator by the denominator, i.e.


/ divide the operand on the left side with the a/b
operand on the right side

This is the modulus operator, it returns the


% remainder of the division of two operands as the a%b
result

This is the Increment operator - increases the


++ integer value by one. This operator needs only a a++ or ++a
single operand.

This is the Decrement operator - decreases


-- integer value by one. This operator needs onlya --b or b--
single operand.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Program using arithmetic operators:
int main()
{
int a = 50, b = 23, result;
// addition
result = a+b;
printf("Addition of a and b = %d \n",result);
// subtraction
result = a-b;
printf("Subtraction of a and b = %d \n",result);
// multiplication
result = a*b;
printf("Multiplication of a and b = %d \n",result);
// division
result = a/b;
printf("Division of a and b = %d \n",result);
//modulus
result = a%b;
printf("modulus of a and b = %d",result);
return 0;
}

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


2. Increment and decrement operators:
 The increment operator is used to increase the value of any numeric value by 1.
 The decrement operator is used to decrease the value of any numeric value by 1.

++ increment operator, -- decrement operator

 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.

Program for using increment and decrement operators:

#include <stdio.h>

int main()
{

int a = 10, b = 20, c, d;

/* Using increment operator */


printf("Incrementing value of a = %d \n", ++a);

/* Using decrement operator */


printf("Decrementing value of b = %d \n", --b);

// first print value of a, then decrement a


printf("Decrementing value of a = %d \n", a--);
printf("Value of a = %d \n", a);

// first print value of b, then increment b


printf("Incrementing value of b = %d \n", b++);
printf("Value of b = %d \n", b);

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


3. Relational operators in C

 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)

== Check if the two operands are equal a == b, returns 0

a != b, returns 1 because a is not


!= Check if the two operands are not equal. equal to b

Check if the operand on the left is greater than theoperand


> on the right a > b, returns 0

Check operand on the left is smaller than the rightoperand


< a < b, returns 1

check left operand is greater than or equal to theright


>= a >= b, returns 0
operand

Check if the operand on the left is smaller than orequal to


<= a <= b, returns 1
the right operand

Program for relational operators:

#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);

INTRODUCTION TO PROGRAMMING QUESTION BANK


// greater than
result = (a>b);
printf("(a > b) = %d \n",result);

// less than equal to


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 :

C language supports the following 3 logical operators.

Example
Operator Description
(a and b, where a = 1 and b = 0)

&& Logical AND a && b, returns 0

|| Logical OR a || b, returns 1

! Logical NOT !a, returns 0

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Program for logical operators:

#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

following table contains the bitwise operators.

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
~ One’s complement
>> Shift Right
<< Shift Left

INTRODUCTION TO PROGRAMMING QUESTION BANK


The bitwise AND, OR, and NOT operator works the same way as the Logical AND, OR, and NOT
operators, except that the bitwise operators work bit by bit.

we have a truth table for showing how these operators work with different values.

a b a&b a|b a^b

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.

Bitwise >> and << operators

 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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Program for bitwise operators:

#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)

assigns values from right side operandto


= a=b, a gets value 5
left side operand

adds right operand to the left operand


a+=b, is same as a=a+b, value
+= and assign the result to leftoperand
of a becomes 15

subtracts right operand from the left


a-=b, is same as a=a-b, value
-= operand and assign the result to left
operand of a becomes 5

INTRODUCTION TO PROGRAMMING QUESTION BANK


Example
Operator Description (a and b are two variables, with
where a=10 and b=5)

mutiply left operand with the right


a*=b, is same as a=a*b, value
*= operand and assign the result to left
operand of a becomes 50

divides left operand with the right


a/=b, is same as a=a/b, value
/= operand and assign the result to left
operand of a becomes 2

calculate modulus using two operandsand a%=b, is same as a=a%b, value


%=
assign the result to left operand of a becomes 0

 When we combine the arithmetic operators with the assignment operator =, then we getthe
shorthand form of all the arthmetic operators.

Example program Using Assignment 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

INTRODUCTION TO PROGRAMMING QUESTION BANK


7. Ternary Operator (?)/Conditional operator:
The ternary operator, also known as the conditional operator in the C language can be usedfor
statements of the form if-then-else.

The basic syntax for using ternary operator is:

(Expression1)? Expression2 : Expression3;

Here is how it works:

 The question mark ? in the syntax represents the if part.


 The first expression (expression 1) returns either true or false, based on which it isdecided
whether (expression 2) will be executed or (expression 3)
 If (expression 1) returns true then the (expression 2) is executed.
 If (expression 1) returns false then the expression on the right side of : i.e (expression 3)is
executed.

Example Program using ternary operators:


/* Using ternary operator
- If a == b then store a+b in result
- otherwise store a-b in result
*/

#include <stdio.h>
int main()
{

int a = 20, b = 20, result;


result = (a==b)?(a+b):(a-b);

printf("result = %d",result);
return 0;
}

Output:
result = 40

8. Special Operator s: &, *, sizeof, etc:

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Operator Description Example

returns the size(length in bytes)


sizeof of the entity, for eg. a variable sizeof(x) will return the size of the variable x
or an array, etc.

returns the memory address of


& &x will return the address of the variable x
the variable

represents a pointer to an m = &x (memory address of the variable x)


object. The * operator returns
*
the value stored at a memory *m will return the value stored at the memory
address. address m

used to access individual


. (dot) If emp is a structure with an element int age in it,
elements of a C structure or C
operator then emp.age will return the value of age.
union.

used to access structure or


-> (arrow) If p is a pointer to the emp structure, then we can
union elements using a pointer
operator access age element using p->age
to the structure or union.

if arr is an array, then we can access its values


used to access array elements
[] operator using arr[index], where index represents the array
using indexing
index starting from zero

INTRODUCTION TO PROGRAMMING QUESTION BANK


Program using size of and & operator:

#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

6. Discuss about the Data types in C.

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Primitive data types/Primary datatypes in C:

1.Integer Data Type:

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.

□ Range: -2,147,483,648 to 2,147,483,647


□ Size: 4 bytes
□ Format Specifier: %d

Syntax of Integer
We use int keyword to declare the integer variable:
int var_name;

The integer data type can also be used as

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()
{

int a = 9; // Integer value with positive data.

int b = -9; // integer value with negative data.

int c = 89U; // U or u is Used for Unsigned int in C.

long int d = 99998L; // L or l is used for long int in C.

INTRODUCTION TO PROGRAMMING QUESTION BANK


printf("Integer value with positive data: %d\n", a);
printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n", c);
printf("Integer value with an long int data: %ld", d);
return 0;
}

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

2. Character Data Type


Character data type allows its variable to store only a single character. The size of the character is 1
byte.
□ Range: (-128 to 127) or (0 to 255)
□ Size: 1 byte
□ Format Specifier: %c

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 ;

printf("Value of a: %c\n", a);

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;

printf("Value of c: %c", c);

return 0;
}
Output
Value of a: a
Value of a after increment is: b
Value of c: c

INTRODUCTION TO PROGRAMMING QUESTION BANK


3.Float Data Type
In C programming float data type is used to store floating-point values. Float in C is used to store
decimal and exponential values. It is used to store decimal numbers (numbers with floating point
values) with single precision.
□ Range: 1.2E-38 to 3.4E+38
□ Size: 4 bytes
□ Format Specifier: %f

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);

INTRODUCTION TO PROGRAMMING QUESTION BANK


program:
#include <stdio.h>

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

Type Storage size Format specifier Value range Precision


float 4 bytes %f 1.2E-38 to 3.4E+38 6 decimal places
double 8 bytes %lf 2.3E-308 to 1.7E+308 15 decimal places
long double 10 bytes %Lf 3.4E-4932 to 1.1E+4932 19 decimal places

INTRODUCTION TO PROGRAMMING QUESTION BANK


Data Type Size (bytes) Range Format Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to 2,147,483,647 %d

long int 4 -2,147,483,648 to 2,147,483,647 %ld

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 %f
1.2E-38 to 3.4E+38

double 8 %lf
1.7E-308 to 1.7E+308

long double 16 %Lf


3.4E-4932 to 1.1E+4932

INTRODUCTION TO PROGRAMMING QUESTION BANK


5.Void Data Type
The void type, used with the keyword void, has no values and no operations.
Void is an empty data type that has no value.
This can be used in functions and pointers.

7. Discuss about Constants in C.


Constants
 Constants are data values that cannot be changed during the execution of a program. Like
variables, constants have a type.
Types of constants:
1. Numeric constants
a) Integer constants:
Decimal,Octal,Hexadecimal
b) Real constants
2. Character constants
Single character constants
String constants

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:

The decimal constant is: 42

INTRODUCTION TO PROGRAMMING QUESTION BANK


Octal Constant:

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:

The octal constant is: 52


Hexadecimal Constant:

A base-16 value is represented by a hexadecimal constant. It uses letters A to F (or a to f) and


numbers 0 to 9 to represent values from 10 to 15. It is prefixed with '0x' or '0X' to identify it as a
hexadecimal constant.

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:

The hexadecimal constant is: 2a

2. Real or Floating-Point Constant:

A fractional component or exponentiation of a number is represented by a real or floating-point


constant. It can be expressed with a decimal point, the letter "E", or the symbol "e" in exponential or
decimal notation.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Example:

#include <stdio.h>

int main()
{
float real = 3.14;
printf("The real constant is: %f\n", real);
return 0;
}
Output:

The real constant is: 3.140000

2. Character Constant:

Single character constant:

A character constant represents a single character that is enclosed in single quotes.

Example: char c=’a’;


char c=’5’;
ASCII character Symbolic name ASCII character Symbolic name
Null character ‘\0’ Form feed ‘\f’
Alert (bell) ‘\a’ Carriage return ‘\r’
Backspace ‘\b’ Single quote ‘\’’
Horizontal tab ‘\t’ Double quote ‘\”’
New line ‘\n’ Backslash ‘\\’
Vertical tab ‘\v’

Example:

#include <stdio.h>

int main()
{
char character = 'A';
printf("The character constant is: %c\n", character);
return 0;
}
Output:

The character constant is: A

INTRODUCTION TO PROGRAMMING QUESTION BANK


String Constant:

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

1) Using const keyword


The const keyword is used to define constant in C programming.

Syntax:

const datatype variablename=value;

eg: const float PI=3.14; // Now, the value of PI variable can't be changed.

Program:
#include<stdio.h>

INTRODUCTION TO PROGRAMMING QUESTION BANK


int main()
{
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}

Output:

The value of PI is: 3.140000

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

2) Using #define preprocessor

The #define preprocessor is also used to define constant.

Syntax:

#define datatype variablename value

Example program:

#include <stdio.h>
#define PI 3.14
int main()
{
printf("%f",PI);
return 0;
}
Output:
3.140000

INTRODUCTION TO PROGRAMMING QUESTION BANK


Boolean constants:
 A Boolean data type can take only 2 values. The values are true and false.
 When we use the Boolean constant must include the Boolean library, stdbool.h.
Example:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool x = false;
if(x== true)
printf("x is true.");
else
printf("x is false.");
return 0;
}
Output:
x is false.

8. Define Algorithm?Explain the characterstics of Algorithm with example?Define Flowchart?


What are the symbols used in Flowchart?Explain with example?
Algorithm:A programming algorithm is a step by step procedure used for solving a problem.
Example:
Write an algorithm to find the largest of 2 numbers?
Algorithm:
Step 1: Start
Step 2: Input the values of A, B
Step 3: Compare A and B.
Step 4: If A > B then go to step 6
Step 5: Print “B is largest” go to Step 7
Step 6: Print “A is largest”
Step 7: Stop
Flowchart: Flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning
tool to solve a problem. It makes use of symbols which are connected among them toindicate the flow of information
and processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.
Basic Symbols used in Flowchart Designs:
1. Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt is
generally used in a program logic under some error conditions. Terminal is the first and last
symbols in the flowchart.

□ Input/Output: A parallelogram denotes any function of input/output type. Program


instructions that take input from input devices and display output on output devices are
indicated with parallelogram in a flowchart.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Processing: A box represents arithmetic instructions. All arithmetic processes such as
adding, subtracting, multiplication and division are indicated by action or process symbol.

□ 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.

Rules For Creating Flowchart :


A flowchart is a graphical representation of an algorithm.it should follow some rules while
creating a flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: The decision symbol in the flowchart is associated with the arrow line.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Advantages of Flowchart:
□ Flowcharts are a better way of communicating the logic of the system.
□ Flowcharts act as a guide for blueprint during program designed.
□ Flowcharts help in debugging process.
□ With the help of flowcharts programs can be easily analyzed.
□ It provides better documentation.

□ Flowcharts serve as a good proper documentation.


□ Easy to trace errors in the software.
□ Easy to understand.
□ The flowchart can be reused for inconvenience in the future.
□ It helps to provide correct logic.

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


9. What is Type Conversion and Type Casting .Explain in detail?
Type Conversion
 Type converse on can be defined as converting one data type into another data type.
 There are 2 different type conversions are there they are:
1. Automatic or implicit type conversion.
2. Type casting or explicit type conversion.
Implicit Type Conversion
 When the type conversion is performed automatically by the compiler without
programmerintervention such type of conversion is known as implicit type conversion.
 If operators are different types the lower type is automatically converted to higher type
beforeoperation proceed.
 The following Figure shows the ranks as we use them for conversion.

INTRODUCTION TO PROGRAMMING QUESTION BANK


 There are two types of conversions in implicit type conversion as:
1. Assignment Type Conversion
2. Automatic Type Conversion
Assignment Type Conversion
 This means that the value of the expression on the right side of the equal sign is converted to the
data type of the variable to the left of the equal sign.
Example: result = 4;
 When ‘result’ is declared as double ‘4’ is an integer then ‘4’ will be converted to the double
Precision value 4.0 and the value is assigned to the result.
Automatic Type Conversion
 The data type have lower rank is converted automatically in to higher rank data before the
operation process.
 This automatic conversion across an assignment operator is referred to as integer type conversion

 Example:int num = 10;


double result = (double) num;
// Implicitly converts 'num' to a double

Example program for implicit type conversion


#include <stdio.h>
int main ()
{
double a = 2.5,s;
int b=2;
s=a+b;
printf("value of s = %d “, s);
}
Output:
value of s = 4

INTRODUCTION TO PROGRAMMING QUESTION BANK


Explicit Type Conversion/Type Casting
 Type conversion performed by the programmer to change the data type of the expression of a
specific type is known as explicit type conversion.
Syntax: (data type) expression
Example: double pi = 3.14159265359;

int roundedPi = (int) pi; // Explicitly casts 'pi' to an integer

Example program for explicit type conversion


#include <stdio.h>
int main() {
double pi = 3.14159265359;
int roundedPi = (int) pi; // Explicitly casting 'pi' to an integer
printf("Original value of pi: %lf\n", pi);
printf("Rounded value of pi: %d\n", roundedPi);
return 0;
}
Output:Original value of pi: 3.141593
Rounded value of pi: 3
Example2:
#include <stdio.h>
int main() {
int num = 42;
char character = (char) num; // Explicitly casting 'num' to a char
printf("Original value of num: %d\n", num);
printf("Character representation: %c\n", character);
return 0;
}
Output:
Original value of num: 42
Character representation: *

9. Write a short note on Time and Space Complexity?


Time and Space Complexicity of an algorithm:
Time complexity is the time taken by the algorithm to execute each set of instructions.
It is always better to select the most efficient algorithm when a simple problem can solve with different
methods.
The time complexity of an algorithm is the total amount of time required by an algorithm to complete its
execution.
Generally, the running time of an algorithm depends upon the following...

1. Whether it is running on Single processor machine or Multi processor machine.


2. Whether it is a 32 bit machine or 64 bit machine.
3. Read and Write speed of the machine.
4. The amount of time required by an algorithm to
perform Arithmetic operations, logical operations, return value and assignment operations etc.,
5. Input data

INTRODUCTION TO PROGRAMMING QUESTION BANK


Consider the following piece of code...
Example 1
int sum(int a, int b)
{
return a+b;
}
In the above sample code, it requires 1 unit of time to calculate a+b and 1 unit of time to return the value.
That means, totally it takes 2 units of time to complete its execution. And it does not change based on the
input values of a and b. That means for all input values, it requires the same amount of time i.e. 2 units.
If any program requires a fixed amount of time for all input values then its time complexity is said to
be Constant Time Complexity.

Consider the following piece of code...


Example 2
int sum(int A[], int n)
{
int sum = 0, i;
for(i = 0; i < n; i++)
sum = sum + A[i];
return sum;
}

For the above code, time complexity can be calculated as follows

INTRODUCTION TO PROGRAMMING QUESTION BANK


In above calculation
Cost is the amount of computer time required for a single operation in each line.
Repeatation is the amount of computer time required by each operation for all its repeatations.
Total is the amount of computer time required by each operation to execute.
So above code requires '4n+4' Units of computer time to complete the task. Here the exact time is not fixed. And it
changes based on the n value. If we increase the n value then the time required also increases linearly.

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...

1. To store program instructions.


2. To store constant values.
3. To store variable values.
4. And for few other things like funcion calls, jumping statements etc,.

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.

Consider the following code..


int square(int a)
{
return a*a;
}
In the above piece of code, it requires 2 bytes of memory to store variable 'a' and another 2 bytes of memoryis used for
return value.
That means, totally it requires 4 bytes of memory to complete its execution. And this 4 bytes of memory
is fixed for any input value of 'a'. This space complexity is said to be Constant Space Complexity.

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


11. Explain the Block Diagram of Computer Organization?
Basic organization of a computer: ALU, input-output units,
memory,program counter:
A Central Processing Unit is the most important component of a computer system. A CPU is
ahardware that performs data input/output, processing and storage functions for a computer
system.
A computer consists of 5 functionally independent main parts:
1) input, 2)memory,3)arithmetic & logic unit(ALU) 4)output and 5)control units.
Input Unit :
The input unit consists of input devices such as a mouse, keyboard, scanner ,joystick etc.
These devices are used to input information or instruction into the computer system. That is that input
unit takes data from us to the computer in an organized for processing.
The input unit performs the following major functions:
-The input unit converts the inputted data or instructions into binary form for further processing.
-Input unit transmits the data to the main memory of the computer.
Output Unit:
Output unit consists of devices that are used to display the results or output of processing. The output
datais first stored in the memory and then displayed in human readable form through output devices.
Examples : monitor, printer, projector, graphic displays etc.
The output unit performs the following major functions:
-The output unit accepts the data or information in binary form from the main memory of the
computersystem.
-The output unit converts the binary data into a human –readable form for better understanding.
CPU(Central Processing Unit):
CPU is known as the brain of the computer system. It is an electronic hardware device that processes
allthe operations (eg: arithmetic and logical operations) of the computer. In other words, all the major
calculations , operations or comparisons are performed inside the CPU.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Control Unit:
The control unit of a CPU controls all the activities and operations of the computer. It is also responsible for
controlling input/output , memory and other devices connected to the CPU.
The control unit acts like the supervisor which determines the sequence in which computer programs and instructions
are executed.
ALU (Arithmetic Logic Unit) :
ALU (Arithmetic Logic Unit) is responsible for performing arithmetic and logical functions or operations.
It consists of two subsections, which are:
 Arithmetic Section
 Logic Section
 Arithmetic Section: By arithmetic operations, we mean operations like addition, subtraction,
multiplication, and division, and all these operation and functions are performed by ALU. Also, all the
complex operations are done by making repetitive use of the mentioned operations by ALU.
 Logic Section: By Logical operations(AND ,OR etc), we mean operations or functions like selecting,
comparing, matching, and merging the data, and all these are performed by ALU. 
 Note: CPU may contain more than one ALU and it can be used for maintaining timers that help run the
computer system.

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).

INTRODUCTION TO PROGRAMMING QUESTION BANK


NOTE: Primary memory is the only memory that is directly accessible to the CPU.
Secondary memory is not directly accessible to the CPU. The data accessed from
the secondary unit is first loaded into RAM and then further transferred to the
processing unit.

2 MARKS

11. Define Identifier

An identifier in programming refers to a name used to identify a variable, function, class, or


any other user-defined item in a program. It serves as a label to represent a specific element,
allowing the programmer to reference it throughout the code.

Key characteristics of identifiers:

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.

In the C programming language, an identifier is a name used to identify variables, functions,


arrays, types, or any other user-defined items. It is a fundamental concept in C programming,
enabling programmers to refer to data and functions in the program.

Key Rules for Identifiers in C:

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.

Example of Valid Identifiers in C:


int totalAmount; // Valid: Starts with a letter
int _count; // Valid: Starts with an underscore
float calculateSum; // Valid: Consists of letters

INTRODUCTION TO PROGRAMMING QUESTION BANK


int x1;
Example of Not Valid Identifiers in C:
// Valid: Contains a digit after the first letter
int 2ndValue; // Invalid: Starts with a digit
int float; // Invalid: Reserved keyword (float is a keyword)

12. Define Keyword.

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.

Common Examples of Keywords in C:

 Data types: int, char, float, double, void


 Control statements: if, else, switch, case, while, for, return
 Storage class specifiers: static, extern, auto, register
 Type qualifiers: const, volatile
 Function-related: sizeof, typedef, enum
 Others: goto, continue, break, struct, union, long, short, signed, unsigned

auto double int struct break else long switch


case enum register union char extern return unsigned
const float short void continue for signed volatile
default goto sizeof while do if static inline
Example of Keywords in C:

#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
}

13. What Are Data Types?

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


types are essential because they determine how much memory a variable will occupy and what
kind of data can be stored in it.

Categories of Data Types in C:

1. Basic (Primitive) Data Types


2. Derived Data Types
3. User-defined Data Types
4. Void Data Type

1. Basic Data Types

These are the fundamental data types provided by C. They include:

 Integer Types: Used to represent whole numbers (positive, negative, or zero).


o int: Typically used for integers. Size is often 4 bytes (32 bits).
o short: A smaller integer type (typically 2 bytes).
o long: A larger integer type (typically 4 or 8 bytes).
o long long: An even larger integer type (typically 8 bytes).

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:

float pi = 3.14f; // 4 bytes


double e = 2.71828; // 8 bytes
long double phi = 1.618; // 12 or 16 bytes

 Character Type: Used to store individual characters.


o char: A single byte (typically 1 byte) used to store characters (e.g., 'A', 'b', '3').

Example:

char letter = 'A'; // 1 byte

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.

2. Derived Data Types

These are types that are derived from the basic data types. They include:

 Arrays: A collection of elements of the same data type.

int arr[5] = {1, 2, 3, 4, 5}; // Array of integers

INTRODUCTION TO PROGRAMMING QUESTION BANK


 Pointers: A variable that stores the memory address of another variable.

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];
};

 Enumerations (enums): A user-defined type that consists of a set of named integer


constants.

enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };


3. User-Defined Data Types

These data types are created by the programmer using the typedef keyword, structures, unions,
or enums. They allow more flexibility and organization in code.

Example using typedef:

typedef unsigned int uint;

uint x = 5; // Equivalent to 'unsigned int x = 5;'


4. Void Data Type

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");
}

void *ptr; // Void pointer

INTRODUCTION TO PROGRAMMING QUESTION BANK


Summary of Common Data Types in C:
Data Type Description Size (in bytes)
int Integer numbers 4
short Smaller integer numbers 2
long Larger integer numbers 4 or 8
long long Even larger integer numbers 8
float Floating-point numbers (single precision) 4
double Floating-point numbers (double precision) 8
long double Extended precision floating-point numbers 12 or 16
char Single character 1
unsigned Non-negative integers (applies to int, char, long, etc.) -
void Represents no value or no type N/A

14. List Out Any Ten Data Types.

Here are ten data types in C:

1. int: Used to represent integer (whole) numbers.


o Example: int num = 10;
2. float: Used to represent single-precision floating-point numbers.
o Example: float pi = 3.14;
3. double: Used to represent double-precision floating-point numbers (larger range and
precision than float).
o Example: double e = 2.71828;
4. char: Used to represent a single character (stored as an integer value based on ASCII).
o Example: char letter = 'A';
5. long: Used to represent larger integer values, typically 4 or 8 bytes depending on the
system.
o Example: long population = 7000000;
6. short: Used for smaller integer values (typically 2 bytes).
o Example: short age = 25;
7. long long: Used for even larger integers (typically 8 bytes).
o Example: long long distance = 123456789;
8. unsigned int: An unsigned integer type that can only store positive values and zero.
o Example: unsigned int counter = 0;
9. unsigned char: An unsigned character type that can store values between 0 and 255.
o Example: unsigned char byte = 255;
10. void: Represents the absence of any type, commonly used for functions that don’t
return a value or for generic pointers (void *).

 Example: void printMessage() { printf("Hello!"); }

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.

15. What Is Meant By Constants?

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


program's lifetime. Constants are useful for representing values that do not change, such as
mathematical constants (e.g., π), configuration settings, or fixed limits.

16. Define Variables.

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.

Key Characteristics of Variables in C:

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.

How to Declare a Variable in C:

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

data_type variable_name = value;


Example:
int age; // Declares an integer variable 'age'
float salary = 50000.5; // Declares and initializes a float variable 'salary'
char grade = 'A'; // Declares and initializes a char variable 'grade'
Types of Variables in C:

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:

int globalVar = 10; // 'globalVar' is a global variable

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


o Example:

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;

// In the main file:


int x = 5; // Definition of 'x' variable
Variable Initialization:

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.

1. Initialization during declaration:

int a = 10; // Variable 'a' is initialized with value 10


float pi = 3.14; // 'pi' is initialized with a floating-point value

2. Initialization after declaration:

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>

int globalVar = 100; // Global variable

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:

INTRODUCTION TO PROGRAMMING QUESTION BANK


 localVar is a local variable accessible only within the display() function.
 globalVar is a global variable accessible both inside the display() function and elsewhere in the
program.

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.

17. What Is Meant By Expressions?

In C programming, an expression is a combination of variables, constants, operators, and


functions that are evaluated to produce a value. An expression can be as simple as a single
constant or variable, or it can be a more complex combination of various components.
Expressions are fundamental in C, as they allow you to perform calculations, make decisions,
and manipulate data.

Key Characteristics of Expressions:

 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:

1. Arithmetic Expressions: These expressions perform mathematical operations like


addition, subtraction, multiplication, and division.

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)

Example of a more complex arithmetic expression:

int a = 5, b = 3;
int result = (a * b) + (a - b); // result = 5*3 + (5-3) = 15 + 2 = 17

2. Relational Expressions: These expressions are used to compare two values or


variables and return a boolean result (true or false), represented as 1 or 0 in C.

Common relational operators:

INTRODUCTION TO PROGRAMMING QUESTION BANK


o == (Equal to)
o != (Not equal to)
o < (Less than)
o > (Greater than)
o <= (Less than or equal to)
o >= (Greater than or equal to)

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.

Common logical operators:

o && (Logical AND)


o || (Logical OR)
o ! (Logical NOT)

Example:

int a = 10, b = 5, c = 15;


if ((a > b) && (c > a)) {
printf("Both conditions are true\n");
}

4. Assignment Expressions: These expressions assign a value to a variable. The


assignment operator is =, but there are also shorthand assignment operators like +=, -=,
*=, etc.

Example:

int a = 5;
a += 3; // Equivalent to a = a + 3; a is now 8

5. Bitwise Expressions: Bitwise expressions operate on individual bits of integer


variables.

Common bitwise operators:

o & (Bitwise AND)


o | (Bitwise OR)
o ^ (Bitwise XOR)
o ~ (Bitwise NOT)
o << (Left shift)
o >> (Right shift)

Example:

int a = 5; // binary: 0101


int b = 3; // binary: 0011

INTRODUCTION TO PROGRAMMING QUESTION BANK


int result = a & b; // binary AND, result is 1 (0001)

6. Conditional (Ternary) Expressions: A shorthand for an if-else statement, the ternary


operator ? : takes three operands.

Syntax:

condition ? expression1 : expression2;

If the condition is true, expression1 is evaluated; otherwise, expression2 is evaluated.

Example:

int a = 10, b = 5;
int result = (a > b) ? a : b; // result = 10 (since a > b)

7. Increment and Decrement Expressions: These are shorthand operators used to


increase or decrease a variable's value by 1.
o ++ (Increment) adds 1 to the value of a variable.
o -- (Decrement) subtracts 1 from the value of a variable.

Example:

int x = 5;
x++; // x is now 6
x--; // x is now 5 again

8. Pointer Expressions: In C, pointers hold memory addresses. Expressions involving


pointers manipulate or dereference these memory addresses.

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;

INTRODUCTION TO PROGRAMMING QUESTION BANK


}
Conclusion:

An expression in C is a combination of variables, constants, operators, and functions that


evaluates to a value. Expressions are used throughout C programs to perform calculations,
make comparisons, assign values, and control program flow. Understanding how to create and
evaluate expressions is crucial for writing effective and efficient C programs.

18. Define Statements? What Is Meant By Operators?


Statements in C:

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:

1. Expression Statements: These involve performing operations like assignments or


function calls.
o Example:

int x = 5; // Assignment statement


x = x + 10; // Another assignment statement

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");
}

o for, while, and do-while loops: Iteration and repetition.

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


printf("%d\n", i);
}

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.

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


if (i == 2) continue; // Skip the iteration when i is 2

INTRODUCTION TO PROGRAMMING QUESTION BANK


printf("%d\n", i);
}

o return: Exits from a function and optionally returns a value.

return 0; // Exits the function and returns 0

4. Declaration Statements: These statements declare variables and specify their data
types.
o Example:

int a = 5; // Declares an integer variable a and initializes it with 5

5. Compound Statement (Block): A compound statement groups multiple statements


together in a single block enclosed by curly braces {}.
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:

An operator in C is a symbol that tells the compiler to perform a specific mathematical,


logical, or relational operation. Operators are used to manipulate data or variables in various
ways, such as performing arithmetic, comparing values, or combining multiple conditions.

There are different types of operators in C, including arithmetic operators, relational


operators, logical operators, bitwise operators, and more.

Types of Operators in C:

1. Arithmetic Operators: These operators are used to perform basic mathematical


operations.
o + (Addition)
o - (Subtraction)
o * (Multiplication)
o / (Division)
o % (Modulus - remainder after division)

Example:

INTRODUCTION TO PROGRAMMING QUESTION BANK


int x = 5, y = 3;
int sum = x + y; // sum = 8
int remainder = x % y; // remainder = 2

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");
}

4. Assignment Operators: These operators are used to assign values to variables.


o = (Simple assignment)
o += (Add and assign)
o -= (Subtract and assign)
o *= (Multiply and assign)
o /= (Divide and assign)

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


6. Bitwise Operators: These operators perform operations on individual bits of integers.
o & (Bitwise AND)
o | (Bitwise OR)
o ^ (Bitwise XOR)
o ~ (Bitwise NOT)
o << (Left shift)
o >> (Right shift)

Example:

int x = 5; // binary: 0101


int y = 3; // binary: 0011
int z = x & y; // z = 1 (binary: 0001)

7. Conditional (Ternary) Operator: This operator provides a shorthand way of


performing an if-else condition.
o Syntax: condition ? expression1 : expression2;

Example:

int x = 10, y = 5;
int max = (x > y) ? x : y; // max is assigned the larger of x and y

8. Pointer Operators: These operators are used to work with pointers in C.


o & (Address-of operator): Returns the memory address of a variable.
o * (Dereference operator): Accesses the value at the memory address a pointer is
pointing to.

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.

19. What Is Meant By Linking Process?


Linking Process 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.

Key Points of the Linking Process:

INTRODUCTION TO PROGRAMMING QUESTION BANK


1. Combining Object Files:
o After the C source code is compiled, each source file (.c file) is transformed into an
object file (.o or .obj file) by the compiler.
o These object files contain machine code but may have unresolved references, such as
calls to functions or variables that are defined in other files or external libraries.
o The linker combines all these object files into a single executable file ( .exe or no
extension, depending on the operating system).
2. Resolution of External Symbols:
o An object file might reference functions, variables, or other resources that are defined
elsewhere, such as in another source file or a library.
o The linker resolves these references by searching through the object files and libraries
to find the correct memory addresses for these symbols.
o For example, if one object file calls a function defined in another object file, the linker
updates the code to point to the correct location of the function in the final executable.
3. Static Linking vs. Dynamic Linking:
o Static Linking: In static linking, all the necessary code from libraries (e.g., the C
standard library or user-defined libraries) is copied directly into the executable. This
creates a standalone executable, which does not rely on external files at runtime.
 Example: When you link your program with gcc using gcc -o myprogram
myprogram.c -lm, the linker includes the necessary library code into the
executable file.
o Dynamic Linking: In dynamic linking, the executable does not contain all the library
code. Instead, it relies on external shared libraries (such as .dll files on Windows or .so
files on Linux) at runtime. The linker inserts placeholders for the external libraries
during compilation, and the operating system loads the libraries into memory when the
program runs.
 Example: When you link with gcc -o myprogram myprogram.c -lm, it links
dynamically to the libm.so library, which is loaded during program execution.
4. Symbol Resolution and Address Binding:
o The linker resolves symbols, such as function names and global variable names, to
their correct memory addresses.
o For example, if you have a global variable in one object file, the linker makes sure that
the reference to that variable in another object file points to the correct address.
o The linker also determines the actual memory locations where code and data will
reside in the final executable.
5. Creating the Executable:
o Once all the object files are combined and all symbols are resolved, the linker
generates the final executable file. This file contains machine code that can be
executed by the operating system.
o The executable file can then be run directly without needing any source code or
intermediate files.

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


o All code required for execution is present in the final executable, so the program is
independent of external libraries once linked.

Example:

gcc myprogram.c -o myprogram -lm // Links the math library statically

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:

gcc myprogram.c -o myprogram -lm // Links dynamically to the math library


Common Linker Errors:

During the linking process, several errors may arise, including:

1. Unresolved External Symbol:


o This error occurs when a function or variable referenced in your program is not
defined in any of the object files or libraries provided to the linker.
o 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.

Example of the Linking Process:

Consider two source files:

INTRODUCTION TO PROGRAMMING QUESTION BANK


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

extern void greet(); // Declaration of the function in file2.c

int main() {
greet(); // Calling the function
return 0;
}

// file2.c
#include <stdio.h>

void greet() { // Definition of the function


printf("Hello, World!\n");
}

Compilation:

1. gcc -c file1.c → This creates file1.o.


2. gcc -c file2.c → This creates file2.o.

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.

20. Define Void?

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:

1. Void as a Return Type (Function Declaration)

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>

// Function with void return type (no return value)


void greet() {
printf("Hello, World!\n");

INTRODUCTION TO PROGRAMMING QUESTION BANK


}

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.

2. Void Pointers (void *)

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>

void printValue(void *ptr, char type) {


if (type == 'i') {
printf("Integer: %d\n", *(int *)ptr); // Casting void pointer to int pointer
} else if (type == 'f') {
printf("Float: %.2f\n", *(float *)ptr); // Casting void pointer to float pointer
}
}

int main() {
int x = 10;
float y = 5.5;

// Passing void pointer to different data types


printValue(&x, 'i'); // Prints the integer
printValue(&y, 'f'); // Prints the float

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.

3. Void in Function Parameters

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>

// Function with void parameter (no input arguments)

INTRODUCTION TO PROGRAMMING QUESTION BANK


void sayHello(void) {
printf("Hello, World!\n");
}

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.

4. Void in Typedefs (Optional Use)

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.

Summary of void Usage in C:

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:

The void keyword in C is versatile and serves several purposes:

INTRODUCTION TO PROGRAMMING QUESTION BANK


 It can indicate that a function does not return a value or does not take parameters.
 It is used to declare generic pointers (void *) that can point to any data type.
 It provides flexibility when dealing with functions that operate on unknown or multiple data
types.

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

2. Define Looping Statement .?

The looping statements are used to execute a single statement or block of statements repeatedly until

the given condition is FALSE.

C language provides three looping statements...

 while statement

 do-while statement

 for statement

3. Define Unconditional Statement.?


In c, there are control statements that do not need any condition to control the program execution flow.

These control statements are called as unconditional control statements. C programming language

provides the following unconditional control statements...

 break

 continue

 goto

INTRODUCTION TO PROGRAMMING QUESTION BANK


 The above three statements do not need any condition to control the program execution flow.

4. Define Simple If Statement.?


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 next
statement or block of statements. If the condition is FALSE, it skips the execution of the next statement or
block of statements. The general syntax and execution flow of the simple if statement is as follows.

5. Define Switch Statement.?


In C programming, a switch case is a control statement that allows you to test a variable or expression
against a series of values (called "cases") and execute the corresponding block of code for the first
matching case. It provides a more efficient way of handling multiple conditions compared to using
several if-else statements.
Program:
#include <stdio.h>
int main() {
int number = 2;
switch (number)
{
case 1: printf("Number is 1\n");
break;
case 2: printf("Number is 2\n");
break;
case 3: printf("Number is 3\n");
break;
default: printf("Number is not 1, 2, or 3\n");
}
return 0;
}
Output: number is 2
6. Define For Statement.?
In C programming, a for statement is a control flow statement used to create loops that execute a
block of code a specific number of times. It is commonly used when the number of iterations is

INTRODUCTION TO PROGRAMMING QUESTION BANK


known in advance.
Syntax:
{
for (initialization; condition; increment/decrement) ;
}
Program:
#include <stdio.h>
int main()
{
for (int i = 1; i <= 5; i++)
{
printf("Iteration %d\n", i);
}
return 0;
}
Output:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
7. Define Goto Statement.?
The goto statement is used to jump from one line to another line in the program. Using goto statement we
can jump from top to bottom or bottom to top. To jump from one line to another line, the goto statement
requires a label.
Program:
#include<stdio.h>
#include<conio.h>

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:

8. Define Break Statement.?


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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


9. Define Exit Statement.?

In C programming, the exit statement is used to terminate a program immediately. It is part of


the stdlib.h library and can be used to indicate the program's termination status to the operating
system.

Syntax:
exit(status);
□ 0 indicates successful program termination.
□ A non-zero value indicates an error or abnormal termination
Common Use Cases:

 Exiting the program when encountering an unrecoverable error.


 Ending a program based on certain conditions during runtime.

10. What Is Getchar().?

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.

Syntax: int getchar(void);


program:
#include <stdio.h>

int main() {
char ch;

printf("Enter a character: ");


ch = getchar(); // Reads a single character from input

printf("You entered: %c\n", ch);

return 0;
}

INTRODUCTION TO PROGRAMMING QUESTION BANK


Input/Output:

Enter a character: A
You entered: A

11. Define Putchar().?

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.

Syntax: int putchar(int char);


Program:
#include <stdio.h>

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?

CONDITIONAL CONTROL STATEMENTS: Decision making (or) branching (or) selection


statements:
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. The result is in the
form of two expressions true or false. There are two decision-making statements
1. if statement
2. switch statement
In C, if statement is used to make decisions based on a condition. The if statement verifies the given
condition and decides whether a block of statements are executed or not based on the condition result.
if statement is classified into four types as follows...

INTRODUCTION TO PROGRAMMING QUESTION BANK


1. Simple if statement
2. if-else statement
3. Nested if statemen
4. if-else-if statement (if-else ladder)

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

. Example program to test whether the given number is divisible by5:


#include
void main()
{
int n ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 5\n") ;
printf("statement does not belong to if!!!") ;
}
Output1:
Enter any integer number: 50
Given number is divisible by 5 statement does not belong to if!!!
Output2:
Enter any integer number: 33
statement does not belong to if!!!

1.2 if-else statement


The if-else statement is used to verify the given condition and executes only one out of the two blocks of
statements based on the condition result. The if-else statement evaluates the specified condition. If it is
TRUE, it executes a block of statements (True block). If the condition is FALSE, it executes another block
of statements (False block). The general syntax and execution flow of the if-else statement is as follows.

INTRODUCTION TO PROGRAMMING QUESTION BANK


The if-else statement is used when we have two options and only one option has to be executed based on a
condition result (TRUE or FALSE).

Example Program | Test whether given number is even or odd.

#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:

INTRODUCTION TO PROGRAMMING QUESTION BANK


1.3 Nested if statement
Writing a if statement inside another if statement is called nested if statement. The general syntax of the
nested if statement is as follows...

The nested if statement can be defined using any combination of simple if & if-else statements.

Example Program | Test whether given number is even or odd if it


is below 100.
#include<stdio.h>
#include<conio.h>

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") ;
}

INTRODUCTION TO PROGRAMMING QUESTION BANK


Output 1:

Output 2:

1.4 if-else-if statement (if-else ladder)


Writing a if statement inside else of an if statement is called if-else-if statement. The general syntax of the
if-else-if statement is as follows...

The if-else-if statement can be defined using any


combination of simple if & if-else statements.

Example Program | Find the largest of three numbers.


#include<stdio.h>
#include<conio.h>

void main(){
int a, b, c ;

INTRODUCTION TO PROGRAMMING QUESTION BANK


clrscr() ;

printf("Enter any three integer numbers: ") ;


scanf("%d%d%d", &a, &b, &c) ;

if( a>=b && a>=c)


printf("%d is the largest number", a) ;

else if (b>=a && b>=c)


printf("%d is the largest number", b) ;

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

using a switch statement.

The switch statement has the following syntax and execution flow diagram.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Example Program | Display pressed digit in words.
#include<stdio.h>
#include<conio.h>

void main(){
int n ;
clrscr() ;

printf("Enter any digit: ") ;


scanf("%d", &n) ;

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") ;

INTRODUCTION TO PROGRAMMING QUESTION BANK


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:

8. Explain Looping (or) Iterative Statements with example?(For,While,Do-


While).?

The looping statements are used to execute a single statement or block of statements repeatedly until

the given condition is FALSE.

C language provides three looping statements...

 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

INTRODUCTION TO PROGRAMMING QUESTION BANK


as the given condition is TRUE. The while statement is also known as Entry control looping

statement.

 The while statement has the following syntax...

INTRODUCTION TO PROGRAMMING QUESTION BANK


At first, the given condition is evaluated. If the condition is TRUE, the single statement or block of
statements gets executed. Once the execution gets completed the condition is evaluated again. If it is TRUE,
again the same statements get executed Whenever the condition is evaluated to FALSE, the execution
control moves out of the while block.
Whenever the condition is evaluated to FALSE, the execution control moves out of the while block.

Example Program | Program to display even numbers upto 10.


#include<stdio.h>
#include<conio.h>
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");

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.

The do-while statement has the following syntax...

INTRODUCTION TO PROGRAMMING QUESTION BANK


The do-while statement has the following execution flow diagram...

Example Program | Program to display even numbers upto 10.


#include<stdio.h>
#include<conio.h>

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 ) ;

INTRODUCTION TO PROGRAMMING QUESTION BANK


getch() ;
}

Output:

3. 'for' statement :
The for statement is used to execute a single statement or a block of statements repeatedly as long as the

given condition is TRUE.

The for statement has the following syntax and execution flow diagram...

INTRODUCTION TO PROGRAMMING QUESTION BANK


Example Program | Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>

void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
for( n = 0 ; n <= 10 ; n++ )
{
if( n%2 == 0)

INTRODUCTION TO PROGRAMMING QUESTION BANK


printf("%d\t", n) ;
}
getch() ;
}

Output:

10. Explain Pre-Tested and Post Tested Loops with example?

In c language there two different types of loops they are as follows…


1.pre tested loops
2.post tested loops

1.pre tested loops:


A pre-tested loop, also known as a precondition loop, is a control structure in programming
where the loop's condition is evaluated before the body of the loop is executed. If the
condition evaluates to true, the loop runs; otherwise, it terminates immediately without
executing its body even once.

The most common examples of pre-tested loops are:

 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.

 The while statement has the following syntax...

INTRODUCTION TO PROGRAMMING QUESTION BANK


At first, the given condition is evaluated. If the condition is TRUE, the single statement or block of
statements gets executed. Once the execution gets completed the condition is evaluated again. If it is TRUE,
again the same statements get executed Whenever the condition is evaluated to FALSE, the execution
control moves out of the while block.
Whenever the condition is evaluated to FALSE, the execution control moves out of the while block.

Example Program | Program to display even numbers upto 10.


#include<stdio.h>
#include<conio.h>
void main(){
int n = 0;

INTRODUCTION TO PROGRAMMING QUESTION BANK


clrscr() ;
printf("Even numbers upto 10\n");

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

given condition is TRUE.

The for statement has the following syntax and execution flow diagram...

INTRODUCTION TO PROGRAMMING QUESTION BANK


Example Program | Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>

void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
for( n = 0 ; n <= 10 ; n++ )
{
if( n%2 == 0)

INTRODUCTION TO PROGRAMMING QUESTION BANK


printf("%d\t", n) ;
}
getch() ;
}

Output:

2. post tested loops:

A post-tested loop, also known as a postcondition loop, is a control structure in programming


where the condition is evaluated after the body of the loop has executed. This guarantees that
the loop body will execute at least once, regardless of whether the condition is true or false
initially.

The most common examples of post-tested loops are:

 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.

The do-while statement has the following syntax...

The do-while statement has the following execution flow diagram...

INTRODUCTION TO PROGRAMMING QUESTION BANK


Example Program | Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>

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:

INTRODUCTION TO PROGRAMMING QUESTION BANK


11. Expalin Multidecision Making Statements with example?(Switch).?

In programming, multidecision making statements allow developers to evaluate multiple


conditions and execute corresponding actions depending on which condition is met. The switch
statement is a common example of such a construct. It provides a way to efficiently manage
decisions based on the value of a single variable or expression, avoiding the need for multiple
if-else statements.
'switch' case:
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

using a switch statement.

The switch statement has the following syntax and execution flow diagram.

Example Program | Display pressed digit in words.


#include<stdio.h>
#include<conio.h>

void main(){
int n ;
clrscr() ;

printf("Enter any digit: ") ;

INTRODUCTION TO PROGRAMMING QUESTION BANK


scanf("%d", &n) ;

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:

1. 5. Write a short notes on Break, Continue, Goto Statements?


In c, there are control statements that do not need any condition to control the program execution flow.

These control statements are called as unconditional control statements. C programming language

INTRODUCTION TO PROGRAMMING QUESTION BANK


provides the following unconditional control statements...

 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...

1. break statement is used to terminate the switch case statement


2. break statement is also used to terminate looping statements like while,
do-while and for.

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.

Example Program to perform all arithmetic operations using


switch statement.
#include<stdio.h>
#include<conio.h>

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;

INTRODUCTION TO PROGRAMMING QUESTION BANK


case '-': result = number1 - number2 ;
printf("Subtraction = %d", result) ;
break;
case '*': result = number1 * number2 ;
printf("Multiplication = %d", result) ;
break;
case '/': result = number1 / number2 ;
printf("Division = %d", result) ;
break;
case '%': result = number1 % number2 ;
printf("Remainder = %d", result) ;
break;
default: printf("\nWrong selection!!!") ;
}
getch() ;
}

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.

For example, consider the following example program...

INTRODUCTION TO PROGRAMMING QUESTION BANK


Example Program for break statement.
#include<stdio.h>
#include<conio.h>

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Example Program Program to illustrate continue statement.
#include<stdio.h>
#include<conio.h>

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:

INTRODUCTION TO PROGRAMMING QUESTION BANK


goto statement
The goto statement is used to jump from one line to another line in the program. Using goto statement we
can jump from top to bottom or bottom to top. To jump from one line to another line, the goto statement
requires a label. Label is a name given to the instruction or line in the program. When we use
a goto statement in the program, the execution control directly jumps to the line with the specified label.

Example Program for goto statement.


#include<stdio.h>
#include<conio.h>

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:

12. Write a C program on calculator using switch case?

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


C Program: Calculator Using Switch Case
#include <stdio.h>

int main() {
char operator;
double num1, num2, result;

// Prompt the user to select an operation


printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);

// Input two operands


printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);

// Perform operation based on user input


switch (operator) {
case '+':
result = num1 + num2;
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result);
} else {
printf("Error! Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid operator! Please use +, -, *, or /.\n");
}

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


Copy code
Enter an operator (+, -, *, /): ^
Enter two numbers: 4 2
Invalid operator! Please use +, -, *, or /.
4o

UNIT-III(ARRAYS AND STRINGS)

2 MARKS

8. Define Array ? What Is An Index Of An Array?


ANS
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:

datatype arrayName [ size ] ;

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.

In the example below the subscripts run from 0 through 5,

the size of the array=upperbound - lower bound+1

INTRODUCTION TO PROGRAMMING QUESTION BANK


2 What Is Two Dimensional Array ?

The two-dimensional array can be defined as an array of arrays. The 2D array is


organized asmatrices which can be represented as the collection of rows and columns.
However, 2D arraysare created to implement a relational database lookalike data
structure. It provides ease of holding the bulk of data at once which can be passed to
any number of functions wherever required.
3 What Is String ?
String: A String is a sequence of characters terminated with a
null character ‘\0’.String is enclosed in double quotation
marks(“ “).
The C String is stored as an array of characters. The difference between a
character array and a Cstring is that the string in C is terminated with a
unique character ‘\0.
For example, char c[ ] = "c string";
char c[5]= ”123”;
When the compiler encounters a sequence of characters enclosed in the double
quotation
marks, it appends a null character \0 at the end by default.

Memory Diagram

4 Write Syntax For The Following


A.Gets() B. Getch() C. Putchar() D.Puts()
A gets( ) function is used to read a string of characters including white spaces.
 Note that white spaces in a string cannot be read using scanf( ) with %s format
specifier.
 Syntax: gets (S); where ‘S’ is a char string variable.
B getch():It will Accepts a Keystroke and never displays it.(So that it can be used in
password).
Getch() returns back on reading any character.

C  putchar( ) function is used to display one character at a time on the monitor.

 Syntax: putchar (ch);

D  puts() is a function used to display strings on screen.

 Syntax: puts (S); where ‘S’ is a char string variable.

5 What Is The Need Of Arrays In C?


Arrays are used to store multiple values in a single variable rather than declaring
separate variables for each value.
6 Discuss Any Two String Handling Functions?
1 strlen(string_name)
returns the length of string name.

INTRODUCTION TO PROGRAMMING QUESTION BANK


2 strcpy(destination, source)
copies the contents of source string to destination string.

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:

datatype arrayName [ size ] ;

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.

1. One Dimensional Array:


A list of items can be given one variable name using only one subscript
and sucha variable is called a single subscripted variable of a One Dimensional
Array.

a) Declaration of One Dimensional Array:


Like any other variable, arrays must be declared before they are used
so that thecompiler can allocate space for them in memory.
when we want to create an array we must know the data type of values to be stored in
that array andalso the number of values to be stored in that array.

syntax to create an array...

INTRODUCTION TO PROGRAMMING QUESTION BANK


Ex: int a[5]d; atatype arrayName [ size ] ;
It represented in memory location as:
4000 4004 4008 4012 4016

a[0] a[1] a[2] a[3] a[4]

b) Initialization of One Dimensional Array:


Initialization in C is the process to assign some initial value to the variable. When
the array isdeclared or allocated memory, the elements of the array contain some
garbage value. So, we need to initialize the array to some meaningful value.
There are several ways in which we can initialize an array in C.
1. Array Initialization with Declaration(compile time):
In compile time initialisation, We can initialize the elements of arrays in the same
way as theordinary variables when they are declared.
In this method, we initialize the array along with its declaration.
We use an initializer list to initialize multiple elements of the array. An initializer list is
the listof values enclosed within braces { } separated by a comma.

Syntax for creating an array with size and initial values

datatype arrayName [ size ] = {value1,value2,... valuen} ;

 Example:
int a[5] = { 20, 40, 30, 60, 70 }
It represented in memory location as:
v
20 10 30 50 40

a[0] a[1] a[2] a[3] a[4]


Array Initialization with Declaration without Size:
If we initialize an array using an initializer list, we can skip declaring the size of

INTRODUCTION TO PROGRAMMING QUESTION BANK


the arrayas the compiler can automatically deduce the size of the array in these
cases. The size of the array in these cases is equal to the number of elements
present in the initializer list as the compiler can automatically deduce the size of the
array.
datatype arrayname[ ] = {1,2,3,4,5};

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]);
}

2. Define String ? Discuss The Various String Handling Functions In C ?


String: A String is a sequence of characters terminated with a
null character ‘\0’.String is enclosed in double quotation
marks(“ “).
The C String is stored as an array of characters. The difference between a
character array and a Cstring is that the string in C is terminated with a
unique character ‘\0.
For example, char c[ ] = "c string";
char c[5]= ”123”;
When the compiler encounters a sequence of characters enclosed in the double
quotation
marks, it appends a null character \0 at the end by default.

Memory Diagram

String Handling Functions in C/Library functions:

C Programming language provides a set of pre-definied functions called


String HandlingFunctions to work with string values. All the string
handling functions are defined in a header file called string.h.
There are many important string functions defined in "string.h" library.
1. String Length: strlen( ) function:
The strlen( ) function returns the length of the given string. It doesn't count null
character '\0'.
Syntax: strlen(StringName);
Example:

INTRODUCTION TO PROGRAMMING QUESTION BANK


#include<stdio.h>
#include<string.h>
Int main()

{
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

2. Copy String: strcpy( ):


It is for copying source string into
destination string.The length of the
destination string >= source string.
Syntax :
strcpy (Destination string, Source String);
The strcpy(destination, source) function copies the source string in destination string.
strncpy (Destination string, Source String, n);
It copy’s ‘n’ characters of source string into
destination string.

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

3 String Concatenation: strcat()


This is used for combining or concatenating n characters of one
string into another.The length of the destination string must be
greater than the source string.
The resultant concatenated string will be in the destination string
Syntax:. strcat (Destination String, Source string, n);

INTRODUCTION TO PROGRAMMING QUESTION BANK


The strcat(first_string, second_string) function concatenates two strings and result is
returnedto first_string
Example:
#include<stdio.h>
#include<string.h>
Int main()
{
char s1[20]={'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '\0'};
char ch2[10] ]={'c', '\0'};
strcat(ch,ch2);
printf("Concatenated string is: %s",ch);
return 0;
}
Output:
Concatenated string is: helloc

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


Example:
#include<stdio.h>
#include<string.h>
Int main()
{
Char str1[20],str2[20];
printf("Enter 1st string:”);
gets(str1);
printf("Enter 2nd string:”);
gets(str2);
if(strcmp(str1,str2==0)
printf("Stringsareequ
al")
else
printf("Strings are not equal");
return 0;

INTRODUCTION TO PROGRAMMING QUESTION BANK


}
Output:
Enter 1st string : hello
Enter 2nd string :hello
Strings are equal
Example:2
#include<stdio.h>
#include<string.h>
Int main()
{
Char a[50],b[50];
int d;
printf("Enter 2 strings;”);
scanf(“%s,%s”,a,b);
d=strcmp(a,b);
if(d==0)
printf("%s is (alphabetically) equal to %s", a,b);
}
else if (d>0)
{
printf("%s is (alphabetically) greater than %s",a,b);
}
else if (d<0)
{
printf("%s is (alphabetically) less than %s", a,b);
}
return 0;
}

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.

Let's see a simple example of strrev() function.


Example:
#include<stdio.h>
#include<string.h>
Int main()
{
Char str[20];
printf("Enter string: ");
gets(str);
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;

INTRODUCTION TO PROGRAMMING QUESTION BANK


}
Output:
Enter string: helloworld
String is: helloworld
Reverse String is: dlrowolleh

6. Lowercase String: strlwr()

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";

// converting the given string into lowercase.


printf("%s\n",strlwr (str));

return 0;
}
Output:
geeksforgeeks is the best

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

int main()
{
char str[] = "CompuTer ScienCe PoRTAl fOr geeKS";

printf("Given string is: %s\n",str);

printf("\nString after converting to the "


"lowercase is: %s",strlwr(str));

return 0;
}
Output:
Given string is: CompuTer ScienCe PoRTAl fOr geeKS

String after converting to the lowercase is: computer science portal for geeks

INTRODUCTION TO PROGRAMMING QUESTION BANK


7. Uppercase String: strupr()

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";

printf("Given string is: %s\n", str);

printf("\nstring after converting to the uppercase is: %s", strupr(str));


return 0;
}
Given string is: CompuTer ScienCe PoRTAl fOr geeKS
string after converting to the uppercase is: COMPUTER SCIENCE PORTAL FOR GEEKS
3. Write A Program To Find Given String Is Palindrome Or Not.?
#include <stdio.h>
#include <string.h>

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]) {

INTRODUCTION TO PROGRAMMING QUESTION BANK


flag = 1;
break;
}
}
if (flag) {
printf("%s is not a palindrome\n", string1);
} else {
printf("%s is a palindrome\n", string1);
}

return 0;
}
Output:
Enter a string :WOW
Wow is a Palimdrome

4. Write A Program To Multiply Two Matrices Of Order ‘Mxn’ And ‘Nxl’ ?


#include <stdio.h>
#define N 3 // Size of square matrices
int main()
{
int matrix1[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int matrix2[N][N] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[N][N];
int i, j, k;

// Multiply the two matrices


for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
int sum = 0;
for (k = 0; k < N; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
result[i][j] = sum;
}
}

// Print the resulting matrix


printf("Result Matrix:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}
Output:
Result Matrix:
30 24 18
84 69 54

INTRODUCTION TO PROGRAMMING QUESTION BANK


138 4 90

5. Explain The Memory Model Of Two Dimensional Array?


The data items in a multidimensional array are stored in the form of rows and columns. Also,
the memory allocated for the multidimensional array is contiguous. So the elements in
multidimensional arrays can be stored in linear storage using two methods i.e., row-major
order or column-major order.
 Row major order: In row-major order, we store the elements according to rows i.e.,
first, we store the elements in the first row followed by the second row, and so on. Hence
elements of the first row are stored linearly in the memory followed by the second row
and so on. In memory, we will not find any separation between the rows.
 Column major order: Column major order is opposite to row-major in storing the
data items i.e., Here, we first store the elements in the first column followed by the
second column, and so on. So in this case, elements of the first column are stored
linearly in the memory followed by the second column, and so on.
C compilers use Row major order method to store the elements in the memory. Basically, C
compilers stores multidimensional arrays as single dimension arrays whose elements are
single-dimensional arrays or a multidimensional array whose dimension is 1 less than the
former. And the storage of these array objects is row-wise.
Size and the memory allocation of the multidimensional array:
The size of every dimension in the multidimensional array needs to be declared initially.
And then the total size of the multidimensional array is calculated by multiplying the size of
each dimension. And the memory allocated to the multidimensional array is equal to
multiple of size of the multidimensional array and the size of a single element.
data_type array_name [ x1 ] [ x2 ] [ x3 ] ….. [ xn ] ;
size of the multidimensional array :- x1*x2*x3*…..*xn
where x1, x2, x3, …, xn are the sizes of each dimensions.
memory allocated = size of the multidimensional array * size of single data_type
For example:-
int arr [ 3 ][ 4 ] [ 2 ];
size of this multidimensional (3 D) array is 3*4*2 = 24
memory allocated = 24 * 4 bytes = 96 bytes
For Example:
As given below: int arr[3][3] = { {24, 15, 34}, {26, 134, 194}, {67, 23, 345} } is stored in
memory as:-

INTRODUCTION TO PROGRAMMING QUESTION BANK


Allocation of data

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:

// C Program to show allocation of data items

// in multidimensional array

#include <stdio.h>

#include <stdlib.h>

int main()

// Declaring the dimension of

// 2-Dimension array

int row = 3;

int col = 3;

// Creating an array arr with size row*col

INTRODUCTION TO PROGRAMMING QUESTION BANK


int* arr = (int*)malloc(row * col * sizeof(int));

int k = 1;

// Inserting values in the array

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

for (int j = 0; j < col; j++) {

// The memory address of arr[i][j]

// is equal to (arr + i*col + j)

*(arr + i * col + j) = k;

k++;

// Printing the multidimensional array

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

for (int j = 0; j < col; j++) {

printf("%d ", *(arr + i * col + j));

printf("\n");

return 0;

Output
123
456

INTRODUCTION TO PROGRAMMING QUESTION BANK


789

6. Write A Program To Perform Addition Of Two Matrices ?


#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

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


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}

// adding two matrices


for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}

// printing the result


printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}

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

Enter elements of 1st matrix:

INTRODUCTION TO PROGRAMMING QUESTION BANK


Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter elements of 2nd matrix:
Enter element b11: -4
Enter element b12: 5
Enter element b13: 3
Enter element b21: 5
Enter element b22: 6
Enter element b23: 3

Sum of two matrices:


-2 8 7

10 8 6

6.Write A Program To Perform Linear Search?

// Linear Search in C

#include <stdio.h>

int search(int array[], int n, int x) {

// Going through array sequencially


for (int i = 0; i < n; i++)
if (array[i] == x)
return i;
return -1;
}

int main() {
int array[] = {2, 4, 0, 1, 9};
int x = 1;
int n = sizeof(array) / sizeof(array[0]);

int result = search(array, n, x);

(result == -1) ? printf("Element not found") : printf("Element found at index: %d", result);
}

Output:
Element found at index: 3

INTRODUCTION TO PROGRAMMING QUESTION BANK


UNIT-IV(FUNCTIONS AND POINTERS)

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.

2. What is the difference between function declaration and definition.


Function Declaration Function Definition

Provides the actual implementation


Declares the existence of a function,
of the function, defining what the
providing its name and parameters
function does

Function Declaration is used to let the Function Definition is used to


compiler know about the existence of provide the actual implementation
such a function so that we don't of the code which will execute
encounter any Reference Errors. every time the function is called.

Function Declaration does not include Function Definition includes the


the body of the function. body of the function.

Syntax: return_type Syntax: return_type

INTRODUCTION TO PROGRAMMING QUESTION BANK


Function Declaration Function Definition

function_name(paramA, paramB); function_name(paramA, paramB)


{ Implementation details }

3. What is Function call?


Function can be called from anywhere in the program. The parameter list must
not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.
4. Define Return type, argument in c?
In computer programming, the return type (or result type) defines and constrains
the data type of the value returned from a subroutine or method. In many
programming languages (especially statically-typed programming languages
such as C, C++, Java) the return type must be explicitly specified when declaring
a function.
The values that are declared within a function when the function is called are
known as an argument. These values are considered as the root of the function
that needs the arguments while execution, and it is also known as Actual
arguments or Actual Parameters.
5. What is scope and lifetime of variables?
Scope of Variables:
Scope of variables in C language refers to the region or part of the code where a
variable can be accessed or used.
Lifetime of Variables in C
Variable lifetime in C refers to the period during which a variable exists in
memory and retains its value.
6. DefineStructures?
Structures are defined first and then it is used for declaring structure variables.
Syntax:
struct tagname
{
Data_type member1;
Data_type member2;
…………….
……………
};

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


Syntax:
union tagname
{
Data_type member1;
Data_type member2;
…………….
……………
} obj;

8. Differentiate Structures And Unions?


S.no C Structure C Union
1 Structure allocates Union allocates one
storage space for all its common storage space
members separately. for all its members.
Union finds that which
of its member needs
high storage space over
other members and
allocates that much
space
2 Structure occupies Union occupies lower
higher memory space. memory space over
structure.
3 We can access all We can access only one
members of structure at member of union at a
a time. time.

5marks
1.How to declare and initialize structures? Explain with examples?

INTRODUCTION TO PROGRAMMING QUESTION BANK


Structure Initialization
Like variables, structures can also be initialized at the compile time.
Example:
main()
{
Struct
{
int rollno;
int attendance;
}s={786,98};
}
Declaring Structure
There are two ways for declaring a structure variable.
1. Declaration of structure variable at the time of defining the structure (i.e
structure definition and structure variable declaration are combined)
struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
} b1,b2,b3;

2) Declaration of structure variable after defining the structure


struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};
struct book b1, b2, b3;
2. Is nesting of structures valid? Justify your answer with an example?
Structures can also be nested. i.e A structure can be defined inside another
structure.
Example
struct employee
{
int empid;

INTRODUCTION TO PROGRAMMING QUESTION BANK


char empname[20];
struct SAL
{
int basicpay;
int da;
int hra;
int cca;
} salary;
} e1;
3. Difference Between Call By Value And Call By Reference?

No. Call by value Call by reference


1 A copy of the value is An address of value is
passed into the function. passed into the function.
2 Changes made inside the Changes made inside the
function is limited to the function validate outside
function only. of the function also.
3 The values of the actual The values of the actual
parameters do not change parameters do change by
by changing the formal changing the formal
parameters. parameters.
4 Actual and formal Actual and formal
arguments are created at arguments are created at
the different memory the same memory
location location

4. Explain Recursion With The Help Of A Program?

Recursion is the process in which a function repeatedly calls itself to perform


calculations.
Syntax: recursion()
{
recursion();
}
int main()
{
……….
recursion();
…………
return 0;
}
Example:
#include <stdio.h>
int fib(int); // function declaration

INTRODUCTION TO PROGRAMMING QUESTION BANK


main()
{
int n,i;
printf(“\nEnter n “);
scanf(“%d”,&n);
for (i=0;i<n;i++)
printf(“%d\t”,fib(i));
}
int fib(int n)
{
if (n==0 || n==1)
return n;
return fib(n-1)+fib(n-2);
}
5. Explain Local Static Variables And What Is Their Use?
Types of Variable Lifetime in C Language
Variables in C have different lifetimes depending on how they are declared. Below are the
main types of variable
lifetime in C:
1. Automatic (Local) Variables

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.

INTRODUCTION TO PROGRAMMING QUESTION BANK


2. Static Variables
Static variables are variables that retain their value between multiple function calls. If a static
variable is declared
inside a function, it is initialized only once, and its value persists across function calls.
Static variables can be declared at the global level as well, in which case they are only visible
within the file they
are declared in.
Characteristics:
 Created when the program starts.
 Retain their value across multiple function calls.
 Destroyed when the program ends.
 Stored in the data segment of memory.

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.

6. What Are The Different Storage Class Specifiers In C?


Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory
location, and initial value of a variable. There are four types of storage classes in
C
o Automatic
o External
o Static
o Register
Automatic:
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they
are defined.

The scope of the automatic variables is limited to the block in which they are

INTRODUCTION TO PROGRAMMING QUESTION BANK


defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the
block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.

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

INTRODUCTION TO PROGRAMMING QUESTION BANK


program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
o An external variable can be declared many times but can be initialized at only
once.
o If a variable is declared as external then the compiler searches for that variable
to be initialized somewhere in the program which may be extern or static. If it is
not, then the compiler will show an error.

7. Explain Functions With Arrays As Arguments?


Passing Array to Functions/Arrays as parameters
□ Array can pass through calling function, where as we don’t return an array
from function.
□ Rather we return a pointer holding the base address of the array to be returned.
But, we must make sure that the array exits after the function ends.
1. Formal parameter as a pointer as follows:

void myfunction(int *p)


{
……
…..
}
2. Formal parameter as a sized array as follows:

myfunctio(int p[10]) myfunctio(int p[ ])


{{
……. ……..
……. …….
}}

INTRODUCTION TO PROGRAMMING QUESTION BANK


Passing data values
#include<stdio.h>
fun(int arr[]);
main()
{
int arr[5]={1,2,3,4,5};
fun(arr[3]);
}
fun(int num)
{
printf(“%d”,num);
}
Passing address
#include<stdio.h>
fun(int *n);
main()
{
int arr[5]={1,2,3,4,5};
fun(&arr[3]);
}
fun(int *n)
{
printf(“%d”,*n);
}
Passing the Entire array
#include<stdio.h>

INTRODUCTION TO PROGRAMMING QUESTION BANK


fun(int arr[5]);
main()
{
int arr[5]={1,2,3,4,5};
fun(arr);
}
fun(int arr[5])
{
int i;
for(i=0;i<5;i++)
printf(“%d”,arr[i]);
}

INTRODUCTION TO PROGRAMMING QUESTION BANK


UNIT-5 POINTERS AND FILES
QUESTIONS WITH ANSWERS

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

2. How You Declare and Initialize a Pointer?

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:

int *p; // Pointer to an integer

Initialization:

int x = 10;
int *p = &x; // p points to the address of x

3. What Is Pointer Arithmetic?

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.

p++; // Move to the next integer in memory

 Decrementing a pointer moves it to the previous memory location.

p--; // Move to the previous integer in memory

4. Do We Perform Subtraction or Multiplication of Two Pointers? Discuss the


Reason.
In C/C++, pointer subtraction is allowed, but pointer multiplication is not.

 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

 Pointer multiplication is not allowed. It doesn’t make sense to multiply pointers


because memory addresses are not linear in terms of multiplication.

5. What Is User Defined Data Types?

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: A collection of variables of different data types.

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;
};

 Enum: A set of named integer constants.

enum Days {Sunday, Monday, Tuesday, Wednesday};

 Typedef: Used to create an alias for an existing data type.

typedef unsigned int uint;

6. Define Dereferencing Operator?

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?

Pointers are needed for various reasons:

 Efficient memory management: Pointers allow dynamic memory allocation,


enabling programs to use memory more efficiently.
 Function arguments: Pointers can be used to pass large structures or arrays by
reference rather than by value, saving memory and processing time.
 Dynamic memory allocation: Using malloc() and free() functions, you can
allocate and deallocate memory at runtime.
 Data structures: Many data structures like linked lists, trees, and graphs are
implemented using pointers.

8. Define fprintf(), fscanf().

 fprintf(): A function used to write formatted output to a file. It works similarly to


printf(), but the output is directed to a file stream rather than the console.

Example:

FILE *fp = fopen("file.txt", "w");


fprintf(fp, "Hello, World! %d", 42);
fclose(fp);

 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:

FILE *fp = fopen("file.txt", "r");


int x;
fscanf(fp, "%d", &x);
fclose(fp);

9. What Is fopen(), fclose()?

 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:

FILE *fp = fopen("file.txt", "r"); // Open file for reading

 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:

fclose(fp); // Close the file after use


1. Demonstrating the Use of fread() and fscanf() for Reading
Sequentially from a Disk
Both fread() and fscanf() are used to read data from a file, but they differ in how they
handle the data and the format in which the data is read.

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);

 ptr: Pointer to a buffer where the read data will be stored.


 size: Size of each element to be read.
 count: Number of elements to be read.
 stream: The file pointer.

Example of fread() for Reading Binary Data:

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;

// Open the file in binary read mode


file = fopen("data.bin", "rb");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}

// Read integers from the file using fread()


while ((readSize = fread(&num, sizeof(int), 1, file)) == 1) {
printf("Read integer: %d\n", num);
}

// Close the file


fclose(file);

return 0;
}
In this example:

 We open the file data.bin in read-binary mode ("rb").


 We use fread() to read one int at a time from the file and print it.
 We keep reading until fread() returns less than 1, meaning there is no more data to read.
 The sizeof(int) argument ensures that we are reading an entire integer at a time.

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, ...);

 stream: The file pointer.


 format: A format string similar to scanf() which tells fscanf() how to interpret the
data.
 ...: The variables where the read data will be stored.

Example of fscanf() for Reading Text Data:

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;

// Open the file in read mode


file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}

// Read integers from the file using fscanf()


while (fscanf(file, "%d", &num) != EOF) {
printf("Read integer: %d\n", num);
}

// Close the file


fclose(file);

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.

Key Differences Between fread() and fscanf():

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).

2. Write A Program To Open A File And Read The File And


Print The File Contents .

C Program to Open a File, Read It, and Print Its Contents


#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *file; // Declare file pointer
char ch; // Variable to store each character read from the
file

// Open the file in read mode ("r")


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

// Check if the file opened successfully


if (file == NULL) {
printf("Error: Could not open the file.\n");
return 1; // Exit with error code 1
}
// Read and print each character from the file
while ((ch = fgetc(file)) != EOF) {
putchar(ch); // Print the character to the console
}

// Close the file after reading


fclose(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.

Sample File Contents:

Assume example.txt contains the following:

Hello, this is a test file.


It contains some text data.

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:

File Opening Functions

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:

FILE *file = fopen("example.txt", "r"); // Open file for reading

Reading Data from a File

Once a file is opened, data can be read using different functions depending on the type and
format of data.

fgetc()

int fgetc(FILE *stream);

 Purpose: Reads a single character from a file.


 Returns: The character read as an unsigned char cast to an int, or EOF if the end of the file is
reached or an error occurs.
 Example:

char ch = fgetc(file); // Read one character from the file


fgets()

char *fgets(char *str, int num, FILE *stream);

 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()

size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

 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 fscanf(FILE *stream, const char *format, ...);

 Purpose: Reads formatted input from a file (similar to scanf()).


 Parameters:
o format: A format string that specifies how the data should be interpreted (e.g., %d
for integers, %s for strings).
o ...: Variables where the read data will be stored.
 Returns: The number of items successfully read.
 Example:

int num;
fscanf(file, "%d", &num); // Read an integer from the file

Writing Data to a 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);

 Purpose: Writes a single character to a file.


 Returns: The character written as an unsigned char cast to an int, or EOF if an error occurs.
 Example:

fputc('A', file); // Write the character 'A' to the file

fputs()

int fputs(const char *str, FILE *stream);

 Purpose: Writes a string to a file (without the null-terminator).


 Returns: A non-negative value on success, or EOF on error.
 Example:

fputs("Hello, World!", file); // Write a string to the file

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:

int arr[5] = {1, 2, 3, 4, 5};


fwrite(arr, sizeof(int), 5, file); // Write 5 integers to the file

fprintf()
int fprintf(FILE *stream, const char *format, ...);

 Purpose: Writes formatted output to a file (similar to printf()).


 Parameters:
o format: A format string that specifies how the data should be formatted (e.g., %d
for integers, %f for floats).
o ...: Values to be formatted and written to the file.
 Returns: The number of characters written, or a negative value if an error occurs.
 Example:

fprintf(file, "The value of pi is approximately: %.2f\n", 3.14159);


// Write formatted text to the file

File Closing Function

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:

fclose(file); // Close the file

Example Program: Reading and Writing to a File

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;

// Open the input file in read mode


inputFile = fopen("input.txt", "r");
if (inputFile == NULL) {
printf("Error opening input file.\n");
return 1;
}

// Open the output file in write mode


outputFile = fopen("output.txt", "w");
if (outputFile == NULL) {
printf("Error opening output file.\n");
fclose(inputFile); // Close the input file if output file fails to
open
return 1;
}

// Read from input file and write to output file


while ((ch = fgetc(inputFile)) != EOF) {
fputc(ch, outputFile); // Write each character to the output file
}

// Close both files


fclose(inputFile);
fclose(outputFile);

printf("File contents copied successfully.\n");


return 0;
}

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.

C Program to Print File Contents in Reverse Order


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

int main() {
FILE *file;
char *buffer;
long fileSize;
size_t bytesRead;

// Open the file in read mode


file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}

// Seek to the end of the file to get the size


fseek(file, 0, SEEK_END);
fileSize = ftell(file); // Get the current position (file size)
rewind(file); // Go back to the start of the file

// Allocate memory to store the entire file


buffer = (char *)malloc(fileSize * sizeof(char));
if (buffer == NULL) {
printf("Memory allocation failed.\n");
fclose(file);
return 1;
}

// Read the entire file into the buffer


bytesRead = fread(buffer, sizeof(char), fileSize, file);
if (bytesRead != fileSize) {
printf("Error reading the file.\n");
free(buffer);
fclose(file);
return 1;
}

// Print the contents in reverse order


for (long i = fileSize - 1; i >= 0; i--) {
putchar(buffer[i]);
}

// Free the allocated memory and close the file


free(buffer);
fclose(file);

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:

Assuming example.txt contains the following:

Hello, this is a test file.


This file will be printed in reverse.

Output:
.esrever ni detnirp eb lliw elif sihT
.elif tset a si siht ,olleH

5. Define a pointer. How to initialize and declare pointer


variables? Explain the same with examples.

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.

Syntax of a Pointer Declaration

To declare a pointer, the syntax is:

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.

How to Declare and Initialize a Pointer

1. Declaring a Pointer:

When declaring a pointer, you specify the data type it will point to. For example:

int *ptr; // Declares a pointer to an integer


float *fptr; // Declares a pointer to a float
char *cptr; // Declares a pointer to a char

2. Initializing a Pointer:

To initialize a pointer, you assign it the memory address of a variable of the


corresponding type. You can get the memory address of a variable using the address-
of operator (&).

int num = 10;


int *ptr = &num; // ptr is initialized to point to the memory
address of num

Here, &num gives the address of the variable num, and this address is stored in the
pointer ptr.

Examples of Pointer Declarations and Initializations

1. Integer Pointer
#include <stdio.h>

int main() {
int num = 10; // Integer variable
int *ptr = &num; // Pointer to int, initialized to the address of num

printf("Value of num: %d\n", num); // Output: 10


printf("Address of num: %p\n", &num); // Prints the address of num
printf("Value of ptr (address of num): %p\n", ptr); // Prints the
address stored in ptr
printf("Value pointed to by ptr: %d\n", *ptr); // Dereferencing ptr to
get the value of num

return 0;
}

Explanation:

 num is an integer variable, and ptr is a pointer to an integer.


 The pointer ptr is initialized with the address of num using &num.
 *ptr dereferences the pointer and accesses the value stored at the address it points to
(which is the value of num).

2. Float Pointer
#include <stdio.h>

int main() {
float pi = 3.14;
float *fptr = &pi; // Pointer to float, initialized to the address of
pi

printf("Value of pi: %.2f\n", pi); // Output: 3.14


printf("Address of pi: %p\n", &pi); // Prints the address of pi
printf("Value of fptr (address of pi): %p\n", fptr); // Prints the
address stored in fptr
printf("Value pointed to by fptr: %.2f\n", *fptr); // Dereferencing
fptr to get the value of pi

return 0;
}

Explanation:

 pi is a float, and fptr is a pointer to a float.


 fptr is initialized with the address of pi.
 Using *fptr, we can dereference the pointer to access the value stored at the address fptr
points to (which is pi).

3. Character Pointer
#include <stdio.h>

int main() {
char letter = 'A';
char *cptr = &letter; // Pointer to char, initialized to the address
of letter

printf("Value of letter: %c\n", letter); // Output: A


printf("Address of letter: %p\n", &letter); // Prints the address of
letter
printf("Value of cptr (address of letter): %p\n", cptr); // Prints the
address stored in cptr
printf("Value pointed to by cptr: %c\n", *cptr); // Dereferencing cptr
to get the value of letter

return 0;
}

Explanation:

 letter is a char, and cptr is a pointer to a char.


 cptr is initialized with the address of letter.
 Using *cptr, we can dereference the pointer and print the character stored at the address
cptr points to.

Important Points about Pointers

1. Address-of Operator (&):


o The & operator is used to obtain the address of a variable. It is essential for
initializing pointers.

Example:

int var = 5;
int *ptr = &var; // ptr stores the address of var

2. Dereferencing Operator (*):


o The * operator is used to access the value stored at the memory address that a
pointer is pointing to. This is called dereferencing the pointer.

Example:

int value = 10;


int *ptr = &value; // ptr points to value
printf("%d\n", *ptr); // Dereferencing ptr prints 10

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:

int *ptr = NULL; // A pointer initialized to NULL

4. Pointer to Pointer:
o You can have a pointer that points to another pointer, known as a pointer to
pointer.

Example:

int var = 10;


int *ptr = &var; // Pointer to an integer
int **ptr2 = &ptr; // Pointer to pointer (points to ptr)

printf("%d\n", **ptr2); // Dereferencing twice to get the value of


var (10)

6. Discuss in detail about pointer arithmetic. Support the answer


with appropriate examples.
Pointer Arithmetic in C

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.

Key Concepts of Pointer Arithmetic

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.

Here are the main operations supported by pointer arithmetic:

1. Pointer Increment (++)


2. Pointer Decrement (--)
3. Pointer Addition (+)
4. Pointer Subtraction (-)
5. Pointer Comparison (==, !=, <, >, etc.)

Pointer Arithmetic Rules

 Increment/Decrement: When you increment (++) or decrement (--) a pointer, it


moves by the size of the type it is pointing to. For example, if a pointer points to an
integer (typically 4 bytes), incrementing it moves the pointer forward by 4 bytes.
 Addition/Subtraction: Adding or subtracting an integer to/from a pointer moves the
pointer by that integer multiplied by the size of the data type. For example, if you add
3 to an integer pointer, the pointer will move ahead by 3 * sizeof(int) bytes.

Pointer Arithmetic Examples

1. Pointer Increment (++)

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

printf("Current value: %d\n", *ptr); // Prints 10 (the first element)

ptr++; // Increment the pointer


printf("After increment, value: %d\n", *ptr); // Prints 20 (the second
element)

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.

2. Pointer Decrement (--)

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

printf("Current value: %d\n", *ptr); // Prints 40 (the last element)

ptr--; // Decrement the pointer


printf("After decrement, value: %d\n", *ptr); // Prints 30 (the third
element)

return 0;
}

 Explanation: After ptr--, the pointer moves backward from arr[3] to arr[2].

3. Pointer Addition (+)

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

printf("Current value: %d\n", *ptr); // Prints 10 (the first element)

ptr = ptr + 2; // Move the pointer 2 positions forward


printf("After addition, value: %d\n", *ptr); // Prints 30 (the third
element)

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)).

4. Pointer Subtraction (-)

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

printf("Current value: %d\n", *ptr); // Prints 40 (the last element)

ptr = ptr - 2; // Move the pointer 2 positions backward


printf("After subtraction, value: %d\n", *ptr); // Prints 20 (the
second element)

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];

if (ptr2 > ptr1) {


printf("ptr2 points to a memory address after ptr1.\n");
}

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.

Pointer Arithmetic with Arrays

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

// Using pointer arithmetic to access elements


printf("First element: %d\n", *ptr); // Prints 10
printf("Second element: %d\n", *(ptr + 1)); // Prints 20
printf("Third element: %d\n", *(ptr + 2)); // Prints 30
return 0;
}

 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.

Important Considerations with Pointer Arithmetic

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).

Example: Pointer Arithmetic in an Array


#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Pointer to the first element of arr

// Printing elements using pointer arithmetic


for (int i = 0; i < 4; i++) {
printf("Element %d: %d\n", i, *(ptr + i)); // Accessing elements
using pointer arithmetic
}

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.

7. Elaborate the importance of dynamic memory allocation with


example.
Importance of Dynamic Memory Allocation in C

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.

Key Benefits of Dynamic 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.

Functions for Dynamic Memory Allocation in C

In C, dynamic memory is allocated using the following functions from the standard library
(<stdlib.h>):

1. malloc(): Allocates a specified number of bytes of memory and returns a pointer to


the first byte.
o Syntax: void* malloc(size_t size);
o It returns a pointer to the allocated memory or NULL if the allocation fails.
2. calloc(): Allocates memory for an array of elements, initializing each element to zero.
o Syntax: void* calloc(size_t num_elements, size_t element_size);
o It returns a pointer to the allocated memory or NULL if the allocation fails.
3. realloc(): Resizes previously allocated memory.
o Syntax: void* realloc(void* ptr, size_t new_size);
o It changes the size of the memory block pointed to by ptr to new_size.
4. free(): Deallocates previously allocated memory, making it available for reuse.
o Syntax: void free(void* ptr);
Example: Dynamic Memory Allocation

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.

Example Program: Dynamic Memory Allocation for an Array


#include <stdio.h>
#include <stdlib.h>

int main() {
int *arr; // Pointer to int
int size, i;

// Ask the user for the number of elements they want


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

// Dynamically allocate memory for 'size' integers


arr = (int*)malloc(size * sizeof(int)); // malloc allocates memory

// Check if memory allocation was successful


if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Input values into the dynamically allocated array


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

// Output the values


printf("The entered integers are:\n");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Release the allocated memory


free(arr);

return 0;
}

Example with calloc() for Zero Initialization


#include <stdio.h>
#include <stdlib.h>

int main() {
int *arr;
int size, i;

// Ask for the number of elements


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

// Dynamically allocate memory for 'size' integers and initialize to 0


arr = (int*)calloc(size, sizeof(int)); // calloc initializes the
memory to 0

// Check if memory allocation was successful


if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Output the initialized array values (they will be zero)


printf("The initialized array values are:\n");
for (i = 0; i < size; i++) {
printf("%d ", arr[i]); // Should print 0 for all elements
}
printf("\n");

// Release the allocated memory


free(arr);

return 0;
}

Advantages of Dynamic Memory Allocation:

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.

Disadvantages of Dynamic Memory Allocation:

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?

Pointers and Arrays in C

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).

Pointers can be used to declare both single-dimensional and multi-dimensional arrays,


providing greater flexibility in managing arrays dynamically. In this answer, we will explore
how pointers can be used for both single and multi-dimensional arrays, along with examples.

Single-Dimensional Arrays Using Pointers

A single-dimensional array is a simple linear collection of elements, where each element is


indexed by a single integer.

1. Declaring a Single-Dimensional Array using a Pointer:

To declare and access a single-dimensional array using a pointer, we typically use the
following approach:

1. Array Declaration:

int arr[5]; // Declaring an array of 5 integers


int *ptr; // Declaring a pointer to an integer

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

3. Accessing Array Elements using Pointer Arithmetic:

You can access array elements using the pointer and pointer arithmetic, like this:

ptr[0] = 10; // Equivalent to arr[0] = 10


ptr[1] = 20; // Equivalent to arr[1] = 20

Alternatively, you can use pointer dereferencing:

*(ptr + 2) = 30; // Equivalent to arr[2] = 30


Example: Single-Dimensional Array with Pointer
#include <stdio.h>

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

// Input values using the pointer


for (int i = 0; i < 5; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", (ptr + i)); // Using pointer arithmetic to input
values
}

// Output values using the pointer


printf("The array elements are:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // Dereferencing pointer to print
values
}

return 0;
}

Explanation of the Example:

 arr[5]: Declares an array of 5 integers.


 int *ptr = arr;: The pointer ptr is initialized to point to the first element of the array
arr.
 scanf("%d", (ptr + i));: This accesses each element of the array using pointer
arithmetic and allows input to be stored at that location.
 printf("%d", *(ptr + i));: Dereferencing the pointer to print each array element.

Multi-Dimensional Arrays Using Pointers

A multi-dimensional array is an array of arrays. The most common type of multi-


dimensional array is a 2D array (array of arrays), but it can also be extended to 3D and
beyond. In C, pointers can be used to declare and access elements of multi-dimensional
arrays.

2D Array with Pointer

A 2D array can be thought of as an array of rows, where each row is a 1D array.

1. Declaring a 2D Array with Pointer:

int arr[3][4]; // A 2D array with 3 rows and 4 columns


int (*ptr)[4]; // Pointer to an array of 4 integers (each row has 4
elements)

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

3. Accessing Elements using Pointer Arithmetic:

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.

 *(ptr + i) accesses the i-th row.


 *(ptr + i) + j accesses the j-th element in the i-th row.

Example: 2D Array with Pointer


#include <stdio.h>

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)

// Input elements using pointer arithmetic


printf("Enter the elements for the 2D array:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &ptr[i][j]); // Using pointer arithmetic to input
values
}
}

// Output elements using pointer arithmetic


printf("The 2D array elements are:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", ptr[i][j]); // Using pointer arithmetic to
access elements
}
printf("\n");
}

return 0;
}

Explanation of the Example:

 arr[3][4]: Declares a 2D array with 3 rows and 4 columns.


 int (*ptr)[4] = arr;: ptr is a pointer to an array of 4 integers. It is initialized to point
to the first row of the 2D array arr.
 ptr[i][j]: This accesses the element in the i-th row and j-th column using pointer
arithmetic.
 We use two nested loops: one for rows and another for columns.

Using Pointer to Dynamically Allocate Multi-Dimensional Arrays

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)

// Dynamically allocate memory for rows


arr = (int **)malloc(rows * sizeof(int *));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Dynamically allocate memory for columns


for (int i = 0; i < rows; i++) {
arr[i] = (int *)malloc(cols * sizeof(int));
if (arr[i] == NULL) {
printf("Memory allocation failed for row %d!\n", i);
return 1;
}
}

// Input values into the dynamically allocated 2D array


printf("Enter elements for the 2D array:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &arr[i][j]);
}
}

// Output the elements of the dynamically allocated 2D array


printf("The 2D array elements are:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

// Free dynamically allocated memory


for (int i = 0; i < rows; i++) {
free(arr[i]); // Free each row
}
free(arr); // Free the array of pointers

return 0;
}

Explanation of Dynamic Memory Allocation Example:

 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.

9. What is pointer? Explain array of pointers with example.?

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:

int *ptr; // Declares a pointer to an integer


char *str; // Declares a pointer to a character

Here, ptr is a pointer that holds the address of an integer, and str is a pointer that holds the
address of a character.

How Pointers Work

 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 (*).

int num = 10;


int *ptr = &num; // ptr holds the address of num
printf("%d", *ptr); // Dereferencing ptr to print the value of num (10)

 Pointer Assignment: You can assign a pointer to the address of a variable using the address-
of operator (&).

int num = 10;


int *ptr = &num; // ptr now holds the address of num

What is an Array of Pointers?

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.

Array of Pointers to Integers:

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

// Assigning the address of num1, num2, and num3 to the pointers


arr[0] = &num1;
arr[1] = &num2;
arr[2] = &num3;

// Dereferencing the pointers to access values


printf("Value at arr[0]: %d\n", *arr[0]); // Output: 10
printf("Value at arr[1]: %d\n", *arr[1]); // Output: 20
printf("Value at arr[2]: %d\n", *arr[2]); // Output: 30

return 0;
}

Explanation of the Example:

1. We declare an array of three integer pointers: int *arr[3];.


2. Each element of the array is assigned the address of one of the integer variables (num1,
num2, num3).
3. We dereference each pointer (*arr[i]) to access the value stored at the corresponding
address.

Array of Pointers to Strings (Array of String Literals):

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"};

// Accessing and printing each string using array of pointers


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

return 0;
}

Explanation of the Example:


1. The array arr[] is an array of pointers to characters (strings). Each element of arr holds
the address of a string literal.
2. We use the pointer arr[i] to print each string in the array.
3. The %s format specifier in printf automatically dereferences the pointer to print the
string.

Key Points to Understand About Arrays of Pointers:

 Pointer Array vs Array of Pointers:


o Pointer Array: This is an array where each element is a pointer (e.g., int
*arr[3];), and it can point to data of a specific type.
o Array of Pointers: This is an array of multiple pointers, where each pointer could
point to different types of data. For example, an array of string literals or an array of
dynamically allocated memory blocks.
 Memory Consideration:
o Each pointer in the array holds a memory address, and thus, when you assign the
address of a variable or a string to each element of the pointer array, it effectively
“points” to that data.
 Use Case for Array of Pointers:
o Dynamic memory allocation: You can use an array of pointers to dynamically
allocate memory for each element in the array during runtime.
o String handling: Array of pointers is often used to handle arrays of strings (since
strings are arrays of characters).
o Linked Lists or Other Data Structures: Pointers in an array could be used for more
complex data structures, such as managing nodes in a linked list.

Example: Array of Pointers for Dynamic Memory Allocation

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

// Dynamically allocate memory for 3 integers


for (int i = 0; i < 3; i++) {
arr[i] = (int*)malloc(sizeof(int)); // Allocate memory for one
integer
if (arr[i] == NULL) {
printf("Memory allocation failed\n");
return 1;
}
}

// Assign values to the allocated memory


*arr[0] = 10;
*arr[1] = 20;
*arr[2] = 30;

// Print the values


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

// Free the allocated memory


for (int i = 0; i < 3; i++) {
free(arr[i]);
}

return 0;
}

Explanation:

1. We declare an array arr[3] of 3 pointers.


2. Each element in the array is dynamically allocated using malloc to hold a single integer.
3. We assign values to the dynamically allocated memory.
4. After using the memory, we free it using free() to avoid memory leaks.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy