Structures and Unions New-Merged
Structures and Unions New-Merged
Structures
• The structure is a user-defined data type that is available in C.
Declaration of structures:
Structure members cannot be initialized like other variables inside the structure definition. Memory is
only allocated when a structure variable is declared.
struct student
{
int rollno;
float marks;
};
void main()
{
Struct student s1;
s1.rollno=134;
s1.marks=88.5;
}
In the above example, the structure variable s1 is modifying the data members of the structure.
s1.rollno=134;
strcpy(s1.name,"Raman");
s1.marks=88.5;
printf("Rollno=%d",s1.rollno);
printf("Name=%s",s1.name);
printf("Marks=%f",s1.marks);
}
OUTPUT:
Array of Structures
#include<stdio.h>
struct student
{
int rollno;
float marks;
};
void main()
{
struct student s1[2];
s1[0].rollno=134;
s1[0].marks=88.5;
s1[1].rollno=135;
s1[1].marks=90.0;
printf("Rollno=%d \n",s1[0].rollno);
printf("Marks=%f \n",s1[0].marks);
printf("Rollno=%d \n",s1[1].rollno);
printf("Marks=%f",s1[1].marks);
}
OUTPUT:
Nested structures
A structure within a structure is known as nested structure in C. When one of the elements
in the definition of a struct type is of another struct type, then we call it a nested
structure in C. Nested structures are defined when one of the elements of a struct type
is itself a composite representation of one or more types.
Syntax
A general syntax of a nested structure is as follows −
struct struct1{
type var1;
type var2;
struct struct2 strvar;
}
Example
#include <stdio.h>
#include <string.h>
struct employee
{
char name[10];
float salary;
struct dob
{
int d, m, y;
} d1;
};
void main()
{
}
Structure with pointers
A structure pointer is defined as the pointer which points to the address of the memory
block that stores a structure known as the structure pointer. The structure pointer tells
the address of a structure in memory by pointing the variable to the structure variable.
#include<stdio.h>
struct person
{
int age;
float weight;
};
void main()
{
struct person *ptr, person1;
ptr = &person1;
printf("Displaying:\n");
printf("Age: %d\n", ptr->age);
printf("weight: %f", ptr->weight);
}
Unions
A union is a special data type available in C that allows to store different data types
in the same memory location. You can define a union with many members, but only
one member can contain a value at any given time. Unions provide an efficient way of
using the same memory location for multiple-purpose.
Memory representation of structures and unions:
Example:
Write a program to show use of unions in c language
union student
{
int rollno;
char name[30];
float marks;
};
void main()
{
union student s1;
s1.rollno=134;
strcpy(s1.name,"Raman");
s1.marks=88.5;
printf("Rollno=%d",s1.rollno);
printf("Name=%s",s1.name);
printf("Marks=%f",s1.marks);
}
File Handling in C
What is File Handling?
File handing in C is the process in which we create, open, read, write, and close
operations on a file. File handling refers to the method of storing data in the C program in the
form of an output or input that might have been generated while running a C program in a data file.
What is a File in C?
A file refers to a source in which a program stores the information/data in the form of bytes of
sequence on a disk (permanently). The content available on a file isn’t volatile like the
compiler memory in C. But the program can perform various operations, such as creating,
opening, reading a file, or even manipulating the data present inside the file. This process is
known as file handling in C.
File is a structure defined in ‘stdio.h’ to handle file operations. Various operations like
opening the file reading/writing in a file and closing the file can be done.
• Text Files
• Binary Files
Text Files
The text files are the most basic/simplest types of files that a user can create in a C program.
We create the text files using an extension .txt with the help of a simple text editor.
Binary Files
The binary files store info and data in the binary format of 0’s and 1’s (the binary number
system). Thus, the files occupy comparatively lesser space in the storage.
C File Operations
Five significant operations can be performed on files:
To handle files in C, file input/output functions available in the stdio library are:
Function Uses/Purpose
fopen Opens a file.
fclose Closes a file.
getc Reads a character from a file.
putc Writes a character to a file.
getw Read integer.
putw Write an integer.
fprintf Prints formatted output to a file.
fscanf Reads formatted input from a file.
fgets Read a string of characters from a file.
fputs Write a string of characters to a file.
feof Detects end-of-file marker in a file.
Opening a file
The fopen() function is used to create a file or open an existing
file:
fp = fopen(const char filename,const char mode);
Program to open a file, read content of the file and display on the screen
#include<stdio.h>
void main( )
{
FILE *fp;
char ch;
fp=fopen("file_handle.txt","r");
if(fp= NULL)
{
printf(“Unable to open file”);
exit(1);
}
while ( 1 )
{
ch=fgetc(fp);
if(ch==EOF)
break;
printf("%c",ch);
}
fclose (fp ) ;
}
Example 1: Program to Create a File, Write in it, And Close the File
#include <stdio.h>
#include <string.h>
int main()
{
FILE* fp;
fp = fopen(“Test.c", "w");
if (fp == NULL)
{
printf("Test.c file failed to open.");
}
else
{
printf("The file is now opened.\n");
if(strlen(data) > 0)
{
fputs(data, fp);
fputs("\n", fp);
}
fclose(fp);
return 0;
}
An operator is a symbol that tells the compiler to perform a certain mathematical or
logical manipulation. Operators are used in programs to manipulate data and
variables.
Operators
Ternary or Conditional
Unary Operators Binary Operators Operators
?:
Arithmetic Operators
++ increment
+, -, *, /, %
-- Decrement
- Unary minus
Relational Operators
Special * dereferencing ==, !=, >, <, >=, <=
Operator & addressof
sizeof operator Logical Operators
&&, ||, !
Assignment Operators
=, +=, -=, *=, /=, %=
Bitwise Operators
<<, >>, &, ^, |
C operators can be classified into following types:
• Arithmetic operators
• Relational operators
• Logical operators
• Bitwise operators
• Assignment operators
• Conditional operators
• Special operators
1|P age
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then –
== Checks if the values of two operands are equal or not. If yes, (A == B) is not
then the condition becomes true. true.
!= Checks if the values of two operands are equal or not. If the (A != B) is true.
values are not equal, then the condition becomes true.
> Checks if the value of left operand is greater than the value of (A > B) is not true.
right operand. If yes, then the condition becomes true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand. If yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is not
the value of right operand. If yes, then the condition becomes true.
true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand. If yes, then the condition becomes
true.
2|P age
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then –
|| Logical OR (a || b) is true
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(These are datatypes, we will learn about them in the next tutorial).
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
3|P age
Now lets see truth table for bitwise &, | and ^
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operator, 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 have
to be shifted. Both operands have the same precedence.
Example
a = 0001000
b=2
a << b = 0100000
a >> b = 0000010
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to left a+=b is same as
a=a+b
-= subtracts right operand from the left operand and assign the result to a-=b is same as a=a-b
left operand
4|P age
*= mutiply left operand with the right operand and assign the result to left a*=b is same as
operand a=a*b
/= divides left operand with the right operand and assign the result to left a/=b is same as a=a/b
operand
%= calculate modulus using two operands and assign the result to left a%=b is same as
operand a=a%b
It is actually the if condition that we use in C language decision making, but using
conditional operator, we turn the if condition statement into a short and simple
operator.
The syntax of a conditional operator is :
#include<stdio.h>
void main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
(num>=0)?printf("Positive."):printf("Negative");
Output:
Enter a number: 8
Positive.
5|P age
Unary Operators
Unary operators are the operators that perform operations on a single operand
to produce a new value.
1. Unary minus (–)
2. Increment (++)
3. Decrement (--)
6|P age
7|P age
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|P age
9|P age
Type Casting (V. Important)
Type casting in C is the process of converting a variable from one data type to another.
This is often necessary in programming to ensure that operations are performed correctly,
especially in a strongly typed language like C. Typecasting is performed by using the cast
operator. If it makes sense, the compiler will automatically change one data type into another.
For example, if you assign an integer value to a floating-point variable, the compiler will
convert the int to float. Type conversion in c can be classified into the following two types:
10 | P a g
e
11 | P a g
e
Pointers: Pointer declaration, Address operator “&”, Indirection operator “*”, Pointer and arrays,
Pointers and 2-Dimensional Arrays, Pointer to an Array, Passing 2-D array to a Function, Array of
Pointers.
Pointers
In C, a pointer is a variable that stores the memory address of another variable.
Pointers are variables that store the address of another variable, rather than storing a
value like an integer, double, or character.
Advantages of pointers:
1. Sometimes it is more convenient or flexible to work with the address of a variable than
the actual variable.
2. The program execution becomes faster with the help of pointers.
3. Using a pointer, your program can access any memory location in the computer’s
memory.
4. Using pointers, arrays and structures can be handled in an efficient way.
5. It will become impossible to create complex data structures without pointers.
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To
declare a pointer, we use the ( * ) dereference operator before its name.
Example
int *ptr;
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the
pointer variable. We generally use the (&) addressof operator to get the
memory address of a variable and then store it in the pointer variable.
Example
int num = 10;
int * ptr;
ptr = #
We can also declare and initialize the pointer in a single step. This method is
called pointer definition as the pointer is declared and initialized at the
same time.
Example
int *ptr = #
Write a program to show the use of pointers
#include <stdio.h>
Void main()
{
int var = 10;
Output:
1. The address of operator (&): it returns the address of a variable. For example:
Int x=10;
2. The indirection operator or value at address operator (*): This operator returns the value of
the variable that the pointer is pointing to. The ‘*’ is an indirection operator or value at address
operator. In simple words, we can say that if address of a variable is known then the ‘*’ operator
is used to access the contents of the variable.
Example
Following is the C program for pointers and two-dimensional array −
#include<stdio.h>
main ( ){
int a[3] [3]={1,2,3,4,5,6,7,8,9}
int i,j;
int *p;
p = &a[0] [0];
printf ("elements of 2d array are");
for (i=0; i<3; i++){
for (j=0; j<3; j++){
printf ("%d \t", *(p+i*3+j));
}
printf ("
");
}
getch ( );
}
Output
When the above program is executed, it produces the following result −
The name of an array can be used as a pointer because it holds the address to
the first element of the array.
#include <stdio.h>
int main()
{
int var1 = 1;
int var2 = 2;
int var3 = 3;
int *ptr[3];
ptr[0] = &var1;
ptr[1] = &var2;
ptr[2] = &var3;
return 0;
}
Output
When the above code is compiled and executed, it produces the following result
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
#include <stdio.h>
const int M = 3;
const int N = 3;
void display(int arr[M][N]);
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
display(arr);
return 0;
}
Output
1 2 3 4 5 6 7 8 9
Unit-I
1. What are arrays? How do you use 1-D and 2-D arrays? write a C program to sort
an array of numbers.
2. How are 2-D arrays passed to a function?
3. How to declare a pointer variable? How do you access values using pointers.
4. How pointers are used with 2-D arrays. Write a program to print all elements of a
2-D array using pointers.
5. Explain the concept of array of characters with an application. Write a program in
C to search for an element in an array using linear search.
6. What is binary search? Explain with an example
7. Write a program to find greatest element in each of an two-dimensional array.
UNIT-IV
1. What is file handling? How to create, open and close a file in a C program?
Explain various file opening modes. Discuss various functions used to write in a
file.
2. What is a string variable? How do you declare and initialize a string variable?
Explain various string handling functions in detail.
3. How do you define and declare a structure in a C program? What are nested
structures.
4. How structures are different from unions?
5. Write a program to copy a string from one character to another without using any
built-in string functions.
Data Flow Diagrams
1
What is a Data Flow Diagram?
2
Symbols and Notations Used in DFDs
3
Symbols and Notations Used in DFDs
4
Symbols and Notations Used in DFDs
• Data flow: the route that data takes between the external
entities, processes and data stores. It portrays the interface
between the other components and is shown with arrows,
typically labeled with a short data name, like “Billing
details.”
5
Symbols and Notations Used in DFDs
6
DFD rules
7
DFD levels and layers
• A data flow diagram can be represented into progressively
more detail by using levels and layers, zeroing in on a
particular piece.
• DFD levels are numbered 0, 1 or 2, and occasionally go to
even Level 3 or beyond.
• The necessary level of detail depends on the scope of what
you are trying to accomplish.
8
DFD Level 0-Context Diagram.
• basic overview of the whole system or process being
analyzed or modeled.
• It’s designed to be an at-a-glance view, showing the
system as a single high-level process, with its relationship
to external entities.
• Its used by a wide audience, including stakeholders,
business analysts, data analysts and developers to
understand the system.
9
DFD Level 1
• It provides a more detailed breakout of pieces of the
Context Level Diagram.
10
DFD Level 1
11
DFD Level 2
12
DFD Level 2
13
Example"Food Ordering System"
It also shows the participants who will interact with the system,
called the external entities. ( the Supplier, Kitchen, Manager,
and Customer)
• In between the process and the external entities, there is
data flow (connectors) that indicate the existence of
information exchange between the entities and the system.
14
Level 1 DFD
15
Decision Tables
A Decision Table is a table that shows the relationship between inputs and
rules, cases, and test conditions. It's a very useful tool for
complicated software. The decision table allows the programmers to
examine all possible combinations of requirements and to immediately
discover any circumstances that were overlooked. True(T) and False(F)
values are used to signify the criteria.
A customer requests a cash withdrawal. One of the business rules for the ATM is that
the ATM machine pays out the amount if the customer has sufficient funds in their
account or if the customer has the credit granted. Already, this simple example of a
business rule is quite complicated to describe in text. A decision table makes the same
requirements clearer to understand:
In this decision table, R1,R2 and R3 are the rules and T and F are used as True and
False values according to application of
In a decision table, conditions are usually expressed as true (T) or false (F). Each
column in the table corresponds to a rule in the business logic that describes the unique
combination of circumstances that will result in the actions. The table above contains
three different business rules, and one of them is the “withdrawal is granted if the
requested amount is covered by the balance.”
2. The requirements become much clearer and you often realize that some
requirements are illogical and can skip those requirements.
Decision Tree
Example: Suppose there is a candidate who has a job offer and wants to decide whether
he should accept the offer or Not. So, to solve this problem, the decision tree starts with
the root node (Salary attribute by ASM). The root node splits further into the next decision
node (distance from the office) and one leaf node based on the corresponding labels. The
next decision node further gets split into one decision node (Cab facility) and one leaf
node. Finally, the decision node splits into two leaf nodes (Accepted offers and Declined
offer). Consider the below diagram:
String Handling
String Manipulations using String functions
You need to often manipulate strings according to the need of a problem.
To solve this, C supports a large number of string handling functions in
the standard library string.h
Few commonly used string handling functions are discussed below:
#include <string.h>
Note: You have to include the code below to run string handling functions.
gets() and puts()
Functions gets() and puts() are two string functions to take string input from
the user and display it respectively.
#include<stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
1. strlen()
The strlen() function takes a string as an argument and returns its length. The
returned value is of type size_t (an unsigned integer type).
It is defined in the <string.h> header file.
#include <stdio.h>
#include <string.h>
int main()
{
char string1[20] = "ScalerAcademy";
printf("Length of string string1: %ld", strlen(string1));
return 0;
}
Output
Length of string string1: 13
Note that the strlen() function doesn't count the null character \0 while
calculating the length.
2. strcpy()
The function prototype of strcpy() is:
Note: When you use strcpy() , the size of the destination string should be large
enough to store the copied string. Otherwise, it may result in undefined
behavior.
3. strcat()
The function definition of strcat() is:
strcat() arguments
puts(str1);
puts(str2);
return 0;
}
Output
This is programiz.com
programiz.com
Note: When we use strcat() , the size of the destination string should be
large enough to store the resultant string. If not, we will get the
segmentation fault error.
4. strcmp()
The strcmp() compares two strings character by character. If the strings are
equal, the function returns 0.
The function prototype of strcmp() is:
strcmp (str1,str2)
strcmp() Parameters
• str1 - a string
• str2 - a string
>0 if the first non-matching character in str1 is greater (in ASCII) than that of str2 .
<0 if the first non-matching character in str1 is lower (in ASCII) than that of str2 .
int main()
{
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
Output
strcmp(str1, str2) = 1
strcmp(str1, str3) = 0
In the program,
• strings str1 and str2 are not equal. Hence, the result is a non-zero
integer.
• strings str1 and str3 are equal. Hence, the result is 0.
•
5. strupr()
The strupr( ) function is used to converts a given string to uppercase.
Syntax:
strupr(str);
Parameter:
• str: This represents the given string which we want to convert into
uppercase.
#include<stdio.h>
#include <string.h>
int main()
{
char str[] = "CompuTer ScienCe PoRTAl";
#include<stdio.h>
#include<string.h>
int main ()
{
char n [ 30 ] ; // declare a string.
return 0 ;
}
Output:
Enter a name in upper case
HELLO
Call by value
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
}
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
Call by reference
• In call by reference method the address of the variable is passed to the formal
arguments of a function.
• Any change in the formal parameters of the function will effect the value of
actual argument.
• Same memory location is accessed by the formal and actual parameters.
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
Storage Classes in C
C Storage Classes are used to describe the features of a variable/function. These
features basically include the scope, visibility, and lifetime which help us to trace the
existence of a particular variable during the runtime of a program.
A storage class in C is used to describe the following things:
The scope of the automatic variables is limited to the block in which they are
defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the
block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
For Example:
File 1: main.c
#include <stdio.h>
// Declare the external variable
extern int count;
void main()
{
count = 5;
printf("Count in main: %d\n", count);
}
File 2: support.c
#include <stdio.h>
// Define the external variable
int count;
void display()
{
printf("Count in support: %d\n", count);
}
In this example:
• The extern keyword in main.c tells the compiler that the variable count is defined in
another file.
• The actual definition of count is in support.c.
• This allows count to be shared and modified across both files.
When you compile these files together, the count variable will be accessible in
both main.c and support.c
#include <stdio.h>
void staticExample()
{
static int count = 0; // static variable
count++;
printf("Count is %d\n", count);
}
int main()
{
staticExample();
staticExample();
staticExample();
return 0;
}
In this example:
• The count variable is declared as static inside the staticExample function.
• Each time staticExample is called, count retains its value from the previous call.
• The output of this program will be:
• Count is 1
• Count is 2
• Count is 3
This demonstrates how the static storage class allows the variable to maintain its state
between function calls.
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU
register. However, it is compiler’s choice whether or not, the variables can be
stored in the register.
o We can store pointers into the register, i.e., a register can store the address of a
variable.
o Static variables can not be stored into the register since we can not use more than
one storage specifier for the same variable.
Output
0
What is a header file?
A header file is a source file that has the .h extension. Header files contain the function
prototypes or function declaration. Whenever we require the definition of a function, then
we simply include that header file in which function is declared.
o System defined header file: The header file which is predefined is known as a
system defined header file.
o User-defined header file: The header file which is defined by the user is known as
a user-defined header file.
Both the user-defined and system-defined header file can be included in a program with
the help of using preprocessing directive (#). These preprocessor directives are used to
instruct the compiler to process these files before compilation. There are two forms of
including header file:
o #include<file>
o #include "file"
o #include<stdio.h>: It is used for performing input and output operations with the
help of using printf() and scanf() function.
o #include<string.h>: It is used for performing string related functionalities like
strlen(), strcmp(), etc.
o #include<iostream>: It is used to perform input and output operations with the
help of using cin and cout objects.
o #include<math.h>: This header file contains some predefined math functions that
perform mathematical operations, such as sqrt(), log2(), pow(), etc.
What is Array in C?
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value
An array is a variable that can store multiple values. For example, if you want
to store 100 integers, you can create an array for it.
int data[100];
Example:
###include<stdio.h>
void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d \t",arr[i]);
}
}
Types of Array in C
There are two types of arrays based on the number of dimensions it has. They
are as follows:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays
1. One Dimensional Array in C
The One-dimensional arrays, also known as 1-D arrays in C are those arrays
that have only one dimension.
Syntax of 1D Array in C
array_name [size];
Example:
#include <stdio.h>
main()
{
int values[5];
}
2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one
dimension. Some of the popular multidimensional arrays are 2D arrays and 3D
arrays.
A. Two-Dimensional Array
B. Three-Dimensional Array
A. Two-Dimensional Array
Syntax of 2D Array in C:
array_name[size1] [size2];
Here,
• size1: Size of the first dimension.
• size2: Size of the second dimension.
Example of 2D Array in C
// C Program to illustrate 2d array
#include <stdio.h>
main()
{
// declaring and initializing 2d array
int arr[2][3] = { 10, 20, 30, 40, 50, 60 };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
Output
10 20 30
40 50 60
B. Three-Dimensional Array in C
Syntax of 3D Array:
#include <stdio.h>
main()
{
// 3D array declaration
int arr[2][2][2] = { 10, 20, 30, 40, 50, 60, 70, 80};
// printing elements
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
#include <stdio.h>
float calculateSum(float num[]);
main()
{
float result;
float num[] = {23.4, 55, 22.6, 3, 40.5, 18};
result = calculateSum(num);
Output
Result = 162.50
Array of Characters
An array of characters in C is used to store a sequence of characters, such as a string. It is
essentially a collection of char data types.
Syntax
char arrayName[size];
Example