0% found this document useful (0 votes)
30 views96 pages

Structures and Unions New-Merged

Uploaded by

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

Structures and Unions New-Merged

Uploaded by

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

Structures and Unions

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.

Accessing structure members


Write a program to show use of structures in c language
struct student
{
int rollno;
char name[30];
float marks;
};
void main()
{
struct 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);
}

OUTPUT:
Array of Structures

An array whose elements are of type structure is called array of structure. It is


generally useful when we need multiple structure variables in our program.

Need for Array of Structures


Suppose we have 50 students and we need to store the data of 50 students. So for
that, we need to define 50 variables of struct student type and store the data within
that. However, declaring and handling the 50 variables is not an easy task. Let’s
imagine a bigger scenario, like 1000 students.

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

Nested Structure Declaration


A nested structure can be declared by using a structure as a member of another
structure.

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

struct employee e1 = {"Kiran", 25000, {12, 5, 1990}};


printf("Name: %s\n", e1.name);
printf("Salary: %f\n", e1.salary);
printf("Date of Birth: %d-%d-%d \n", e1.d1.d, e1.d1.m, e1.d1.y);

}
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("Enter age: ");


scanf("%d", &ptr->age);

printf("Enter weight: ");


scanf("%f", &ptr->weight);

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.

Types of Files in a C Program


When referring to file handling, we refer to files in the form of data files. Now, these data files
are available in 2 distinct forms in the C language, namely:

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

• Creation of a new file.


• Opening an existing file.
• Reading data from a file.
• Writing data in a file.
• Closing a file.
Steps for Processing a File

• Declare a file pointer variable.


• Open a file using fopen() function.
• Process the file using the suitable function.
• Close the file using fclose() function.

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.

What is a File Pointer in C?

A file pointer is a reference to a particular position in the opened file. It is used


in file handling to perform all file operations such as read, write, close, etc. We use
the FILE macro to declare the file pointer variable. The FILE macro is defined
inside <stdio.h> header file.

Syntax of File Pointer


FILE* pointer_name;

File Pointer is used in almost all the file operations in C.

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

There are many modes for opening a file:


• r - open a file in read mode
• w - opens or create a text file in write mode
• a - opens a file in append mode
• r+ - opens a file in both read and write mode
• a+ - opens a file in both read and write mode
• w+ - opens a file in both read and write 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 ) ;
}

Closing File: fclose()


The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:

Example 1: Program to Create a File, Write in it, And Close the File
#include <stdio.h>
#include <string.h>
int main()
{
FILE* fp;

char data[50] = "Computer Science Portal for C Programming";

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

printf("Data successfully written in file Test.c \n ");


printf("The file is now closed.");
}

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 −

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B%A=0

The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then –

Operator Description Example

== 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 –

Operator Description Example

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

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

! Logical NOT (!a) is false

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 AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

3|P age
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 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

Operator Description Example

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

expression 1 ? expression 2: expression 3


Explanation:

• The question mark "?" in the syntax represents the if part.


• The first expression (expression 1) generally returns either true or false,
based on which it is decided whether (expression 2) will be executed or
(expression 3)
• If (expression 1) returns true then the expression on the left side of " : " i.e
(expression 2) is executed.
• If (expression 1) returns false then the expression on the right side of " : " i.e
(expression 3) is executed
Write a program in C Find number is positive or negative

#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

* Pointer to a variable *x ; will be pointer to a 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.

How to Use Pointers?


The use of pointers in C can be divided into following steps:
1. Pointer Declaration
2. Pointer Initialization

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 = &num;

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 = &num;
Write a program to show the use of pointers
#include <stdio.h>
Void main()
{
int var = 10;

// declare pointer variable


int* ptr;

// note that data type of ptr and var must be same


ptr = &var;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
}

Output:

Value at ptr = 0x7ffca84068dc


Value at var = 10
Value at *ptr = 10

The pointers and the indirection operator

The two fundamental operators used with pointers are:

1. The address of operator (&): it returns the address of a variable. For example:

Int x=10;

Printf(“The value of x=%d”,x);

Printf(“The address of x=%d”,&x);

Output will be:

The value of x=10


The address of x=2002(assumed)

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.

int var = 10;


int* ptr;
ptr = &var;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr); //use of * operator

Pointers and Arrays


1. Pointers and arrays are very closely related to each other.
2. In C, the name of an array designates the starting address or base address of the array.
3. In fact, it is a pointer to first element of an array.
4. Thus array name behaves as a pointer variable.

Pointers and one-dimensional arrays:


#include<stdio.h>
main ( ){
int a[5]={5,10,15,20,25};
int *p,i;
p = &a[0];
printf ("Elements of the array are");
for (i=0; i<5; i++)
printf("%d \t", *(p+i));
}

Pointers and two dimensional arrays

Memory allocation for a two-dimensional array is as follows −

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


a[1] [2] = *(1234 + 1*3+2)
= *(1234 + 3+2)
= *(1234 + 5*4) // 4 is Scale factor
= * (1234+20)
= *(1254)
a[1] [2] = 6

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 −

