0% found this document useful (0 votes)
13 views29 pages

FPL Lab Manual For B

Ehdhfbbffjf Gkkgmg G G G Hh H H H H G G G F F H F ICICI Kuch kho Tshich Tshich ICICI

Uploaded by

vjaythombre
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)
13 views29 pages

FPL Lab Manual For B

Ehdhfbbffjf Gkkgmg G G G Hh H H H H G G G F F H F ICICI Kuch kho Tshich Tshich ICICI

Uploaded by

vjaythombre
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/ 29

K J’s Educational Institute

K J College of Engineering & Management Research

Department of Engineering Sciences

Certificate
This is to certify that,
Mr. /Ms.
of F.E. Division Roll No.
has completed all the practical work and assignments in
the subject Fundamentals of Programming Languages
satisfactorily in the department of Engineering Sciences as
prescribed by Savitribai Phule Pune University, in the
academic year 2024 - 2025.

Faculty-in-charge Head of Department Principal

Date: / / .
INDEX
Subject: Fundamentals of Programming Languages
Name: __________________________________ Roll No: ____________
Class: _____________

Sr. Title of Experiment Date Page Remark Sign


No No.
1. To accept an object mass in kilograms
and velocity in meters per second and
display its momentum. Momentum is
calculated as e=m*c*c where m is the
mass of the object and c is its velocity.
2. Write a C program for employee salary
calculation given, Basic, H.R.A. 20 %
of Basic and D.A. 150 % of Basic
3. To accept a student's marks for five
subjects, compute his/her result.
Student is passing if he/she scores
marks equal to and above 40 in each
course. If student scores aggregate
greater than 75%, then the grade is
distinguished. If aggregate is 60>= and
<75 then the Grade of first division. If
aggregate is 50>= and <60 then the
grade is second division. If aggregate is
40>= and <50 then the grade is third
division.
4. To accept from the user the number of
Fibonacci numbers to be generated and
print the Fibonacci series.
5. To accept the number and Compute 1.
square root of number, 2. Square of
number, 3. Check for prime 4. Factorial
of number. 5. Prime factor.
6. In array do the following: 1. Find given
element 2. Find Max 3. Find min 4. Find
frequency of given element in array 5.
Find Average of elements in Array.
7. Write a C program that accepts a string
from the user and performs the following
string operations- i. Calculate length of
string ii. String reversal iii. Equality
check of two Strings iv. Check
palindrome v. Check substring
8. Create Structure EMPLOYEE for storing
details (Name, Designation, gender, Date
of Joining and Salary) and store the data
and update the data structure
Assignment No. 1
Title: To accept an object mass in kilograms and velocity in meters per second and
display its Momentum. Momentum is calculated as 𝑒 = 𝑚𝑐 2 where m is the mass of the
object and c is its velocity.

Date of
Completion

Remark

Sign. of Staff

Problem Statement:
To accept an object mass in kilograms and velocity in meters per second and display it’s Momentum.
Momentum is calculated as 𝒆 = 𝒎𝒄𝟐 where m is the mass of the object and c is its velocity.

Objective:
1. To design basics of c programming.
2. To study variable declaration.
3. To accept and display input and output values.

Outcomes:

After this experiment, students will acquire knowledge about designing c program structure and
variable declaration.
Aim:

(A) Study of basics of c program structure.

(c) Accepting and displaying input and output values.

(d) Understand variable declaration.


H/W & S/W Requirements:
Linux Operating System with GCC / TURBO C in WINDOWS OS

Theory:
Structure of C program :
C program is a collection of several instructions where each instruction is written as a separate
statement. The C program starts with a main function followed by the opening braces which
indicates the start of the function. Then follows the variable and constant declarations which are
followed by the statements that include input and output statements.
C program may contain one or more sections as shown below:
Documentation Section
Link Section Definition Section
Global Declaration Section
main() Function section
{
Declaration part ;
Executable part;
}
Subprogram Section
User defined functions

Declaration of variable:

Variables are the basic unit of storage in a programming language. These variables consist of a data
type, the variable name, and the value to be assigned to the variable. Unless and until the variables are
declared and initialized, they cannot be used in the program.
Basic Syntax:

The basic form of declaring and initialize a variable is:

data_type variable_name = value;

where,

type = Data type of the variable


identifier = Variable name

value = Data to be stored in the variable (Optional field)

Note 1: The Data type and the Value used to store in the Variable must match.

Note 2: All declaration statements must end with a semi-colon (;)

Example :

int a, b, c; // declare 3 variables.

int z = 35; // declare and initialize variable z with value 35.

double pi = 3.14159; // declare an approximation of pi.

char str[30]; // declare an array named ‘str’ which holds 30 characters.

Keywords:

C has 32 keywords (reserved words with special meaning:

1. auto, 2. break, 3. case, 4. char, 5. const, 6. continue, 7. default, 8. do, 9. double, 10. else, 11.
enum, 12. extern, 13. float, 14. for, 15. goto, 16. if, 17. int, 18. long, 19. register, 20. return,
21. short, 22. signed, 23. sizeof, 24. static, 25. struct, 26. switch, 27. typedef, 28. union, 29.
unsigned, 30. void, 31. volatile, and 32. while.

C Input & Output:


In C programming, printf() is one of the main output function. The function sends formatted output
to the screen. In C programming, scanf() is one of the commonly used function to take input from the
user. The scanf() function reads formatted input from the standard input such as keyboards.
Sample Example:

#include <stdio.h>
int main()
{
int num1;
printf("Hello World\n");
printf("Enter any number: ");
scanf("%d", &num1);
printf("Number=%d",num1);
return 0;
}

Output:

Hello World
Enter any number: 500
Number=500

=== Code Execution Successful ===

The e = m𝑐 2 is equation from Einstein's theory of relativity, which calculates energy.

 e is the energy of the object,


 m is the mass of the object,
 c is the speed of light in a vacuum (approximately 3×1083 \times 10^83×108 meters per
second).

However, for calculating momentum, the formula you should use is:

p=mv

Where:

 p is the momentum of the object,


 m is the mass of the object (in kilograms),
 v is the velocity of the object (in meters per second).

Conclusion:
Thus, we have successfully calculated momentum using basics of C programming.
Assignment No. 2
Title:
Write a C program for employee salary calculation given, Basic, H.R.A. 20 % of
Basic and D.A. 150 % of Basic.
Date of
Completion

Remark
Sign. of Staff

Problem Statement:
To calculate salary of an employee given his basic pay (take as input from user). Calculate salary
of employee. Let HRA be 20 % of basic pay and DA be 150% of basic.

Objective:

1. To use arithmetic operators and expression


2. To study precedence of operators

Outcomes:
After this experiment, students will get knowledge of arithmetic operators, expression their
precedence.

Aim:
(A) Operators and expression in C.
(B) Precedence of operator
(D) Calculate salary of employee

Hardware & Software Requirement:


Linux Operating System with GCC / TURBO C in WINDOWS OS

Theory:
This assignment will read Basic Salary of an employee, calculate other part of the salary on percent
basic and finally print the Salary of the employee. Here, we are reading basic salary of the employee, and
calculating HRA, DA, salary of the employee.

Operators
C supports a rich set of operators, which are symbols used within an expression to specify the manipulations
to be performed while evaluating that expression.
C has the following arithmetic operators:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Operator Precedence in C
The C compiler evaluates its value based on the operator precedence and associativity of operators. The
precedence of operators determines the order in which they are evaluated in an expression. Operators with
higher precedence are evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right


Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


above table lists the order of precedence of operators in C. Here, operators with the highest precedence
appear at the top of the table, and those with the lowest appear at the bottom.

C Expressions:
An expression is a formula in which operands are linked to each other by the use of operators to compute a
value. An operand can be a function reference, a variable, an array element or a constant.
e.g a-b
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
There are four types of expressions exist in C:
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions

Salary Calculation Details:

Sample Example:

Basic Pay:10000

Let HRA be 20% of Basic pay

Therefore HRA= 10,000* 20/100 = 2000

Let DA be 150% of basic pay

Therefore DA= 10,000 *150/100 =

Gross salary = Basic pay + HRA + DA


=10000+2000+15000
=27000

Conclusion:
Thus, we have successfully calculated the gross salary of an employee in C using concept of operator.
Assignment No. 3
Title: To accept a student's marks for five subjects, compute his/her result. Student is passing if he/she
scores marks equal to and above 40 in each course. If student scores aggregate greater than 75%, then
the grade is distinguished. If aggregate is 60>= and <75 then the Grade of first division. If aggregate is
50>= and <60 then the grade is second division. If aggregate is 40>= and <50 then the grade is third
division.
Date of
Completion

Remark
Sign. of Staff

Problem Statement:
To accept a student's marks for five subjects, compute his/her result. Student is passing if he/she scores
marks equal to and above 40 in each course. If student scores aggregate greater than 75%, then the grade is
distinguished. If aggregate is 60>= and <75 then the Grade of first division. If aggregate is 50>= and <60 then
the grade is second division. If aggregate is 40>= and <50 then the grade is third division.

Objective:
1. To study Decision Control Statements
2. To understand and apply if-else statement.

Outcomes:
After this experiment, students will acquire knowledge of decision control structures in C and its
application.

Aim:
(A) Study of flow control statement.
(B) Declaration of if-else.
(C) Study of if-else-if.
(D) Display grade of student.

Hardware & Software Requirement:


Linux Operating System with GCC / TURBO C in Windows OS.

Theory:
The if-else statement in C is a flow control statement used for decision-making in the C program. It is
one of the core concepts of C programming. It is an extension of the if in C that includes an else block along
with the already existing if block.

if Statement:
The if statement in C is used to execute a block of code based on a specified condition.
The syntax of the if statement in C is:
if (condition) {
// code to be executed if the condition is true
}
The if statement evaluates the test expression inside the parenthesis ().
 If the test expression is evaluated to true, statements inside the body of if are executed.
 If the test expression is evaluated to false, statements inside the body of if are not executed.

if-else Statement:
The if-else statement is a decision-making statement that is used to decide whether the part of the code
will be executed or not based on the specified condition (test expression). If the given condition is true, then
the code inside the if block is executed, otherwise the code inside the else block is executed.

Syntax of if-else:
if (condition) {
// code executed when the condition is true
}
else {
// code executed when the condition is false
}
If the test expression is evaluated to true,
 statements inside the body of if are executed.
 statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,
 statements inside the body of else are executed
 statements inside the body of if are skipped from execution.

if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple options. The C if statements
are executed from the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is
true, then the final else statement will be executed. if-else-if ladder is similar to the switch statement.
Syntax of if-else-if Ladder
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Flowchart of if-else-if Ladder

Conclusion:
Thus, we have successfully computed the marks and display its grade using decision control statement.
Assignment No. 4
Title: To accept from the user the number of Fibonacci numbers to be generated and print
the Fibonacci series.

Date of
Completion

Remark

Sign. of Staff

Problem Statement:

To accept from the user the number of Fibonacci numbers to be generated and print the Fibonacci
series.

Objective:

1. To apply control flow statements

Outcomes:

After this experiment, students will acquire knowledge of control flow structures in C and its
application.

Aim:

(A) Use of decision making and looping in c.

(B) Understand and calculate Fibonacci series

H/W & S/W Requirements:


Linux Operating System with GCC / TURBO C in Windows OS.

Theory:
For loop:
The for loop in C Language provides a functionality/feature to repeat a set of statements a
defined number of times. The for loop is in itself a form of an entry-controlled loop.
for (Initialization; Condition; Increment / decrement) {
// code block to be executed
}

Initialization- The loop begins with the initialization of the control variable. This refers to the
initial value taken by the variable.

Condition- Next to checks the looping condition given the initial value expression.

If the condition returns false, the for loop gets terminated.

If the condition returns true, the piece of code inside the body gets executed.

Increment / decrement- After the successful execution of code statements/ code blocks inside
the body of the loop, the loop variable is incremented or decremented. In other words, the value
of the variable is changed in other ways depending on the operation.

While loop:

The while Loop is an entry controlled loop in C programming language. This loop can be used
to iterate a part of code while the given condition remains true.
Syntax
The while loop syntax is as follows:

while (test condition)


{
// body consisting of multiple statements
}

Fibonacci Series :

Fibonacci numbers in the following integer sequence, called the Fibonacci sequence:
0,1,1,2,3,5,8,13,21,34,55,89,144…..

The first two numbers in the Fibonacci sequence are 0 and 1 and each subsequent number is the
sum of the previous two.

Sample Example-

 Base Cases:
 F(0) = 0
 F(1) = 1
2. Recursive Relation:

 F(n) = F(n-1) + F(n-2) for n > 1


This recursive definition tells us that each Fibonacci number (except for the first two) is the
sum of the two preceding Fibonacci numbers. This is the essence of the Fibonacci sequence
and is the foundation for generating it computationally.

Example: Let's calculate the Fibonacci series using the recursive definition:

 F(0) = 0 (Base Case)


 F(1) = 1 (Base Case)
 F(2) = F(1) + F(0) = 1 + 0 = 1
 F(3) = F(2) + F(1) = 1 + 1 = 2
 F(4) = F(3) + F(2) = 2 + 1 = 3
 F(5) = F(4) + F(3) = 3 + 2 = 5
 And so on...

Conclusion:

Thus, we have successfully generated Fibonacci series in c programming using control flow
statements.
Assignment No. 5
Title: To accept the number and Compute 1. square root of number, 2. Square of number,
3. Check for prime 4. Factorial of number. 5. Prime factor.

Date of
Completion

Remark

Sign. of Staff

Problem Statement:
To accept the number and Compute 1. Square root of number 2. Square of number 3. Check for prime
4. Factorial of number 5. Prime factor.
Objective:

1. To apply control flow structures in C programming.


Outcomes:

After this experiment, students will able to apply control flow structure in c programming language.
AIM:
Study and apply decision making and looping statement.

H/W S/W Requirement:


Linux Operating System with GCC / TURBO C in WINDOWS OS.

Theory:
This assignment will read the number and perform different operation such as find Square root of
number, Square of number, Check for prime find Factorial of number, Prime factor on that number.
Switch case:
Switch case statement evaluates a given expression and based on the evaluated value (matching
a certain condition), it executes the statements associated with it. Basically, it is used to perform
different actions based on different conditions (cases).
Switch case statements follow a selection-control mechanism and allow a value to change control
of execution. They are a substitute for long if statements that compare a variable to several
integral values. The switch statement is a multiple way branch statement. It provides an easy
way to dispatch execution to different parts of code based on the value of the expression.
In C, the switch case statement is used for executing one condition from multiple conditions. It
is similar to an if-else-if ladder. The switch statement consists of conditional-based cases and a
default case.
Syntax of switch Statement in C:
switch(expression)
{
case value1: statement_1;
break;
case value2: statement_2;
break;
.
.
.
.
case value_n: statement_n;
break;
default: default_statement;
}

Sample Example of Switch case:

#include <stdio.h>

int main()

int week;

/* Input week number from user */

printf("Enter week number(1-7): ");

scanf("%d", &week);

switch(week)
{

case 1:

printf("Monday");

break;

case 2:

printf("Tuesday");

break;

case 3:

printf("Wednesday");

break;

case 4:

printf("Thursday");

break;

case 5:

printf("Friday");

break;

case 6:

printf("Saturday");

break;

case 7:

printf("Sunday");

break;

default:

printf("Invalid input! Please enter week number between 1-7.");

return 0;

}
Output:
Enter week number (1-7): 3
Wednesday

=== Code Execution Successful ===

Conclusion:
Thus, we have successfully calculated the Square root of number, Square of number, Check for
prime, Factorial of number and Prime factor.
Assignment No. 6
Title: In array do the following: 1. Find a given element in array 2. Find Max element 3.
Find Min element 4. Find frequency of given element in array 5. Find average of elements in
array.

Date of
Completion

Remark

Sign. of Staff

Problem Statement:
In array do the following: 1. Find a given element in array 2. Find Max element 3. Find Min element
4. Find frequency of given element in array 5. Find Average of elements in Array.

Objective:
To design a solution using Arrays in C Programming.

Outcomes:

After this experiment, students will able to declare array in C programming.

Aim:
Understand different types of arrays in C programming.

H/W & S/W Requirements:


Linux Operating System with GCC / TURBO C in WINDOWS OS.

Theory:
An array in C is a fixed-size collection of similar data items stored in contiguous memory locations.
It can be used to store the collection of primitive data types such as int, char, float, etc., and also
derived and user-defined data types such as pointers, structures, etc.
Syntax of Array Declaration:
datatype array_name [size 1] [size 2]....[size N];

Where N is the number of dimensions.


The ‘data type’ in the declaration refers to the type of each element in the array. ‘array_name’ refers
to the name by which the memory locations will be identified. ‘MAX_SIZE’ indicates the maximum
number of elements that can be stored in the array.

For example, an array with name ‘a’ having maximum 5 integer elements can be declared as int
a[5];
This declaration allocates 5 consecutive memory locations that can store 5 integer values. The
elements are referred using the combination of array name and index value. The array index is
referred to as ‘subscript’. For example, elements are referred to as a[0], a[1], a[2], …,
a[MAX_SIZE-1]. Following figure shows the scenario of the above declaration in memory:

Address: 3001 3003 3005 3007 3009

Index: 0 1 2 3 4

The number of memory locations required to hold an array depends on its type and size. For a one
dimensional array, its total size is,
Total Size=Size of array*Size of (array data type).
In above declaration, size of array ‘a’ is 5*2=10 bytes.
Array Initialization

An integer array can be initialized during its declaration. For


example, int marks[4]={67,80,55,79};
char grades[4]={‘A’, ‘B’, ‘C’, ‘D’};
The elements will be stored in the memory as shown in the figure below

Address: 5010 5012 5013 5015

67 80 55 79
Index: 0 1 2 3

Conclusion:
Thus, we have successfully find a given element in array, find Max element, find Min element, find
frequency of given element in array and find average of elements in array.
Assignment No. 7
Title:
To accepts a string that performs the following string operations- i. Calculate
length ii. String reversal iii. Equality iv. Palindrome v. substring
Date of
Completion

Remark
Sign. of Staff

Problem Statement:
Write a C program that accepts a string from the user and performs the following
string operations- i. Calculate length of string ii. String reversal iii. Equality check of two
Strings iv. Check palindrome v. Check substring

Objective:
1. To study strings and string operation in C
2. To apply different types of string built in functions.

Outcomes:
After this experiment, students will acquire knowledge of string operation in C

Aim:
A) Study of string in C.
B) Declaration of string variables in C.
C) Accepting and displaying string input.
D) Perform different operation on string.

