0% found this document useful (1 vote)
136 views50 pages

Unit 1 2 3

This document discusses concepts related to problem solving and programming in C. It begins by defining a flowchart and its various symbols. It then provides examples of flowcharts for different problems. The rest of the document covers key concepts in C programming like algorithms, data types, variables, constants, arrays, expressions, and different operators. It provides definitions and examples for each concept.

Uploaded by

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

Unit 1 2 3

This document discusses concepts related to problem solving and programming in C. It begins by defining a flowchart and its various symbols. It then provides examples of flowcharts for different problems. The rest of the document covers key concepts in C programming like algorithms, data types, variables, constants, arrays, expressions, and different operators. It provides definitions and examples for each concept.

Uploaded by

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

Problem solving and programming in C

Unit 1
Q1. What is a flow chat and give its various symbols?
Ans. A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the
steps as boxes of various kinds, and their order by connecting them with arrows. This diagrammatic
representation illustrates a solution model to a given problem. Flowcharts are used in analyzing,
designing, documenting or managing a process or program in various fields. Fig below gives a typical
Flow chart diagram.

START

Read Input.

Process

Display results.

END

Various symbols used in flow chart

Assignment Unit 1(Trial)


1
Qa. Give a flow to input age of a person ? If the age is greater than 18 then display “Eligible to vote” or
else not display “Not eligible to vote”
Qb. Give flow chart to convert rupee into Dollars ?
Qc. Give a flow chart to to calculate discount of 10 % on any product above Rs.1000/- ?
Qd. Give a flow chart to display all numbers between 1 to 20 ?
Qe. Give a flow chart to display all even numbers between 10 to 20 ?
Qf. Give a flow chart to display list of numbers and its square from 1 to 10 ?

Q2. Define algorithm?


Ans. Algorithm is a process or set of rules to be followed in calculations or other problem-solving
operations, especially by a computer. An algorithm is a formula or set of steps for solving a particular
problem.

Q3. Give the characteristic / features of an algorithm ? (Just go through and remember only main
points)
Ans. An algorithm has following characteristics:
1. Each and every instruction should be precise and unambiguous i.e. each and every instruction should
be clear and should have only one meaning.
2. Each instruction should be performed in finite time.
3. One or more instructions should not be repeated infinitely. It means that the algorithm must
terminate ultimately.
4. After the instructions are executed, the user should get the required results.
The characteristics of a good algorithm are:
Precision – the steps are precisely stated(defined).
Uniqueness – results of each step are uniquely defined and only depend on the input and the result
of the preceding steps.
Finiteness – the algorithm stops after a finite number of instructions are executed.
Input – the algorithm receives input.
Output – the algorithm produces output.
Generality – the algorithm applies to a set of inputs.

Q4. What are the criteria to be followed by an algorithm?


Ans. An algorithm must satisfy the following criteria:
1. Input- These are the values that are supplied externally to the algorithm.
2. Output- These are the results that are produced by the algorithm.
3. Definiteness- Each step must be clear and unambiguous.
4. Finiteness- The algorithm must terminate after a finite number of steps.
5. Effectiveness- Each step must be feasible i.e. it should be practically possible to perform the step

Q5. What is design or development of an algorithm ?


Ans . Designing the algorithm to solve the problem requires you to develop a list of steps called an
algorithm to solve the problem and to then verify that the algorithm solves the problem as intended.
Writing the algorithm is often the most difficult part of the problem-solving process. Most computer
algorithms consist of at least the following
subproblems.
1. Get the data.
2. Perform the computations.
3. Display the results.

UNIT 2
2
Q6. What is c character set?
C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special
characters as building blocks to form basic program elements (e.g., constants, variables, operators,
expressions, etc.).

The 30 special characters are listed below.


! # % ^ & * ( ) - _ = + ~ ' " : ; ? / | \ { } [ ] , . < > $
Five white space characters:
Space ()
Horizontal tab (\t)
Form feed (\f)
Vertical tab (\v)
New-line character (\n)

Q7. What is a Keywords?


Keywords are preserved words that have special meaning in C language. The meaning of the keywords
has already been described to the C compiler. These meaning cannot be changed. Thus, the keywords
cannot be used as variable names because that would try to change the existing meaning of the
keyword, which is not allowed. There are total 32 keywords in C language.
auto Double int struct

break else long Switch

case enum register typedef

const extern return union

char float short unsigned

continue for signed volatile

3
default goto sizeof void

do If static while

Q8. What is identifier , give rules for naming identifier ?


Identifiers In C language identifiers are the names given to variables, constants, functions and user-
define data. These identifier are defined against a set of rules.

Rules for an Identifier


An Identifier can only have alphanumeric characters( a-z , A-Z , 0-9 ) and underscore( _ ).
The first character of an identifier can only contain alphabet( a-z , A-Z ) or underscore ( _ ).
Identifiers are also case sensitive in C. For example name and Name are two different identifier in C.
Keywords are not allowed to be used as Identifiers.
No special characters, such as semicolon, period, whitespaces, slash or comma are permitted to be used
in or as Identifier.

Q9. What is data types in c?


There are four basic data types associated with variables:
int - integer: (a whole number , without decimal part)
float - floating point value: ie a number with a fractional part.
double - a double-precision floating point value.
char - a single character.

Q10. what is constants in c?


Constants refer to fixed values that the program may not alter during its execution. These fixed values
are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string

Q11. What is a variable ?


A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific data type, which determines the size and layout of the variable's memory.

Q12. What is the difference between constant and variable in c?


Variable can change its value throughout the course of program , but a constant does not change.
int x ;
Here x is a variable of interger type

const int y = 5;
here y is a constant of integer type , its value is fixed to 5 and it cannot be changed in the program.

4
Q13. What is array and how is it declared in c and how it is initialized?
An array is a collection of data that holds fixed number of values of same type. For example: if you want
to store marks of 100 students, you can create an array for it.

float marks[100];

The size and type of arrays cannot be changed after its declaration.
declare an array in C
data_type array_name[array_size];

For example,
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point
values.

int point[6]={4,-3,1,0,10,7};
Here point is an array and its element are initialized as 4, -3 , 1, 0, 10 , 7
Each element of an array is referred by its index. Point [0] is 4 , point [1] is -3 and so on ..

