[go: up one dir, main page]

0% found this document useful (0 votes)
45 views36 pages

Dsa M1

The document discusses the basic structure and sections of a C program. It explains that a C program consists of 6 main parts: documentation, preprocessor section, definitions, global declarations, main function, and sub-programs. These sections help make the program readable, modifiable, and easy to understand.

Uploaded by

kesebas6ex
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)
45 views36 pages

Dsa M1

The document discusses the basic structure and sections of a C program. It explains that a C program consists of 6 main parts: documentation, preprocessor section, definitions, global declarations, main function, and sub-programs. These sections help make the program readable, modifiable, and easy to understand.

Uploaded by

kesebas6ex
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/ 36

Structure of the C Program

The basic structure of a C program is divided into 6 parts which makes it easy to read, modify, document, and
understand in a particular format. C program must follow the below-mentioned outline in order to
successfully compile and execute. Debugging is easier in a well-structured C program.

Sections of the C Program

There are 6 basic sections responsible for the proper execution of a program. Sections are mentioned below:

Documentation

Preprocessor Section

Definition

Global Declaration

Main() Function

Sub Programs

1. Documentation
This section consists of the description of the program, the name of the program, and the creation date and
time of the program. It is specified at the start of the program in the form of comments. Documentation can
be represented as:

2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the program. Header files
help us to access other’s improved code into our code. A copy of these multiple files is inserted into our
program before the process of compilation.

Example:

#include<stdio.h>

#include<math.h>

3. Definition
Preprocessors are the programs that process our source code before the process of compilation. There are
multiple steps which are involved in the writing and execution of the program. Preprocessor directives start
with the ‘#’ symbol. The #define preprocessor is used to create a constant throughout the program.
Whenever this name is encountered by the compiler, it is replaced by the actual piece of defined code.

Example:

#define long long ll

4. Global Declaration
The global declaration section contains global variables, function declaration, and static variables. Variables
and functions which are declared in this scope can be used anywhere in the program.

Example:

int num = 18;


5. Main() Function
Every C program must have a main function. The main() function of the program is written in this section.
Operations like declaration and execution are performed inside the curly braces of the main program. The
return type of the main() function can be int as well as void too. void() main tells the compiler that the
program will not return any value. The int main() tells the compiler that the program will return an integer
value.

Example:

void main()

6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is shifted to the
called function whenever they are called from the main or outside the main() function. These are specified as
per the requirements of the programmer.

Example:

int sum(int x, int y)

return x+y;

Example: Below C program to find the sum of 2 numbers:


Data Structures using C

CONTROL STATEMENTS

C language allows you to manipulate the flow of program control by using various control
statements.These control statements are categorized into the following types:
1. Decision making statements Decide which actions are to be performed.
2. Looping statements Decide how many times an action is to be performed.
One of the significant differences between decision making and looping statements is that the
decisionmaking statements direct the flow of program control from top to bottom without any
iteration; while,looping statements direct the flow of program control from top to bottom, and
then again to the top, inan iterative manner.
A program may contain both decisions making as well as looping statements.

1.Decision Making Statements

C language supports the following decision-making statements:


1. If
2. If Else
3. Switch
1. If statement: If statement executes a specific set of instructions only if the given
expression is true. However, if the expression evaluates to a false value, then the set of
instructions are skipped at the time of program execution. A program can contain multiple if
statements.

Syntax:
if(expression)

statement 1;
statement 2;

statement n;

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 16
Data Structures using C

Figure below shows the flowchart of if statement:

Fig. Flowchart of if statement

Example: Using if statement, write a program to find out if the given number is positive or
negative.
Program : Determine whether given number is positive or negative
#include<stdio.h>
#include<conio.h>
void main()

int num;
clrscr();
printf(“Enter an integer value: “);
scanf(“%d”, &num);
if(num>=0)
If there is only a single statement inside the
printf(“%d is a positive number”,num); if block then the braces are not required
if(num<0) to be added.

printf(“%d is a negative number”,num);


getch();

2. If else statement: If else statement comprises two sets of instruction, one each with if and
else block. If the given expression statement is true then the if-block instructions are executed.
However, ifthe expression evaluates to a false value, then the if-block instructions are skipped
and the else-block instructions are executed. A program can contain multiple if else statements.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 17
Data Structures using C

Syntax:

if(expression)

statement 1;
statement 2;

statement n;

else

statement 1;
statement 2;