Hardware & Software Requirement:


Linux Operating System with GCC / TURBO C in WINDOWS OS

Theory:
A string is a sequence of characters. e.g. "ScholarHat". In C, a string is stored as
an array of characters. You have to use char data type and make an array of characters to create
a string. The string is terminated with a null character '\0'. A string is represented using double
quotes, (" ") or single quotes (' '). Whenever an array of characters e.g. c[10] gets created, the
compiler implicitly appends '\0' at the end of the string.

How to declare a string in C?


Syntax:
char variableName[size];
Example:
char str[20];

String Functions in C
In C programming language, several string functions can be used to manipulate
strings. To use them, you must include the <string.h> header file in your program. Here are
some of the commonly used string functions in C:

1) strlen(): This function is used to find the length of a string. It takes a string as input and
returns the number of characters in the string (excluding the null character).
Syntax: int strlen(const char *str);

#include<stdio.h>
#include <string.h>
int main()
{
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output: 10
Length of string is:

2)strcpy(): This function is used to copy one string to another. It takes two arguments, the first
argument is the destination string where the source string will be copied and the second
argument is the source string.

#include<stdio.h>
#include <string.h>
int main()
{
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}
Output:
Value of second string is: javatpoint

3)strcat(): This function is used to concatenate two strings. It takes two arguments, the first
argument is the destination string where the source string will be appended and the second
argument is the source string.