Q14. What is array index or array subscript?


An array is a collection of like variables that share a single name. The individual elements of an array are
referenced by appending a subscript, in square brackets, behind the name.
Example int point[6]={4,-3,1,0,10,7};
Here point [0] -> here 0 is the subscript or index , which is 4
point [1] -> here 1 is the subscript or index , which is-3

Q15. How is array variable different from normal variable ?


An ordinary variable holds a single value; an array variable holds multiple values. Each member of array
variable are referred by its index. Where as normal variable stores only one value. For arrays the
compiler allocates consecutive values in the memory For Normal variables it may not be continuous

Q16. What is expression in c?


An expression is a combination of variables constants and operators written according to the syntax of C
language. In C every expression evaluates to a value i.e., every expression results in some value of a
certain type that can be assigned to a variable.
e.g x + y is an expression
z= x + y (here value of x and y is evaluated and assigned to z)

Q17. Explain different operators in c?


C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler to
perform certain mathematical or logical manipulations. Operators are used in program to manipulate
data and variables.
C operators can be classified into following types, Arithmetic operators, Relation operators, Logical
operators, Bitwise operators , Assignment operators ,Conditional operators ,Special operators

18.Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.
Operator Description

5
+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denominator

% remainder of division

++ Increment operator - increases integer value by one

-- Decrement operator - decreases integer value by one

Relation operators
The following table shows all relation operators supported by C.
Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

Logical operators
C language supports following 3 logical operators. Suppose a=1 and b=0,
Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false

Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of
bits from right to left. Bitwise operators are not applied to float or double.
Operator Description

& Bitwise AND

6
| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Now lets see truth table for bitwise &, | and ^


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
The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and the
right operand specifies the number of positions that the bits in the value are to be shifted. Both
operands have the same precedence.

Example :
a = 0001000
b= 2
a << b //( becomes 0100000) // shifts a by 2 position left. Notice that 1 has shifted left side by 2 spaces
a >> b// (becomes 0000010) //shifts a by 2 position right. Notice that 1 has shifted right side by 2
spaces

Assignment Operators
Assignment operators supported by C language are as follows.
Operator Description Example

= assigns values from right side operands to left side a=b


operand

+= adds right operand to the left operand and assign the a+=b is same as
result to left a=a+b

-= subtracts right operand from the left operand and assign a-=b is same as
the result to left operand a=a-b

*= mutiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b

/= divides left operand with the right operand and assign the a/=b is same as
result to left operand a=a/b

%= calculate modulus using two operands and assign the a%=b is same as
result to left operand a=a%b

19 . Conditional operator

7
The conditional operator in C is if and other one is ‘?’ called ternary operator
Ternary Operator
? : Operator
It is actually the if condition that we use in C language, but using conditional operator, we turn if
condition statement into more simple line of code conveying the same thing.
The syntax of a conditional operator is :
expression 1 ? expression 2: expression 3

Explanation-
The question mark "?" in the syntax represents the if part.
The first expression (expression 1) is use to check true or false condition only.
If that condition (expression 1) is true then the expression on the left side of " : " i.e expression 2 is
executed.
If that condition (expression 1) is false then the expression on the right side of " : " i.e expression 3 is
executed.
Special operator
Operator Description Example

sizeof Returns the size of an variable sizeof(x) return size of the variable x

& Returns the address of an variable &x ; return address of the variable x

* Pointer to a variable *x ; will be pointer to a variable x

Q20. Explain increment and decrement operators in c?


Increment and Decrement Operator , increases or decreases the value of an operand.
Example
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000

Q21. What is pre and post , increment and decrement?


++a is pre increment. it first increment the value of an operand then it assigns it to the variable.
a++ is post increment first it assigns the value to a variable then it increments
similar is pre decrement –a and post decrement a --.

Q22. Library Function and Header File

8
A C header file is a text file that contains pieces of code written in the C programming language. The
name of a header file, by convention, ends with the . h extension. It is inserted inside a program by
coding the #include <headerFilename.h>

C Standard library functions or simply C Library functions are inbuilt functions in C programming.
The prototype and data definitions of the functions are present in their respective header files, and
must be included in your program to access them.
For example: If you want to use printf() which is a libraby function, the header file <stdio.h> should be
included.

Q23. What is input / output (I/O) in c?


C programming has several in-built library functions to perform input and output tasks.
Like printf, scanf, gets, puts, getchar, putchar, frpintf, fscanf

Two commonly used functions for I/O (Input/Output) are printf() and scanf().
The scanf() function reads formatted input from standard input (keyboard) whereas the printf() function
sends formatted output to the standard output (screen).
Example #1: C Output
#include <stdio.h> //This is needed to run printf() function.
int main()
{
printf("C Programming"); //displays the content inside quotation
return 0;
}

Output
C Programming

Example scanf() and printf() functions


#include<stdio.h>
#include<conio.h>
void main()
{
int i;
printf("Enter a value");
scanf("%d",&i);
printf( "\nYou entered: %d",i);
getch();
}
When you will compile the above code, it will ask you to enter a value. When you will enter the value, it
will display the value you have entered.

24 getchar() & putchar() functions


The getchar() function reads a character from the terminal and returns it as an integer. This function
reads only single character at a time. You can use this method in the loop in case you want to read more
than one characters. The putchar() function prints the character passed to it on the screen and returns
the same character. This function puts only single character at a time. In case you want to display more
than one characters, use putchar() method in the loop.
9
#include <stdio.h>
#include <conio.h>
void main( )
{
int c;
printf("Enter a character");
c=getchar();
putchar(c);
getch();
}
When you will compile the above code,it will ask you to enter a value. When you will enter the value, it
will display the value you have entered.

25. gets() & puts() functions


The gets() function reads a line from stdin into the buffer pointed to by s until either a terminating
newline or EOF (end of file) occurs. The puts() function writes the string s and a trailing newline to
stdout.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
When you will compile the above code,it will ask you to enter a string. When you will enter the string, it
will display the value you have entered.

26. Difference between scanf() and gets()


The main difference between these two functions is that scanf() stops reading characters when it
encounters a space, but gets() reads space as character too.
If you enter name as Study Tonight using scanf() it will only read and store Study and will leave the part
after space. But gets() function will read it completely.