statement n;

Figure below shows the flowchart of if else statement:

Fig. Flowchart of if else statement

Example: Using if else statement, write a program to find out if the given number is positiveor
negative.
Program: Determine whether given number is positive or negative

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 18
Data Structures using C

#include<stdio.h>
#include<conio.h>
void main()

int num;
clrscr();
printf(“Enter an integer value: “);
scanf(“%d”, &num);
if(num>= 0) If-else block
printf(“%d is a positive number”,num);
else
printf(“%d is a negative number”,num);
getch();

Output:
Enter an integer value: 22
22 is a positive number
3. Switch statement: Switch statement is a multi-way selection structure that matches the
given expression or variable value with one of a number of integer values, and upon successful
match branches to the corresponding statement block. A default value is also specified with the
switch statement to take appropriate action in case there is a complete mismatch. Switch
statement can be considered as an alternative to multiple if statements.
Syntax:
switch (expression)
{
case value1:
<statement block>
break;
case value2:
<statement block>
break;
case value3:
<statement block>
break;
.
.
.
default:
<statement block>
}
In the above syntax:
expression is the expression to be matched.
value1, value2, etc., are constants, also known as case labels.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 19
Data Structures using C

Figure below shows the flowchart of switch statement:

Fig. Flowchart of switch statement

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 20
Data Structures using C

Example: Using switch statement, write a program to count the frequency of individual digits
in a number.
Program : To count the frequency of individual digits in a number

#include<stdio.h>
#include <conio.h>

void main()
{
long int num1, num2;
int temp, d1=0, d2=0, d3=0, d4=0, d5=0, d6=0, d7=0, d8=0, d9=0, d0=0;
clrscr();

printf(“\n Enter a number:”);


scanf(“%ld”, &num1);

num2=num1;
while(num1! = 0)
{
temp=num1%10;
switch(temp) /*Switch statement*/
{
case 1:
d1++; /*Counting number of Ones*/break;
case 2:
d2++; /*Counting number of Twos*/break;
case 3:
d3++; /*Counting number of Threes*/break;
case 4:
d4++; /*Counting number of Fours*/break;
case 5:
d5++; /*Counting number of Fives*/break;
case 0:
d0++; /*Counting number of Zeros*/break;
case 6:
d6++; /*Counting number of Sixes*/break;
case 7:
d7++; /*Counting number of Sevens*/break;
case 8:
d8++; /*Counting number of Eights*/break;
Case 9:
d9++; /*Counting number of Nines*/break;
default:
/*Do-nothing*/
}
num1=num1/10;
}

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 21
Data Structures using C

/*Displaying the frequency of individual digits in a number*/


printf(“\nThe no of 0s in %ld are %d”,num2,d0);
printf(“\nThe no of 1s in %ld are %d”,num2,d1);
printf(“\nThe no of 2s in %ld are %d”,num2,d2);
printf(“\nThe no of 3s in %ld are %d”,num2,d3);
printf(“\nThe no of 4s in %ld are %d”,num2,d4);
printf(“\nThe no of 5s in %ld are %d”,num2,d5); printf(“\nThe no of 6s in %ld are %d”,num2,d6);
printf(“\nThe no of 7s in %ld are %d”,num2,d7); printf(“\nThe no of 8s in %ld are %d”,num2,d8);
printf(“\nThe no of 9s in %ld are %d”,num2,d9);

getch( );
}
Output:
Enter the number: 889653442

The no of 0s in 889653442 are 0


The no of 1s in 889653442 are 0
The no of 2s in 889653442 are 1
The no of 3s in 889653442 are 1
The no of 4s in 889653442 are 2
The no of 5s in 889653442 are 1
The no of 6s in 889653442 are 1
The no of 7s in 889653442 are 0
The no of 8s in 889653442 are 2
The no of 9s in 889653442 are 1

Note The break statement is inserted with each case block so that the control exits from the
case
blocks will be sequentially validated.

2. Looping Statements
C language supports the following looping statements:
1. While
2. Do-While
3. For

1. While loop is used for repetitively executing a set of instructions until the specified condition
is true. As soon as the condition becomes false, the control is automatically transferred out of the
loop. Awhile loop can be considered as an equivalent of a repetitive set of if statements.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 22
Data Structures using C

Syntax:

while (expression)

statement 1;
statement 2;

statement n;

Figure below shows the flowchart of while loop.

Fig. Flowchart of while loop