#include<stdio.h>
#include <string.h>
int main()
{
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}

Output :

Value of first string is: helloc

4)strcmp(): This function is used to compare two strings. It takes two arguments, the first
argument is the first string and the second argument is the second string. It returns an integer
value that indicates the result of the comparison.
Syntax: int strcmp(const char *str1, const char *str2);

#include<stdio.h>
#include <string.h>
int main()
{
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Output:
Enter 1st string: hello
Enter 2nd string: hello
Strings are equal

5)Strrev() : The C standard library does not contain the strrev() function, which is not
a standard library function. However, it has long been a well-liked utility function for C
programmers to reverse strings. Despite being widely used, strrev() should not be used owing
to potential hazards and its inherent restrictions.The strrev(string) function returns reverse of
the given string
#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:
Enter string: javatpoint
String is: javatpoint
Reverse String is: tnioptavaj

6)strstr():The strstr() function in C is a part of the string.h library and is used to find the first
occurrence of a substring within a given string. If the substring is found in the string, it returns
a pointer to the first character of the first occurrence of the substring. The function returns
a NULL pointer if the substring is not present in the given string.
Syntax : char *strstr(const char *string, const char *match);

#include <stdio.h>
#include <string.h>
int main()
{
char str[100] = "this is javatpoint with c and java";
char *sub;
sub = strstr(str, "java");
if (sub != NULL)
{
printf("Substring is: %s", sub);
}
Else
{
printf("Substring not found.");
}
return 0;
}