27. getch() and putch


This function is used to get (read) single character from standard input device (keyboard) without
echoing i.e. it does not display the input character & it does not require [return] key after
input. getch()is declared in conio.h header file.
/*Compatible for TurboC compiler */
#include <stdio.h>
#include <conio.h>

int main()
{
char ch;
printf("Enter a character :");
ch=getch();
printf("\nEntered character is : %c",ch);
10
return 0;
}

28.putchar() & putch()


These functions are used to put (print) a single character on standard output device (monitor).
#include <stdio.h>
Void main()
{
char ch;
printf("Enter a character :");
ch=getchar();
printf("\nEntered character is :");
putchar(ch);

29. Difference of getc ,getch , getche , getchar


Firstly, getch() and getche() are non standard library functions found in conio.h. Hence, they
are useless and should never be used (nor the Turbo C/C++ compilers).
getc():
It reads a single character from a given input stream and returns the corresponding integer value
(typically ASCII value of read character) on success. It returns EOF on failure.

getchar():

The difference between getc() and getchar() is getc() can read from any input stream, but getchar()
reads from standard input. So getchar() is equivalent to getc(stdin).

getch():
getch() is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS
compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX
(Source:conio.h)
Like above functions, it reads also a single character from keyboard. But it does not use any buffer, so
the entered character is immediately returned without waiting for the enter key.

getche()
Like getch(), this is also a non-standard function present in conio.h. It reads a single character from the
keyboard and displays immediately on output screen without waiting for enter key.

getc() with this function we Input charater from input stream. it work same as getchar();

getchar ( )It will accept a character from keyboard , displays immediately while typing and we need to
press Enter key for proceeding.

getch ( ) It just accepts a keystroke and never displays it and proceeds further. Normally we use it at the
end of the main ( ).

getche ( )It will accept a character from keyboard , displays it immediately and does not wait for Enter
key to be pressed for proceeding.

clrscr() is a library function which is used clear the output screen , its written inside the conio.h header
file
11
Q30 What is control statement in c?
C provides two styles of flow control:
Branching and Looping
Branching is deciding what actions to take and looping is deciding how many times to take a certain
action.
Branching:
Branching is so called because the program chooses to follow one branch or another.
if statement
This is the most simple form of the branching statements. It takes an expression in parenthesis and an
statement or block of statements. if the expression is true then the statement or block of statements
gets executed otherwise these statements are skipped.

NOTE: Expression will be assumed to be true if its evaulated values is non-zero.


if statements take the following form:
Show Example
1. if (expression)
statement;

or

2. if (expression)
{
Block of statements; it means more than one line
}

or

3. if (expression)
{
Block of statements;
}
else
{
Block of statements;
}

or

4. if (expression)
{
Block of statements;
}
else if(expression)
12
{
Block of statements;
}
else
{
Block of statements;
}

Q31. What is ternary Operator (?)


The ? : operator is just like an if ... else statement except that because it is an operator you can use it
within expressions.
? : is a ternary operator in that it takes three values, this is the only ternary operator C has.
? : takes the following form:

if condition is true ? then X return value : otherwise Y value;

Example Example
//Looking at the maximum example

int findMaximum(int a, int b){

return (a > b) ? a : b; //if a > b, it returns a, if not it returns b


}
Another Example
#include <stdio.h>

main()
{
int a , b;

a = 10;
printf( "Value of b is %d\n", (a == 1) ? 20: 30 );

printf( "Value of b is %d\n", (a == 10) ? 20: 30 );


}
This will produce following result:

Value of b is 30
Value of b is 20

32. Switch statement:


The switch statement is much like a nested if .. else statement. Its mostly a matter of preference which
you use, switch statement can be slightly more efficient and easier to read.
Show Example
switch( expression )
{
case constant-expression1: statements1;

13
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]
[default : statements4;]
}

33. Using break keyword:


If a condition is met in switch case then execution continues on into the next case clause also if it is not
explicitly specified that the execution should exit the switch statement. This is achieved by
using break keyword. So break is used to end the case in switch
Try out given example Show Example

What is default condition in switch case : ?


If none of the listed conditions is met then default condition executed.
Try out given example Show Example

34. What is Looping ? explain different types of looping ?


Loops provide a way to repeat commands and control how many times they are repeated. C provides a
number of looping way.
while loop
The most basic loop in C is the while loop.A while statement is like a repeating if statement. Like an If
statement, if the test condition is true: the statments get executed. The difference is that after the
statements have been executed, the test condition is checked again. If it is still true the statements get
executed again. This cycle repeats until the test condition evaluates to false.
Basic syntax of while loop is as follows:
Show Example
while ( expression )
{
Single statement
or
Block of statements;
}

for loop
for loop is similar to while, it's just written differently. for statements are often used to proccess lists
such a range of numbers:
Basic syntax of for loop is as follows:
Show Example
for( expression1; expression2; expression3)
{
Single statement
or
Block of statements;
}

In the above syntax:


expression1 - Initialisese variables.
expression2 - Condtional expression, as long as this condition is true, loop will keep executing.
expression3 - expression3 is the modifier which may be simple increment of a variable.
do...while loop

14
do ... while is just like a while loop except that the test condition is checked at the end of the loop
rather than the start. This has the effect that the content of the loop are always executed at least once.
Basic syntax of do...while loop is as follows:
Show Example
do
{
Single statement
or
Block of statements;
}while(expression);
break and continue statements
C provides two commands to control how we loop:
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.
You already have seen example of using break statement. Here is an example showing usage
of continue statement.

#include <stdio.h>
Void main()
{
int i;
int j = 10;

for( i = 0; i <= j; i ++ )
{
if( i == 5 )
{
continue;
}
printf("Hello %d\n", i );
}
}
This will produce following output:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10

Q35. What is loop ?


Loops are used in programming to repeat a specific block until some end condition is met. There are
three loops in C programming:
for loop
15
while loop
do...while loop

Q36. Give difference of while and do .. while loop?


A while loop checks the Condition in the beginning where as a do..while loops checks condition after
excuting the loop once. So a do wile loop will run atleast once even if the condition is false.