Elements of 2D array are


123
456
789

What is an Array of Pointers?


Just like an integer array holds a collection of integer variables, an array of
pointers would hold variables of pointer type. It means each variable in an array
of pointers is a pointer that points to another address.

The name of an array can be used as a pointer because it holds the address to
the first element of the array.

Example of Creating an Array of Pointers


The following example demonstrates how you can create and use an array of pointers. Here, we
are declaring three integer variables and to access and use them, we are creating an array of
pointers. With the help of an array of pointers, we are printing the values of the variables.

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

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


{
printf("Value at ptr[%d] = %d\n", i, *ptr[i]);
}

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

Passing 2-D array to a Function


A one dimensional array can be easily passed as a pointer. One important
thing for passing multidimensional arrays is, first array dimension does not
have to be specified. The second (and any subsequent) dimensions must be
given.

#include <stdio.h>
const int M = 3;
const int N = 3;
void display(int arr[M][N]);

void display(int arr[M][N])


{
int i, j;
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
printf("%d ", arr[i][j]);
}

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 is flowchart? Draw a flowchart to find out total number of students in a


class who have scored more than 60%.
2. What are data flow diagrams. Explain with example.
3. What is a constant? Discuss different types of contants used in C language.
4. Discuss the significance of decision table and algorithm development in the
programming process. Write an algorithm for generating Fibonacci series.
5. Write about various operators in C along with their hierarchy.
6. Write about the structure of c program along with a sample code.
7. What are various data types in C language.
8. What are header files? Explain types of header files.
9. What are variables? Write rules for naming variables in C
10. What are identifiers? Give examples.
UNIT-II
1. Discuss various looping statements used in c language with example.
2. Write a program to find the factorial of a number
(with recursion + without recursion)
3. What is recursion? Write a program to print Fibonacci series using recursion.
4. What are different ways to pass parameters to function? Explain with the help of
an example. (V.V.V important)
5. What are functions? How they are used in c language. How library functions are
different from user-defined functions.
6. What is decision/conditional statements? Write examples of each.
7. What is the purpose of switch, break and continue statements in a program?
8. Differentiate between local and global variables.
9. What is the use of goto statement.
10. Explain various storage classes used in C language
UNIT-III

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?

• A data flow diagram (DFD) is a graphical representation


of the movement of data between external entities,
processes and data stores within a system.

• Simply put, DFD’s show how data moves through an


information system.

2
Symbols and Notations Used in DFDs

• Two common systems of symbols are named after their


creators:
– Yourdon and Coad
– Yourdon and DeMarco
– Gane and Sarson

• One main difference in their symbols is that Yourdon-Coad


and Yourdon-DeMarco use circles for processes, while Gane
and Sarson use rectangles with rounded corners,

3
Symbols and Notations Used in DFDs

• External entity: an outside system that sends or receives


data, communicating with the system being diagrammed.
They are the sources and destinations of information
entering or leaving the system
• Process: any process that changes the data, producing an
output. It might perform computations, or sort data based
on logic, or direct the data flow based on business rules. A
short label is used to describe the process, such as “Submit
payment.”

4
Symbols and Notations Used in DFDs

• Data store: files or repositories that hold information for


later use, such as a database table or a membership form.
Each data store receives a simple label, such as “Orders.”

• 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

• Each process should have at least one input and an output.


• Each data store should have at least one data flow in and
one data flow out.
• Data stored in a system must go through a process.
• All processes in a DFD go to another process or a data store.

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.

• It highlights the main functions carried out by the system,


as we break down the high-level process of the Context
Diagram into its subprocesses

10
DFD Level 1

11
DFD Level 2

• It goes one step deeper into parts of Level 1.


• It may require more text to reach the necessary level of
detail about the system’s functioning.

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.

Decision Table Example:


Let’s take an example scenario for an ATM where a decision table would be of use.

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

Advantage of using decision tables:

1.Decision tables make it possible to detect combinations of conditions that


would otherwise not have been found and therefore not tested or developed.

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:

Function Work of Function

strlen() computes string's length

strcpy() copies a string to another

strcat() concatenates(joins) two strings

strcmp() compares two strings

strlwr() converts string to lowercase

strupr() converts string to uppercase


Strings handling functions are defined under string.h header file.

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

strcpy(destination string,source string);


• The strcpy() function copies the string pointed by source (including the
null character) to the destination.
• The strcpy() function also returns the copied string.
Example: C strcpy()
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "C programming";
char str2[20];
// copying str1 to str2
strcpy(str2, str1);
puts(str2); // C programming
return 0;
}
Output
C programming

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(destination string, source string)

strcat() arguments

As you can see, the strcat() function takes two arguments:


destination - destination string
source - source string
The strcat() function concatenates the destination string and
the source string, and the result is stored in the destination string.
Example: C strcat() function
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "This is ", str2[] = "programiz.com";

// concatenates str1 and str2


// the resultant string is stored in str1.
strcat(str1, str2);

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

The function takes two parameters:

• str1 - a string
• str2 - a string

Return Value from strcmp()