7)strchr(): This function is used to find the first occurrence of a character in a string. It takes
two arguments, the first argument is the string and the second argument is the character to be
searched. It returns a pointer to the first occurrence of the character in the string.

Conclusion:
Thus, we have successfully performed operations on string.
Assignment No. 8
Title: Create Structure EMPLOYEE for storing details (Name, Designation, gender, Date
of Joining and Salary) and store the data and update the data structure

Date of
Completion

Remark
Sign. of Staff

Problem Statement:
Create Structure EMPLOYEE for storing details (Name, Designation, gender, Date of
Joining and Salary) and store the data and update the data structure

Objective:
1. To understand the concept of structure.
2. To declare structure variable.

Outcomes:
After this experiment, students will acquire knowledge of structures in C
language.

Aim:
(A) Study of structures in C.
(B) Declaration and initialization of structure variables in C.
(C) Perform different operation on structures.

Hardware & Software Requirement:


Linux Operating System with GCC / TURBO C in WINDOWS OS .

Theory:
Structure in c is a user-defined data type that enables us to store the collection of
different data types. Each element of a structure is called a member. Structure simulate the use
of classes and templates as it can store various information
The struct keyword is used to define the structure. Let's see the syntax to define
the structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Let's see the example to define a structure for an entity employee in c.


struct employee
{
int id;
char name [20];
float salary;
};

The following image shows the memory allocation of the structure employee that is defined
in the above example.

Here, struct is the keyword; employee is the name of the structure; id, name, and salary are
the members or fields of the structure. Let's understand it by the diagram given below:

Declaring structure variable


We can declare a variable for the structure so that we can access the member of the
structure easily. There are two ways to declare structure variable:

1.By struct keyword within main() function


2.By declaring a variable at the time of defining the structure.
Declaration within main ():
Let's see the example to declare the structure variable by struct keyword. It should be
declared within the main function.
struct employee
{
int id;
char name[50];
float salary;
};
Now write given code inside the main() function.
struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure.

Declaration with struct :


Let's see another way to declare variable at the time of defining the structure.
struct employee
{
int id;
char name[50];
float salary;
}e1,e2;

Accessing members of the structure


There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)

Simple program
#include<stdio.h>
#include<string.h>
struct employee
{
int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}

Conclusion:
Thus, we have studied structures and structure variables.

You might also like