Q37. Goto statement


Goto is used to jump from one part of program to another part, where the goto label is specified

Example
void main(){
printf(“Hello ”);
goto l;
printf(“World”);
l:printf(“Program over”)

Output : Hello Program over


Reason is after printing hello on screen it will directly jump to goto l; So printf(“World”) will not a get a
chance to execute.

Q38 Nested Loop


A nested loop means a loop statement inside another loop statement. That is why nested loops are also
called “loop inside loops“. We can define any number of loops inside another loop.
Example 1

1. Outer_loop
2. {
3. Inner_loop
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }

Another Example

1. for (initialization; condition; update)


2. {
3. for(initialization; condition; update)
4. {

16
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Example with program

1. #include <stdio.h>
2. int main()
3. {
4. int n;// variable declaration
5. printf("Enter the value of n :");
6.
7. for(int i=1;i<=n;i++) // outer loop
8. {
9. for(int j=1;j<=10;j++) // inner loop
10. {
11. printf("%d\t",(i*j)); // printing the value.
12. }
13. printf("\n");
14. }

Q39. What is symbolic constant?


A symbolic constant is name that substitute for a sequence of character that cannot be changed. The
character may represent a numeric constant, a character constant, or a string. When the program is
compiled, each occurrence of a symbolic constant is replaced by its corresponding character sequence.
They are usually defined at the beginning of the program.
Example
#include<stdio.h>
#include<conio.h>
#define PI 3.14
void main()
{
float r=3, area=0;
area= PI * r * r;
printf(“area =%f”, area)
getch();
}

Q40. What is an array ?


An array is collection of items of same type .

17
Fig above is one dimensional array

Here x is array of size 5 . x[0] , x[2] , x[3] , x[4] x[5] are called array members or variables

Arrays can be one dimensional or multi dimensional

Fig above is two dimensional array. A two dimensional array has multiple rows and columns

Q41. How do we declare array ?


int x [5]
Here x is an array of size 5 , al the element of the array
here are integer type

Q42. How is array initialized ?


It is possible to declare and array and initialized it as the same time. This is how it is done
Int x [5] ={2, -1 , 0 , 3 , 5}

18
UNIT-II continues: Functions, Arrays (Theory)

A function is a self-contained block of code that performs a specific task or a set of tasks. Functions
provide a way to modularize code, making it easier to read, understand, and maintain. Functions are
used to break down a large program into smaller, manageable pieces, each of which can be written and
tested independently

A function in C consists of a function declaration, a function definition, and a function call

Functions in C have a return type, a name, parameters (optional), and a body. Here's the basic syntax of
a function in C

return_type function_name(parameters) {
// function body
// statements to be executed
// return statement (if applicable)
}

 return_type: It specifies the type of value that the function will return. It can be int, float,
double, char, void (if the function doesn't return any value), or any other data type in C.
 function_name: It is the name of the function you define. Choose a descriptive name that
indicates the purpose of the function.
 parameters: These are optional. If a function requires some data to work on, you can pass
parameters (also known as arguments) to the function. Parameters are enclosed in parentheses
and separated by commas. For example, int x, int y are parameters.
 function body: It contains the actual code that the function will execute. It is enclosed in curly
braces {}.
 return statement: If the function has a return type other than void, it must contain a return
statement to return a value of the specified type.

Here's an example of a simple function that adds two integers and returns the result:

#include <stdio.h>
// Function declaration
int add(int a, int b);

int main() {
int result = add(3, 5); // Function call
printf("Sum is %d\n", result);
return 0;
}

// Function definition
int add(int a, int b) {
int c;
c = a + b;
return c;
}

Call by value in C
19
o In call by value method, the value of the actual parameters is copied into the formal parameters.
In other words, we can say that the value of the variable is used in the function call in the call by
value method.
o In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
o In call by value, different memory is allocated for actual and formal parameters since the value
of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.

Call by Value Example: Swapping the values of the two variables


1. #include <stdio.h>
2. void swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a an
d b in main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual par
ameters do not change by changing the formal parameters in call by value, a = 10, b = 20
10. }
11. void swap (int a, int b)
12. {
13. int temp;
14. temp = a;
15. a=b;
16. b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20,
b = 10
18. }

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

20
Call by reference in C

In call by reference, the address of the variable is passed into the function call as the actual parameter.

The value of the actual parameters can be modified by changing the formal parameters since the
address of the actual parameters is passed.

In call by reference, the memory allocation is similar for both formal parameters and actual parameters.
All the operations in the function are performed on the value stored at the address of the actual
parameters, and the modified value gets stored at the same address.

Call by reference Example: Swapping the values of the two variables


1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a an
d b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameter
s do change in call by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 2
0, b = 10
18. }

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

21
Difference between call by value and call by reference in c

No Call by value Call by reference


.

1 A copy of the value is passed into the function An address of value is passed into the
function

2 Changes made inside the function is limited to the Changes made inside the function
function only. The values of the actual parameters validate outside of the function also. The
do not change by changing the formal values of the actual parameters do
parameters. change by changing the formal
parameters.

3 Actual and formal arguments are created at the Actual and formal arguments are created
different memory location at the same memory location

C Storage Classes and Storage Class Specifiers


What is a Storage Class?
Storage Class Specifiers
Types of Storage Classes
What is a Storage Class?
Storage class in C decides the part of storage to allocate memory for a variable, it also determines the
scope of a variable. All variables defined in a C program get some physical location in memory where
variable's value is stored. Memory and CPU registers are types of memory locations where a variable's
value can be stored. The storage class of a variable in C determines the life time of the variable if this is
'global' or 'local'. Along with the life time of a variable, storage class also determines variable's storage
location (memory or registers), the scope (visibility level) of the variable, and the initial value of the
variable. There are four storage classes in C those are automatic, register, static, and external.

Types of Storage Classes


There are four storage classes in C they are as follows:
Automatic Storage Class (by default all variable are auto)
Register Storage Class (its stored in the register )
Static Storage Class (retains its value between different function calls)
External Storage Class (just like Global variable)

22
String Functions:

1. strcmp(): Compares two strings and returns an integer value representing their relationship. It
returns 0 if the strings are equal, a negative value if the first string is less than the second, and a
positive value if the first string is greater than the second.
2. strlen(): Calculates the length (number of characters) of a null-terminated string and returns the
count as an integer.
3. strrev(): Reverses the characters in a given string in-place. It modifies the original string.
4. strcat(): Concatenates (appends) the contents of one string to another. It combines two strings
into one.
5. strcpy(): Copies the contents of one string to another, overwriting the destination string with the
source string.
6. toupper(): Converts a character to its uppercase equivalent if it's a lowercase alphabet
character. It doesn't modify non-alphabet characters.
7. tolower(): Converts a character to its lowercase equivalent if it's an uppercase alphabet
character. It doesn't modify non-alphabet characters.

Math Functions:

1. sqrt(): Calculates the square root of a given number and returns a floating-point result.
2. abs(): Computes the absolute (positive) value of a number. It returns a non-negative value
regardless of the input's sign.
3. sin(): Calculates the sine of an angle in radians and returns a floating-point value between -1 and
1.
4. cos(): Computes the cosine of an angle in radians and returns a floating-point value between -1
and 1.

23
Standard exit function
In C programming, the exit() function is a standard library function that is used to terminate the
program execution and exit to the operating system. It is declared in the stdlib.h header file. The exit()
function accepts an integer argument, which is used as the exit status of the program.
Example given below
#include <stdio.h>
#include <stdlib.h>

int main() {
printf("This is before the exit function.\n");

// Exit the program with a status code of 0 (indicating successful execution).


exit(0);

// This code will not be executed as the program has already exited.
printf("This is after the exit function.\n");

return 0;
}

In this example, the program will terminate immediately after the exit(0) statement, and the
second printf() statement will not be executed.

Array:
What is array and how is One Dimensional Array declared in c and how it is initialized?
An array is a collection of data that holds fixed number of values of same type. For example: if you want
to store marks of 100 students, you can create an array for it.

float marks[100];

The size and type of arrays cannot be changed after its declaration.
declare an array in C
data_type array_name[array_size];

For example,
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point
values.

int point[6]={4,-3,1,0,10,7};
Here point is an array and its element are initialized as 4, -3 , 1, 0, 10 , 7
Each element of an array is referred by its index. Point [0] is 4 , point [1] is -3 and so on

24
Another Example
#include <stdio.h>

int main() {
// Declare and initialize a one-dimensional array of integers
int myArray[5] = {1, 2, 3, 4, 5};

// Accessing elements of the array and printing them


printf("Elements of the array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", myArray[i]);
}
return 0;
}

In this example, int myArray[5] declares an array of integers with a size of 5. The elements of
the array are initialized within curly braces {}. The values 1, 2, 3, 4, 5 are assigned to the
elements of the array respectively.

You can change the size of the array and the values inside the curly braces to create an array of
different sizes and with different initial values.

Passing a one-dimensional array to a function


it is straightforward. we can declare the function to accept an array as a parameter, and within
the function, you can access the array elements. Here's a simple example

#include <stdio.h>

// Function that takes a 1D array as a parameter


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

int main() {
const int size = 5;

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

// Passing the 1D array to the function


printArray(myArray, size);

return 0;
}

25
pass a one-dimensional array to a function using pointers.
When you pass an array to a function, it decays into a pointer to its first element. Here's an
example
#include <stdio.h>

int main() {

const int size = 5;

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

// Passing the 1D array to the function using pointers

printArray(myArray, size);

return 0;

// Function that takes a 1D array using pointers

void printArray(int *arr, int size) {

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

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

printf("\n");

What is two Dimentional array in c ?


A two-dimensional (2D) array in C is an array of arrays. It is a data structure that can store
elements in a grid or matrix format, where each element is uniquely identified by two indices –
row and column. In C, 2D arrays.
A two-dimensional array, also known as a matrix, is an array of arrays. In programming, it is a
data structure that can hold a collection of values organized in a grid with rows and columns.
Each element in a two-dimensional array is identified by two indices: the row index and the
column index. Passing a 2 D array to a function

26
Here's an example of a 2D array declaration and initialization in C:

#include <stdio.h>
int main() {
// Declare and initialize a 2D array with 3 rows and 4 columns
int myArray[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Access and print elements of the 2D array
printf("Elements of the 2D array:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", myArray[i][j]);
}
printf("\n");
}
return 0;
}
Explanation : In this example, myArray is a 2D integer array with 3 rows and 4 columns. The
elements are initialized using nested curly braces. To access elements in a 2D array, you use two
indices: the first one for the row and the second one for the column. In the nested for loop in
the main function, all elements of the 2D array are printed.

#include <stdio.h>
// Function that takes a 2D array as a parameter
int main() {
const int rows = 3;
const int cols = 3;

int myArray[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

printArray(rows, cols, myArray); // Passing the 2D array to the function

return 0;
}

void printArray(int rows, int cols, int arr[rows][cols]) {


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

27
}

Pass 2 D array using pointers

// Function that takes a 2D array using pointers


#include<stdio.h>
void print2DArray(int **arr, int rows, int cols) // prototype
int main() {
const int rows = 3;
const int cols = 3;

int myArray[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Passing the 2D array to the function using pointers


print2DArray(myArray, rows, cols);

return 0;
}

void print2DArray(int **arr, int rows, int cols) {


for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
printf("%d ", *(arr+i)+j);
}
printf("\n");
}
}

28
Unit 3(Pointers)
In computer programming, a pointer is a variable that stores the memory address of another variable.

Here are some key concepts related to pointers:

1. Memory Address:

 Every variable in a program is stored in a specific memory location, and each location has
a unique address.
2. Declaration of Pointers:

 A pointer is declared with the data type it points to, followed by an asterisk *, and then the
name of the pointer variable. For example:

3.Initialization of Pointers:

 A pointer can be initialized with the address of another variable using the address-of operator &.
For example:

int num = 42;

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

In computer programming, a pointer is a variable that stores the memory address of another variable.
Pointers are fundamental in languages like C and C++ and are used for various purposes, including
dynamic memory allocation, array manipulation, and accessing functions indirectly.

Here are some key concepts related to pointers:

1. Memory Address:

 Every variable in a program is stored in a specific memory location, and each location has
a unique address.
2. Declaration of Pointers:

 A pointer is declared with the data type it points to, followed by an asterisk *, and then the
name of the pointer variable. For example:

int *ptr; // Pointer to an integer

3. Initialization of Pointers:

 A pointer can be initialized with the address of another variable using the address-of
operator &. For example:

int num = 42;


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

4.Dereferencing Pointers:
29
 Dereferencing a pointer means accessing the value it points to. It is done using the
dereference operator *. For example:

int value = *ptr; // 'value' now holds the value pointed to by 'ptr'

5. Pointer Arithmetic:

 Pointers can be incremented or decremented, and arithmetic operations can be performed on them.
This is commonly used with arrays. For example:

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

int *p = arr; // 'p' points to the first element of the array

int thirdElement = *(p + 2); // Accessing the 3rd element using pointer arithmetic

6. Dynamic Memory Allocation:

 Pointers are crucial for dynamic memory allocation using functions like malloc, calloc, and
realloc. For example:

int *dynamicPtr = (int *)malloc(sizeof(int)); //Allocating memory for integer

7. Null Pointers:

 A pointer that does not point to any valid memory location is often set to NULL (or nullptr in
C++). It indicates that the pointer is not pointing to anything. For example

int *nullPtr = NULL; // Null pointer

30
Passing a pointer to a function

C allows the function to access and modify the value stored at the memory location pointed to by the
pointer. This is useful for functions that need to operate on or manipulate data outside their local
scope. Here's an example: We can pass pointer as aruments in a function

#include <stdio.h>

// Function that takes a pointer to an integer and modifies its value

void modifyValue(int *ptr) {

// Dereference the pointer and modify the value

*ptr = 20;

int main() {

int num = 10;

printf("Before function call: %d\n", num);

// Pass the address of 'num' to the function

modifyValue(&num);

printf("After function call: %d\n", num);

return 0;

Passing a pointer to a function in C allows the function to access and modify the value stored at the
memory location pointed to by the pointer. This is useful for functions that need to operate on or
manipulate data outside their local scope. Here's an example:
#include <stdio.h>
// Function that takes a pointer to an integer and modifies its value
void modifyValue(int *ptr) {
// Dereference the pointer and modify the value
*ptr = 20;
}
int main() {
int num = 10;
printf("Before function call: %d\n", num);
// Pass the address of 'num' to the function
modifyValue(&num);
printf("After function call: %d\n", num);
return 0;
}

In this example:

31
1. The modifyValue function takes a pointer to an integer as its parameter.
2. Inside the function, the value at the memory location pointed to by ptr is modified.

When calling the function from main, the address of the variable num is passed to the function using the
address-of operator &. As a result, the function modifies the actual value of num.

Output:

Before function call: 10

After function call: 20

Arrays of pointers

It means creating an array where each element is a pointer to a specific type. This is commonly used for
managing arrays of strings, dynamic memory allocation, and other situations where an array of pointers is
more flexible than a simple array of values. Here's a basic example:

#include <stdio.h>

int main() {

// Array of pointers to integers

int *ptrArray[3];

// Individual integers

int num1 = 10, num2 = 20, num3 = 30;

// Assigning the addresses of the integers to the array of pointers

ptrArray[0] = &num1;

ptrArray[1] = &num2;

ptrArray[2] = &num3;

// Accessing values through the array of pointers

printf("Value at index 0: %d\n", *ptrArray[0]);

printf("Value at index 1: %d\n", *ptrArray[1]);

printf("Value at index 2: %d\n", *ptrArray[2]);

return 0;

In this example:

32
 ptrArray is an array of pointers to integers.
 num1, num2, and num3 are individual integers.
 The addresses of these integers are assigned to the elements of the ptrArray.
 By dereferencing the pointers in the array, you can access the values they point to.

function pointers or pointer to a function to call a function indirectly. This allows you to decide at
runtime which function to call. Here's a simple example:
#include <stdio.h>
// Function 1
void add(int a, int b) {
printf("Sum: %d\n", a + b);
}
// Function 2
void subtract(int a, int b) {
printf("Difference: %d\n", a - b);
}

int main() {
// Declare a function pointer that takes two ints as parameters and returns void
void (*operation)(int, int);
// Assign the address of the 'add' function to the function pointer
operation = add;
// Call the function indirectly through the function pointer
operation(5, 3);
// Assign the address of the 'subtract' function to the function pointer
operation = subtract;
// Call the 'subtract' function indirectly through the function pointer
operation(5, 3);
return 0;
}

In this example:

33
 Two functions, add and subtract, take two integers as parameters and perform addition and
subtraction, respectively.
 A function pointer named operation is declared, which can point to functions taking two
integers and returning void.
 The function pointer is assigned the address of the add function, and then the subtract
function.
 The function pointer is used to call the functions indirectly.

This allows you to dynamically choose which function to call at runtime based on the assignment to the
function pointer.

Functions as arguments to other functions.


This is often referred to as "function pointers" and is useful in scenarios where you want to customize the
behavior of a function dynamically. Here's a simple example:

#include <stdio.h>
// Function that takes two integers and a function pointer
void operate(int a, int b, void (*operation)(int, int)) {
operation(a, b);
}

// Example functions that can be passed as arguments


void add(int a, int b) {
printf("Sum: %d\n", a + b);
}
void subtract(int a, int b) {
printf("Difference: %d\n", a - b);
}
int main() {
// Pass the 'add' function as an argument to 'operate'
operate(5, 3, add);
// Pass the 'subtract' function as an argument to 'operate'
operate(5, 3, subtract);
return 0;
}

functions as arguments to other functions. This is often referred to as "function pointers" and is useful

34
in scenarios where you want to customize the behavior of a function dynamically. Here's a simple
example:

#include <stdio.h>

// Function that takes two integers and a function pointer


void operate(int a, int b, void (*operation)(int, int)) {
operation(a, b);
}

// Example functions that can be passed as arguments


void add(int a, int b) {
printf("Sum: %d\n", a + b);
}

void subtract(int a, int b) {


printf("Difference: %d\n", a - b);
}

int main() {
// Pass the 'add' function as an argument to 'operate'
operate(5, 3, add);

// Pass the 'subtract' function as an argument to 'operate'


operate(5, 3, subtract);

return 0;
}

In this example:

 The operate function takes two integers (a and b) and a function pointer (operation) as
arguments.
 The function pointer is expected to point to a function that takes two integers and returns void.
 The operate function then calls the provided function pointer with the given integers.

In the main function:

 The add and subtract functions are defined, each taking two integers and printing the result.
 The operate function is called twice, once with the add function and once with the
subtract function.

This way, you can dynamically specify the behavior of the operate function by passing different
functions as arguments. This concept is commonly used in callback functions, allowing you to change the
behavior of a function without modifying its code.

35
Functions returning pointers : In c a function can return pointer to the calling program example
given below
// Function returning pointer

int* fun()

int A = 10;

return (&A);

int main()

// Declare a pointer

int* p;

// Function call

p = fun();

printf("%p\n", p);

printf("%d\n", *p);

return 0;

Dynamic memory allocation

Dynamic memory allocation in C


The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h
header file. Since C is a structured language, it has some fixed rules for programming. One of them
includes changing the size of an array. An array is a collection of items stored at contiguous
memory locations
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory allocation and
dynamic memory allocation.

static memory allocation dynamic memory allocation


memory is allocated at compile time. memory is allocated at run time.

36
memory can't be increased while executing memory can be increased while executing
program. program.
used in array. used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc() allocates single block of requested memory.


calloc() allocates multiple block of requested memory.
realloc() reallocates the memory occupied by malloc() or calloc() functions.
free() frees the dynamically allocated memory.

The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large
block of memory with the specified size. It returns a pointer of type void which can be cast into a
pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized each
block with the default garbage value initially.

Syntax of malloc() in C

ptr = (cast-type*) malloc(byte-size)

ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr
holds the address of the first byte in the allocated memory.

.
Q6. Explain Dynamic memory allocation

The concept of dynamic memory allocation in c language enables the C programmer to allocate memory
at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

They are malloc() , calloc() realloc() . free().

So dynamic memory allocation is used to allocate memory when we run the program .

37
Before learning above functions, let's understand the difference between static memory allocation and
dynamic memory allocation.

static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run time.

memory can't be increased while executing memory can be increased while executing
program. program.

used in array. used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

realloc( reallocates the memory occupied by malloc() or calloc() functions.


)

free() frees the dynamically allocated memory.

malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)

// For Theory example program are not very imp , but definition of Calloc and maloc is very imp

Let's see the example of malloc() function.

#include <stdio.h>

#include <stdlib.h>

void main(){
38
int n,i,*ptr,sum=0;

printf("Enter number of elements: ");

scanf("%d",&n);

ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc

if(ptr==NULL)

printf("Sorry! unable to allocate memory");

exit(0);

printf("Enter elements of array: ");

for(i=0;i<n;++i)

scanf("%d",ptr+i); // or you can write scanf(“%d”,&ptr[i]);

free(ptr);

Output:

Enter elements of array: 3

Enter elements of array: 10

10

10

Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

Calloc The syntax of calloc() function is given below:

ptr=(cast-type*)calloc(number, byte-size)

Let's see the example of calloc() function.


39
#include <stdio.h>

#include <stdlib.h>

void main(){

int n,i,*ptr,sum=0;

printf("Enter number of elements: ");

scanf("%d",&n);

ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc

if(ptr==NULL)

printf("Sorry! unable to allocate memory");

exit(0);

printf("Enter elements of array: ");

for(i=0;i<n;++i)

scanf("%d",ptr+i);

sum+=*(ptr+i);

printf("Sum=%d",sum);

free(ptr);

Output:

Enter elements of array: 3

Enter elements of array: 10

10

10

Sum=30

40
realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function.
In short, it changes the memory size.

Let's see the syntax of realloc() function.

ptr=realloc(ptr, new-size)

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

free(ptr)

Q7. Give the difference of callo , malloc , realloc

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function.

41
Structures

In C programming, a structure is a user-defined data type that allows you to group together
different data types under a single name. Each element in the structure is called a member, and
you can access these members using the dot (.) operator. Here's an example of how you can
define a structure in C

#include <stdio.h>

// Define a structure named 'Person'

struct Person {

char name[50];

int age;

float height;

};

int main() {

// Declare a variable of type 'struct Person'

struct Person person1;

// Assign values to the members of the structure

printf("Enter person's name: ");

scanf("%s", person1.name);

printf("Enter person's age: ");

scanf("%d", &person1.age);

printf("Enter person's height: ");

scanf("%f", &person1.height);

// Display information using the structure

printf("\n Person's Information:\n");

printf("\n Name: %s", person1.name);

printf("\n Age: %d", person1.age);

printf("\n Height: %.2f", person1.height);

return 0;

42
Array of structures Once you've defined a structure, you can process its members in various ways. Here's an
example of how you can define a structure and process it in C by creating array of structures

#include <stdio.h>

struct Person {

char name[50];

int age;

float height;

};

int main() {

// Declare an array of structures

struct Person people[3]; // here people is an array of structure of Person type

// Input information for each person

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

printf("Enter person %d's name: ", i + 1);

scanf("%s", people[i].name);

printf("Enter person %d's age: ", i + 1);

scanf("%d", &people[i].age);

printf("Enter person %d's height: ", i + 1);

scanf("%f", &people[i].height);

// Display information for each person using the displayPerson function

printf("Person's Information:\n");

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

printf("\nName: %s", p[i].name);

printf("\nAge: %d", p[i].age);

printf("\nHeight: %f", p[i].height);

printf("\n");

return 0; }

For Extra explanation :: In this example:

43
 We define a structure named Person.
 We create an array people of type struct Person to store information about multiple people.
 We use a for loop to input information for each person using scanf.
 We define a function displayPerson that takes a struct Person as a parameter and displays
information about that person.
 Finally, we use another for loop to display information for each person in the array.
Passing structure to a Function
In C, you can pass structures to functions just like any other variable. When passing a structure to a
function, you can pass it by value or by reference (using pointers). Here's an example illustrating both
methods:
#include <stdio.h>

// Define a structure named 'Person'


struct Person {
char name[50];
int age;
float height;
};

int main() {
// Declare a variable of type 'struct Person' and initialize it
struct Person person1 = {"John Doe", 25, 175.5};

// Pass the structure by value to the function


displayPersonByValue(person1);

// Pass the structure by reference using a pointer to the function


displayPersonByReference(&person1);
return 0;
}
// Function to display information about a person (passed by value)
void displayPersonByValue(struct Person p) {
printf("Person's Information (Passed by Value):\n");
printf("Name: %s\n", p.name);
printf("Age: %d\n", p.age);
printf("Height: %.2f\n", p.height);
}

44
// Function to display information about a person (passed by reference using a pointer)
void displayPersonByReference(struct Person *p) {
printf("Person's Information (Passed by Reference):\n");
printf("Name: %s\n", p->name);
printf("Age: %d\n", p->age);
printf("Height: %.2f\n", p->height);
}

Self-referential structures,
also known as linked structures or recursive structures, are structures in which a member of the structure
is a pointer to the same type of structure. These structures are commonly used in the implementation of
linked lists, trees, and other data structures where elements are connected in a hierarchical or sequential
manner.
For example, consider the following code:
struct Node {
int data;
Node* next;
};

Explanation
Here, Node is a self-referential structure because it contains a pointer to a Node object (next). This allows
us to create a linked list, where each node points to the next node in the list.

Bit fields in structures


allows us to specify the number of bits that should be used for each member of a structure. This can be
useful when you want to optimize memory usage and pack several variables into a smaller space.
#include <stdio.h>

// Define a structure using bit fields


struct Flags {
unsigned int isSet1 : 1; // 1 bit for isSet1
unsigned int isSet2 : 1; // 1 bit for isSet2
unsigned int value : 4; // 4 bits for value (0 to 15)
};

int main() {
// Declare a variable of type 'struct Flags'
struct Flags flags;
// Set values using bit fields
flags.isSet1 = 1; // true
flags.isSet2 = 0; // false
45
flags.value = 7; // binary 0111

// Display the values


printf("isSet1: %u\n", flags.isSet1);
printf("isSet2: %u\n", flags.isSet2);
printf("value: %u\n", flags.value);

// Size of the structure in bytes


printf("Size of struct Flags: %lu bytes\n", sizeof(struct Flags));
return 0;
}

union
is a user-defined data type that allows you to store different data types in the same memory location.
Unlike structures, where each member has its own separate memory space, members of a union share the
same memory location. The size of a union is determined by the size of its largest member.

Example
#include <stdio.h>

// Define a union named 'Data'


union Data {
int intValue;
float floatValue;
char stringValue[20];
};
int main() {
// Declare a variable of type 'union Data'
union Data data;
// Access and modify members of the union
data.intValue = 42;
printf("intValue: %d\n", data.intValue);
data.floatValue = 3.14;
printf("\nfloatValue: %f", data.floatValue);
printf("\nstringValue: %s", data.stringValue);
// Size of the union in bytes
printf("Size of union Data: %lu bytes\n", sizeof(union Data));
return 0;
46
}

In this example:
 The union Data has three members: intValue (an integer), floatValue (a floating-point
number), and stringValue (an array of characters).
 All three members share the same memory location. When you modify one member, the others
may contain unpredictable values.
 The sizeof operator is used to determine the size of the union.

Unions are often used in situations where you need to represent the same data in different ways or when
memory efficiency is crucial.

Union of structures
Allows you to combine multiple structures within a union, and each structure can have its own set of
members. The memory allocated for the union is large enough to accommodate the largest structure
within it.
#include <stdio.h>
// Define a structure for phone number
struct PhoneNumber {
char areaCode[4];
char number[11];
};

// Define a structure for email address


struct EmailAddress {
char email[50];
};

// Define a union for contact information


union ContactInfo {
struct PhoneNumber phone;
struct EmailAddress email;
};

int main() {
// Declare a variable of type 'union ContactInfo'
union ContactInfo contact;

// Set values for a phone number


printf("Enter area code: ");
47
scanf("%s", contact.phone.areaCode);

printf("Enter phone number: ");


scanf("%s", contact.phone.number);

// Print the phone number


printf("\n Phone Number: %s-%s", contact.phone.areaCode,
contact.phone.number);

// Set values for an email address


printf("Enter email address: ");
scanf("%s", contact.email.email);

// Print the email address


printf("\n Email Address: %s", contact.email.email);

return 0;
}
We have two structures: PhoneNumber and EmailAddress, representing a phone number and an email
address, respectively.
 We define a union named ContactInfo that can hold either a phone number or an email
address.
 In the main function, we declare a variable of type union ContactInfo named contact.
 The user is prompted to input either a phone number or an email address. Depending on the user's
choice, the appropriate structure within the union is populated.
 We then print the entered information based on the type of contact information.
This simple example demonstrates how a union can be used to store different types of data in the same
memory location, providing flexibility based on the program's needs.

Enumerations
48
are user-defined data types that consist of named integral constants. Enums provide a way to create
named constant values, making the code more readable and maintainable. Here's a simple example

#include<stdio.h>
enum week {Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()

enum week day;

day = Wed;

printf("%d",day);

return 0;

tryout
Another example
#include <stdio.h>

// Define an enumeration named 'Days'


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

int main() {
// Declare a variable of type 'enum Days'
enum Days today;

// Assign a value to the 'today' variable


today = Wednesday;

// Switch statement based on the enum value


switch (today) {
case Sunday:
printf("It's a relaxing day!\n");
break;
case Monday:
printf("Start of the workweek.\n");

49
break;
case Wednesday:
printf("Halfway through the week.\n");
break;
default:
printf("Another day.\n");
break;
}

return 0;
}

Typedef
keyword is used to create an alias (a new name) for an existing data type. This allows you to define
custom names for types, making the code more readable and providing a level of abstraction. typedef is
often used to simplify complex type declarations or to create more descriptive names for existing types.
The basic syntax of typedef is as follows:

typedef existing_type new_type_name;


very similar to what we give nick name to our friends
#include <stdio.h>

// Define a new name for the existing data type


typedef int myInteger;
int main() {
// Use the new name to declare variables
myInteger x = 42;

// Print the value


printf("The value of x: %d\n", x);

return 0;
}

50

You might also like