Example : Using while loop, write a program to compute the sum of digits of a number.
Program : Sum of digits of a number
#include <stdio.h>
#include <conio.h>

void main()

long num, temp;


int sum=0;
clrscr();
printf(“\nEnter an integer value: “);
scanf(“%ld”,&num);

temp=num;
/*Calculating sum of digits*/
while(temp!=0)
If there are multiple statements inside the
sum = sum+temp%10; while block then the same must be
included inside braces; otherwise only
temp=temp/10; the immediate statement after the while
statement will be considered.

printf(“\nThe sum of digits of %ld is %d”,num,sum);


getch();

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 23
Data Structures using C

2. Do-While Loop:
Similar to the while loop, the do-while loop is also used for repetitively executing a set of
instructions until the specified condition is true. The difference between while loop and do-while
loop is that in while loop the conditional expression is evaluated first and if it is true, the
associated statement block is executed. However, in do-while loop the statement block is
executed first and thenthe conditional expression is evaluated. If the expression evaluates to a
true value, then the statement block is executed again; else the control is transferred out of the
do-while loop. Hence, in case of do- while loop, the statement block is executed at least once even
if the conditional expression evaluates to a false value at its very first attempt. This is in contrast
to the while statement which executes the statement block if and only if the conditional
expression is true.
Syntax
do

statement 1;
statement 2;

statement n;
}while(expression);

Figure below shows the flowchart of do-while loop.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 24
Data Structures using C

Example: Using do-while loop, write a program to compute the sum of digits of a number.
Program: Sum of digits of a number

#include <stdio.h>
#include <conio.h>

void main()

long num, temp;


int sum=0;
printf(“\nEnter an integer value: ”);
scanf(“%ld”,&num);

temp=num;
/*Calculating sum of digits*/

do

sum = sum+temp%10; A compiler error will be generated if


temp=temp/10; semi-colon is not inserted after while
} while(temp!=0); statement .

printf(“\nThe sum of digits of %ld is %d”,num,sum);


getch();

Output:
Enter an integer value: 123456
The sum of digits of 123456 is 21
3. For Loop:
The functionality of for loop is exactly the same as while loop, however its specificationis a little
different. It includes the initialization statement, conditional expression and the modifier
statement of the loop inside a single one-line for statement. At the end of each iteration, the
value of the variable is updated as per the modifier expression and the condition is again
evaluated. This processcontinues until the conditional expression holds true. The for loop is more
compact and easier to implementin comparison to while loop.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 25
Data Structures using C

Syntax:

for (expression1; expression2; expression3)

statement 1;
statement 2;

statement n;

In the above syntax:


Expression1 is the initialization statement that initializes the looping variable.
Expression2 is the conditional expression that states the looping condition.
Expression3 is the modifier expression that modifies the looping variable.

Figure below shows the flowchart of for loop.

Example : Using for loop, write a program to print integers from 1 to 10.
Program: To print integers from 1 to 10
#include <stdio.h>
#include <conio.h>

void main()

int i;
clrscr();
printf(“Integers from 1 to 10:\n”);

printf(“%d\n”,i)
The initialization statement, conditional
getch(); expression, and modifier expression are
separated by semi-colons.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 26
Data Structures using C

ARRAYS
Array is a linear data structure that groups elements of similar types and stores them at
contiguous memory locations. The concept of arrays can be easily related with real-life scenarios.
For example, percentage marks of 50 students, salary amounts of 100 employees and names of
books present in a library are all examples of arrays.
Each element in an array is assigned an index number called array subscript. It is used to
identify the location of element in the array. In C language, the index number of the base element
(first element)of an array starts with 0. Therefore, the location of the last element of an array
containing n elements is always n-1. An array is referred using the array name defined at the time
of array declaration. Each individual array element is referred using array name and index
number.
Let us consider an array A containing four elements. Figure below shows the logical
representation ofarray A:

Fig. Logical representation of array

Some of the typical operations performed on arrays include:


1. Insertion Inserts an element into the array.
2. Deletion Deletes an element from the array.
3. Traversal Accesses each element of the array.
4. Sort Rearranges the array elements in a specific order, such as ascending or descending.
5. Search Searches a key value in the array.

C supports the following types of arrays:


1. Single-dimensional arrays Represent elements of the array in a single column. The array
A shown in Figure above is an instance of single-dimensional array.
2. Multi-dimensional arrays Represent elements of an array in multiple columns and rows.
A multi-dimensional array is also referred as array of arrays. Such arrays are commonly
used to realize the mathematical concept of matrices.
Before an array can be used in a program, it needs to be first declared and initialized. You can

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 27
Data Structures using C

initialize an array either at the time of its declaration or initialize it later in the program with the
help of assignment operator.
The subsequent sections explain the declaration and initialization of single and multi-
dimensional arrays along with related syntax and examples.

1 .Single/Dimensional Array
Array Declaration:
Syntax:
<data-type> <array_name>[size];
Example:
int A[10];

Array Initialization:
Syntax:
<data-type> <array_name>[size] = {element1, element2, ….., elementn};
<array_name>[index_number] = <element>;

Example:

int A[3]={2,4,8};
A[0]=2;

Array size (in bytes):


The size of a single-dimensional array can be calculated by using the following formula:
array size = length of array * size of data type
Example:
Consider the following array:
int A[4] = {10, 20, 30, 40};
Here, size of array A = 4 * 2 = 8 bytes.

Array Representation
Figure below shows the logical representation of single-dimensional array.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 28
Data Structures using C

Example:Using single-dimensional array, write a program to find the average of 10 numbers.


Program : To find average of 10 numbers

#include <stdio.h>
#include <conio.h>

void main()

int a[10], sum, i;

clrscr();

printf(“Enter ten integers: “);


for(i=0;i<=9;i++)
scanf(“%d”,&a[i]);

sum=0;

for(i=0;i<=9;i++)
sum=sum+a[i];

ave=1.0*sum/10;

/*Displaying the results*/


printf(“\nAverage = %.2f”,ave);
getch();

2.Multi/Dimensional Array

Array Declaration:
Syntax:

<data-type> <array_name>[row-subscript] [column-subscript];


Example:
int A[2][2];

Array Initialization:
Syntax:
<array_name> [row-index_number][column-index_number] = <element>;
<data-type> <array_name>[row-subscript][column-subscript] =
{element1, element2, ….., elementn};
Example:
A[1][0]=3;
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 29
Data Structures using C

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


The above declaration statement initializes array A in the following manner:
A[0][0]=1
A[0][1]=2
A[1][0]=3
A[1][1]=4 */

Array size (in bytes):


The size of a multi-dimensional array can be calculated by using the following formula:
array size = row-size * column-size * size of data type
Example: Consider the following array:
int A[2][2] = {10, 20, 30, 40};
Here, size of array A = 2* 2 * 2 = 8 bytes.

Array Representation
Figure below shows the logical representation of multi-dimensional array.

Example :Using multi-dimensional array, write a program to represent a 2 ¥ 2 matrix.

#include <stdio.h>
#include <conio.h>

void main()

int i,j,M[2][2];

printf(“Enter the elements of the 2 ¥ 2 matrix:\n”);


for(i=0; i<2;i++)
for(j=0; j<2;j++)

printf(“M[%d][%d] = “, i, j);
the inner loop signifies matrix columns.
scanf(“%d”,& M[i][j]);

printf(“The matrix represented by the 2 ¥ 2 2D array is:\n”);


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

printf(“\n\t\t “);
for(j=0; j<2; j++)
printf(“%d “, M[i][j]);
getch();

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 30
Data Structures using C

3. STRINGS

C supports the concept of strings to store a string of characters. Strings are nothing but character
arrays that store the string characters at contiguous memory locations with a null character
stored at the last location to indicate the end of the string.
The syntax and example of string declaration and initialization is shown below:
Syntax:

<data_type> <string_name>[size]=”string_characters”;
Example:
char str[10]=”hello”;
C supports a number of built-in functions that make it easier to work with strings. Table
below lists these string-based functions:

String functions:

Type Function
Input/output string functions gets( ) Receives a character string from the console.
Example:
char str[50]; gets(str);
puts( ) Prints the string data on the console.
Example:
char str[50]; gets(str); puts(str);

String-handling functions strcat( ) Joins two strings together.


strlen( ) Determines the number of characters in a string.
strcpy( ) Copies the characters of one string into anotherstring.
strcmp( ) Compares whether two strings are equal or not.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 31
Data Structures using C

Example: Write a program to print the reverse of a string.


#include <stdio.h>
#include <conio.h>
#include <string.h> Appropriate header files should be
included in a program before the
related functions are called.
void main()

charstr[30],revstr[30]; /*Declaring character arrays for storing strings*/


