Unit 1 2 3
Unit 1 2 3
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
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.
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.).
3
default goto sizeof void
do If static while
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 ..
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
% remainder of division
Relation operators
The following table shows all relation operators supported by C.
Operator Description
> Check if operand on the left is greater than operand on the right
Logical operators
C language supports following 3 logical operators. Suppose a=1 and b=0,
Operator Description Example
|| Logical OR (a || b) is true
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
6
| Bitwise OR
^ Bitwise exclusive OR
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
+= 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
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.
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
int main()
{
char ch;
printf("Enter a character :");
ch=getch();
printf("\nEntered character is : %c",ch);
10
return 0;
}
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.
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;
}
Example Example
//Looking at the maximum example
main()
{
int a , b;
a = 10;
printf( "Value of b is %d\n", (a == 1) ? 20: 30 );
Value of b is 30
Value of b is 20
13
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]
[default : statements4;]
}
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;
}
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
Example
void main(){
printf(“Hello ”);
goto l;
printf(“World”);
l:printf(“Program over”)
1. Outer_loop
2. {
3. Inner_loop
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Another Example
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. }
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
Fig above is two dimensional array. A two dimensional array has multiple rows and columns
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
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.
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.
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
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
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");
// 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};
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.
#include <stdio.h>
int main() {
const int size = 5;
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() {
printArray(myArray, size);
return 0;
printf("\n");
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}
};
return 0;
}
27
}
int myArray[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
return 0;
}
28
Unit 3(Pointers)
In computer programming, a pointer is a variable that stores the memory address of another variable.
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:
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.
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:
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 thirdElement = *(p + 2); // Accessing the 3rd element using pointer arithmetic
Pointers are crucial for dynamic memory allocation using functions like malloc, calloc, and
realloc. For example:
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
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>
*ptr = 20;
int main() {
modifyValue(&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:
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() {
int *ptrArray[3];
// Individual integers
ptrArray[0] = &num1;
ptrArray[1] = &num2;
ptrArray[2] = &num3;
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.
#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);
}
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>
int main() {
// Pass the 'add' function as an argument to 'operate'
operate(5, 3, add);
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.
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;
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.
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
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.
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.
memory can't be increased while executing memory can be increased while executing
program. program.
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() function in C
ptr=(cast-type*)malloc(byte-size)
// For Theory example program are not very imp , but definition of Calloc and maloc is very imp
#include <stdio.h>
#include <stdlib.h>
void main(){
38
int n,i,*ptr,sum=0;
scanf("%d",&n);
if(ptr==NULL)
exit(0);
for(i=0;i<n;++i)
free(ptr);
Output:
10
10
Sum=30
calloc() function in C
ptr=(cast-type*)calloc(number, byte-size)
#include <stdlib.h>
void main(){
int n,i,*ptr,sum=0;
scanf("%d",&n);
if(ptr==NULL)
exit(0);
for(i=0;i<n;++i)
scanf("%d",ptr+i);
sum+=*(ptr+i);
printf("Sum=%d",sum);
free(ptr);
Output:
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.
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.
free(ptr)
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>
struct Person {
char name[50];
int age;
float height;
};
int main() {
scanf("%s", person1.name);
scanf("%d", &person1.age);
scanf("%f", &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() {
scanf("%s", people[i].name);
scanf("%d", &people[i].age);
scanf("%f", &people[i].height);
printf("Person's Information:\n");
printf("\n");
return 0; }
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>
int main() {
// Declare a variable of type 'struct Person' and initialize it
struct Person person1 = {"John Doe", 25, 175.5};
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.
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
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>
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];
};
int main() {
// Declare a variable of type 'union ContactInfo'
union ContactInfo contact;
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()
day = Wed;
printf("%d",day);
return 0;
tryout
Another example
#include <stdio.h>
int main() {
// Declare a variable of type 'enum Days'
enum Days today;
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:
return 0;
}
50