Return Value Remarks

0 if strings are equal

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

Example: C strcmp() function


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

int main()
{
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;

// comparing strings str1 and str2


result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);

// comparing strings str1 and str3


result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}

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

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

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


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

string after converting to the uppercase is: COMPUTER SCIENCE PORTAL


6. Strlwr ()
Strupr () function gets a string and turn its every letter to small caps.

#include<stdio.h>
#include<string.h>
int main ()
{
char n [ 30 ] ; // declare a string.

printf ( " Enter a name in upper case \n " ) ;


gets(n);
printf ( " Entered name in lower case %s \n " , strlwr ( n ) ) ;
// strupr () function is called.

return 0 ;
}
Output:
Enter a name in upper case

HELLO

Entered name in lower case


hello
Passing Arguments to Function
A function sometime needs data from calling function to perform its task. It accepts data
from calling function by declare variables that accept the values of the calling functions.
These variables are called the formal parameters of the function.

In C, parameter(arguments) refers to data which is passed to function while calling


function. The formal parameters are similar to local variables inside the function scope
and are created when control enters into the function and gets destroyed upon exit.
A Function in C can be called in two ways.
1. Call by value
2. Call by reference
First of all, we should understand the meaning of actual and formal parameters
Formal parameter
This is the argument which is used inside body of function definition. It's is limited to the scope
of function. It gets created when control enters function and gets destroyed when control exits
from function.
Actual parameter
This is the argument which is used while calling a function.

Call by value

• In call by value method a copy of actual arguments is passed into formal


arguments in the function definition.
• Any change in the formal parameters of the function have no effect on the value
of actual argument.
• Call by value is the default method of passing parameters in C.
• Different memories are allocated for the formal and actual parameters.
C Program to Pass Arguments as Call by Value
#include <stdio.h>
void swap(int , int);
main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);

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

C Program to Pass Arguments as Call by Reference


#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a an
d b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual paramete
rs do change in call by reference, a = 10, b = 20
}
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); // Formal parameters, a = 2
0, b = 10
}

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


• The location where the variable will be stored.
• The initialized value of a variable.
• A lifetime of a variable.

C language uses 4 storage classes, namely:


o Automatic
o External
o Static
o Register

1. Auto storage class:


This is the default storage class for all the variables declared inside a function
or a block. Hence, the keyword auto is rarely used while writing programs in C
language.
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are
defined.

The scope of the automatic variables is limited to the block in which they are
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.

2. Extern Storage class

The extern storage class in C is used to declare a global variable or function in


another file. This allows the variable or function to be shared across multiple files.
Here’s a simple example to illustrate how it works:

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

3. Static Storage class


The static storage class in C is used to declare variables that retain their value even
after the scope in which they were declared has ended. This means that the
variable is initialized only once and exists until the program terminates.
o The variables defined as static specifier can hold their value between the multiple
function calls.
o Static local variables are visible only to the function or the block in which they are
defined.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.
o The keyword used to define static variable is static.

Here’s a simple example to illustrate this:

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

4. Register Storage Class:

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.

There are two types of header files defined in a program:

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"

Some of the header files are given below:

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

How to declare an array?


In C, we have to declare the array like any other variable before using it. We can
declare an array by specifying its name, the type of its elements, and the size of
its dimensions. When we declare an array in C, the compiler allocates the
memory block of the specified size to the array name.
Syntax: dataType arrayName[arraySize];

For example, float mark[5];

Here, we declared an array, mark, of floating-point type. And its size is 5.


Meaning, it can hold 5 floating-point values.
It's important to note that the size and type of an array cannot be changed once it
is declared.

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

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i)
{
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


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

}
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

A Two-Dimensional array or 2D array in C is an array that has exactly two


dimensions. They can be understood in the form of rows and columns
organized in a two-dimensional plane.

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

Another popular form of a multi-dimensional array is Three-Dimensional Arrayor 3D


Array. A 3D array has exactly three dimensions. It can be visualized as a collection
of 2D arrays stacked on top of each other to create the third dimension.

Syntax of 3D Array:

array_name [size1] [size2] [size3];

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

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


}
printf("\n");
}
printf("\n \n");
}
return 0;
}
Passing Arrays to Function
In C, there are various general problems which requires passing more than one variable of the
same type to a function. For example, consider a function which sorts the 10 elements in
ascending order. Such a function requires 10 numbers to be passed as the actual parameters
from the main function. Here, instead of declaring 10 different numbersand then passing into
the function, we can declare and initialize an array and pass that into the function. This will
resolve all the complexity since the function will now work for any number of values.

// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>
float calculateSum(float num[]);
main()
{
float result;
float num[] = {23.4, 55, 22.6, 3, 40.5, 18};
result = calculateSum(num);

printf("Result = %f", result);


}

float calculateSum(float num[])


{
float sum = 0.0;
for (int i = 0; i < 6; ++i)
{
sum += num[i];
}
return sum;
}

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

To declare an array of characters, you use the following syntax:

char arrayName[size];

Example

Here’s a simple example of declaring and using an array of characters in C:

You might also like