inti,len;
clrscr();
printf(“\nEnter a string: “);
gets(str);
len=strlen(str);
for(i=0;i<len;i++
) revstr[len-i-
1]=str[i];
revstr[len]=’\0’;

printf(“\n\nThe reverse of string %s is

%s”,str,revstr);getch();

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 32
Data Structures using C

Example :Using functions, write a program to implement a simple arithmetic calculator.


Program: To implement a simple arithmetic calculator

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 37
Data Structures using C

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 38
Data Structures using C

7. STRUCTURES

Structures are used to group together data of different types inside a single unit. It removes one
of the key limitations of arrays which can only store data elements with similar types. Thus,
structures can be easily used in situations where data elements with distinct types are required
to be stored as a singleentity; for example, a student record containing data elements such as
name, roll no, marks, etc.
Before a structure can be used in a program, it needs to be first declared and initialized. The
subsequent sections explain the declaration and initialization of a structure along with the
method of accessing itsdata members.
Structure Declaration
Syntax:
struct <structure_name>

<data_type> member1;
<data_type> member2;

<data_type> membern;
}var1;
struct <structure_name> var2;

Example:
struct book

Char title[20];
Char author[15];

}book1;
struct book book2;

Structure Initialization:
Syntax
structure_variable1.member1=value;
structure_variable2.member2= value;

Example:
book.title = “Data Structures”;

book.pages = 450;

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 39
Data Structures using C

Example :Write a program that uses a simple structure to store students’ details.
Program:To store students’ details
#include <stdio.h>
#include <conio.h>

void main ()

int num, i=0;

/*Structure Declaration*/
struct student

char name[30];
int rollno;
int t_marks;
};

struct student std[10];


clrscr(); This statement declares an
array of structures.
printf(“Enter the number of students: “);

scanf(“%d”,&num);

/*Reading student details*/


for(i=0;i<num;i++)
{
printf(“\nEnter the details for student %d”,i+1);printf(“\n\n Name “);
scanf(“%s”,std[i].name);
printf(“\n Roll No. “); scanf(“%d”,&std[i].rollno); printf(“\n Total Marks “);
scanf(“%d”,&std[i].t_marks);
}

/*Displaying student details*/


printf(“\n Press any key to display the student details!”);getch();

for(i=0;i<num;i++)
printf(“\n student %d \n Name %s \n Roll No. %d \n Total Marks %d\n”,i+1,std[i].name,
std[i].rollno, std[i].t_marks);

getch();
}

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 40
Data Structures using C

Example: write a program to perform complex number addition using structures.


Program: To perform complex number addition using structures
#include <stdio.h>
#include <conio.h>
#include <math.h>

void main()

struct complex/*Realizing a complex number using structure*/

double real;/*Real part*/


double img;/*Imaginary part*/
};
struct complex c1, c2, c3;
clrscr();

/*Reading the 1st complex number*/


printf(“\n Enter two Complex Numbers (x+iy):\n\n Real Part of First
Number: “);
scanf(“%lf”,&c1.real);
printf(“\n Imaginary Part of First Number: “);
scanf(“%lf”,&c1.img);

/*Reading the 2nd complex number*/


printf(“\n Real Part of Second Number: “);
scanf(“%lf”,&c2.real);
printf(“\n Imaginary Part of Second Number: “);
scanf(“%lf”,&c2.img);

/*Performing complex number addition*/


c3.real=c1.real+c2.real; The dot (.) operator is used for
c3.img=c1.img+c2.img; accessing individual structure
members.
/*Displaying the result*/
printf(“\n\n %.2lf+(%.2lf)i + %.2lf+(%.2lf)i = %.2lf+(%.2lf)i”, c1.real,
c1.img, c2.real, c2.img, c3.real, c3.img);

getch();

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 41
Data Structures using C

8. UNIONS
Like structures, unions also allow us to group together dissimilar type elements inside a single
unit. But there is a significant difference between structures and unions in the way they are
implemented in the system. The size of a structure is equal to the sum of the sizes of its
constituent members. In contrast, the size of a union is equal to the size of its largest sized
element. This is because unions allow only one member to be utilized at any given point of time.
That is, union members can only be manipulated exclusive of each other.

Syntax:

union <union_name>

type1 var1;
type2 var2;

typen varn;
};
Example:

union result
{
int marks;
char grade;
float percent;
};
Unions are particularly useful in situations where it is not required to simultaneously access
the data members. In such situations, unions prove to be memory efficient in comparison to
structures.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 42
Data Structures using C

Example: Write a program to demonstrate the use of unions.


Program: Use of unions
/*Program for demonstrating the use of unions*/
#include <stdio.h>
#include <conio.h>
void main ()
/*Union Declaration*/
union student

Int roll_no;
char result;
}st1,st2;

st1.roll_no=20; /*Initializing union variables*/


st2.result=’P’;

/*Accessing and printing the values correctly*/


printf(“\nRoll NO: %d”,st1.roll_no);
printf(“\nResult: %c”,st2.result);

printf(“\n\n”);
/*Accessing and printing the values incorrectly*/
printf(“\nRoll NO: %d”,st2.roll_no);
printf(“\nResult: %c”,st1.result);

getch();

9. Structures v/s Unions


Table below lists the key differences between structures and unions.

Structures Unions
It is defined with ‘struct’ keyword. It is defined with ‘union’ keyword.
All members of a structure can be utilized Only one member of a union can be utilized at
simultaneously. anygiven point of time.
The size of a structure is equal to the sum of the The size of a union is equal to the size of its
sizesof its members. largestmember.
Structure members are stored at discrete locations All the union members share common memory
inmemory. space.
Structures are not considered as memory efficient Unions are considered as memory efficient in
incomparison to unions. situationswhere the members are not required to
be accessed simultaneously.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 43
Data Structures using C

POINTERS

Pointer is a derived data type that stores memory addresses as its value. It points or indicates the
location where another variable is stored. Pointers are particularly used for dynamic memory
management. Figure below shows the logical representation of a pointer:

Pointer Declaration and Initialization


A pointer is declared with the help of ‘ * ’ operator and initialized with the help of & operator, as
shown in the following code snippet:

int num=10;
int *ptr; /*Pointer declaration*/
ptr=&num; /*Pointer initialization*/
In the above code, the address of num variable is allocated to pointer variable ptr. Whenever
* is preceded with a variable name, it refers to the value stored at the location being pointed by the
variable.On the other hand, whenever & is preceded with a variable name, it refers to the memory
address of the variable.
Like any other variable, pointer variables can also be used in expressions to form pointer expressions.
This is depicted below:
a = *b +*c;

z = z + *y;

*c = *ptr+5;

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 44
Data Structures using C

Example: Using the concept of pointers, write a program to print the address and value of a
variable.
Program: To print address and value of a variable
#include<stdio.h>
#include<conio.h>

void main()

int a;
int *ptr; /*Declaring pointer variable*/
clrscr();

a=50;
ptr=&a; /*Pointer allocation*/

printf(“address of a = %u\tvalue of a = %d\n”,ptr,*ptr);


printf(“address of ptr = %u\tvalue of ptr = %u”,&ptr,ptr);

getch(); %u specifier is used for


printing address values.

Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 45
8/8/23, 7:43 PM Swapping numbers using Call by Value in C - Forget Code

Choose Category

Swapping numbers using Call by Value in


C
Forget Code (/) / C (/Sitemap/C) / Swapping numbers using Call by Value

1. //Call by Value Example - Swapping 2 numbers using Call by Value


2. #include <stdio.h>
3.
4.
5. void swap(int, int);
6.
7. int main()
8. {
9. int x, y;
10.
11. printf("Enter the value of x and y\n");
12. scanf("%d%d",&x,&y);
13.
14. printf("Before Swapping\nx = %d\ny = %d\n", x, y);
15.
16. swap(x, y);
17.
18. printf("After Swapping\nx = %d\ny = %d\n", x, y);
19.
20. return 0;
21. }
22.
23. void swap(int a, int b)
24. {
25. int temp;
26.
27. temp = b;
28. b = a;
29. a = temp;
30. printf("Values of a and b is %d %d\n",a,b);
31. }
32.

Output:

Enter the value of x and y

Before Swapping

x = 10

y=5

https://forgetcode.com/c/1957-swapping-numbers-using-call-by-value 2/3
8/8/23, 7:43 PM Swapping numbers using Call by Value in C - Forget Code

Output:

Values of a and b is 5 10

After Swapping

x = 10

y=5

© Forget Code 2023 About (/About) | Feedback | Sitemap (/Sitemap)

https://forgetcode.com/c/1957-swapping-numbers-using-call-by-value 3/3

You might also like