[go: up one dir, main page]

0% found this document useful (0 votes)
19 views42 pages

Pps Answers

The document provides a comprehensive overview of fundamental concepts in C programming, including the purpose of the main() function, basic data types, and the importance of linking and definition sections. It covers various programming constructs such as loops, conditional statements, pointers, and type casting, along with examples and explanations of their usage. Additionally, it includes sample C programs for practical understanding and details about program creation and execution steps.

Uploaded by

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

Pps Answers

The document provides a comprehensive overview of fundamental concepts in C programming, including the purpose of the main() function, basic data types, and the importance of linking and definition sections. It covers various programming constructs such as loops, conditional statements, pointers, and type casting, along with examples and explanations of their usage. Additionally, it includes sample C programs for practical understanding and details about program creation and execution steps.

Uploaded by

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

UNIT-1

.What is the purpose of main () function in C?

Ans:- The main() function is the starting point of a program, where the computer begins executing
the code.

The main() function i.n C programming is the entry point of a program, where execution begins

2. List the basic datatypes in C?

Ans:-

The four basic data types in C are:

 Char: Stores a single character, letter, number, or ASCII value

 Int: Stores whole numbers, without decimals

 Float: Stores fractional numbers, containing one or more decimals

 Double: Stores fractional numbers, containing one or more decimals

3.What is the importance of Linking and Definition section in C?

Ans:-

 Linking

Linking is the process of combining multiple object files into a single executable file. This process is
necessary to create a self-contained program. There are two types of linkers: static and
dynamic. Static linkers merge all the necessary object code and libraries into a single executable
file. Dynamic linkers allow the program to be loaded into memory at runtime and link to shared
libraries.

Definition section

A declaration establishes an association between a variable, function, or type and its attributes. It
also specifies where and when an identifier can be accessed

4.Describe the difference between = and = = operators in C.


Ans:- In C, the = operator is used to assign a value to a variable, while the == operator compares the
values of two variables:

 = Assigns a value to a variable

 == Compares the values of two variables

5. Define Variable with syntax? Give an example.

A variable is a named container for storing data in a program. The syntax for declaring a variable
depends on the programming language:

The syntax for declaring a variable in C is type variableName = value. For example, int myNum =
15 creates a variable named myNum of type int and assigns it the value 15.

6. Differentiate between compiler and interpreter.

Ans:- A compiler translates source code into machine code before a program runs, while an
interpreter translates code line-by-line as the code runs Part -A

1Define multidimensional array? List the advantages of Arrays.

Ans:-

A multi-dimensional array is an array with more than one level or dimension. For example, a 2D
array, or two-dimensional array, is an array of arrays, meaning it is a matrix of rows and columns
(think of a table). A 3D array adds another dimension, turning it into an array of arrays of arrays

2 Distinguish between String & Character.

Ans:-Strings are sequences of characters enclosed in double quotes, used for handling text and
varying in length. Characters, represented by single symbols in single quotes, are primitive data types
primarily used for storing and manipulating individual symbols.

3.Define Structure with syntax?

In C, the syntax for defining a structure is as follows:

 struct: The keyword that defines a structure

 StructureName: The name of the structure


 {: The opening curly brace that encloses the structure's components

 dataType1 member1; dataType2 member2; The member variables, also known as fields,
and their data types

 }: The closing curly brace that ends the structure

Example:-

struct MyStructure {

int myNum; // Member (int variable)

char myLetter; // Member (char variable)

};

4.What are the advantages of loops? Loops are a fundamental concept in programming that have
many advantages, including:

Ans:-

 Code reusability

Loops allow programmers to reuse code without writing it repeatedly.

 Time and error reduction

Loops can save time and reduce errors by minimizing the number of lines of code.

 Clear and effective code

Loops reduce repetition, which can lead to clearer and more effective code.

 Dynamic programs

Loops allow developers to create dynamic programs that can efficiently perform repetitive tasks.

 Data structure traversal

Loops can be used to traverse over the elements of data structures, such as arrays or linked lists.

5. List the types of conditional statements.

Ans :-Here are some types of conditional statements:

 If statement
A fundamental conditional statement that evaluates if a statement is true or false. If the statement is
true, the if statement runs. If the statement is false, the program skips to the next section.

 If-else statement

Defines conditions for execution. If the if condition is true, the if statement executes. If the if
condition is false, the else statement executes.

 Nested if statement

An if statement inside another if statement. This is used when a variable needs to be processed more
than once.

 Switch statement

Evaluates an expression against multiple cases and executes one or more blocks of code based on
matching cases.

 Ternary operator

Also known as the conditional operator, conditional expression, ternary if, or inline if (iif). It can be
used to replace if-else statements

6. Define Union with syntax?

Ans:-

A union is a user-defined data type that allows different data types to be stored in the same memory
location. The size of the union is determined by the size of its largest member.

1.Define Pointer? List the types of pointers.

Ans:-

A pointer is a variable that stores the memory address of another variable.

 Structure pointer: Points to a structure, which is a group of related variables

 Dangling pointer: Points to a memory location that has been deallocated

 Null pointer: Points to no valid memory location

 Void pointer: Can hold the address of any type

 Pointer to pointer: A pointer variable that holds the address of another pointer

2.What is the use of pointers in Self-referential Structures.

Ans:
Pointers are used in self-referential structures to store the address of the next node, which allows for
iteration through data structures

3. Discuss the advantages of Pointers?

Ans:-

Pointers have several advantages, including:

 Direct memory access: Pointers allow you to directly access and manipulate memory
locations, which can improve performance. This is especially useful when working with large
data structures or performing low-level operations.

 Dynamic memory allocation: Pointers can be used to take advantage of dynamic memory
allocation.

PART-B

1.What are the rules of identifiers in C?

ANS:- Here are some rules for identifiers in C:

 First character: The first character of an identifier must be an underscore or an alphabet.

 Case sensitivity: Identifiers are case-sensitive, so "myVar" and "myvar" are different
identifiers.

 Length: Identifiers can have up to 31 characters.

 Characters: Identifiers can contain letters, digits, and underscores, but no other special
characters.

 Keywords: Identifiers cannot be C keywords.

 Uniqueness: Each identifier must have a unique name within the scope it is defined in.

 White spaces: Identifiers cannot contain white spaces or commas.

 Descriptive: Identifiers should be short yet descriptive and easy to understand.

2.Write a C program to find the sizes of all data types.

ANS:-

#include <stdio.h>

void main()
{

int a;

float b;

char c;

double d;

printf("\n SIZE OF OPERATOR int=%lu bytes\n and address=%d %d", sizeof(a),&a,&b);

printf("\n SIZE OF OPERATOR float=%lu bytes\n", sizeof(b));

printf("\n SIZE OF OPERATOR char=%lu bytes\n", sizeof(c));

printf("\n SIZE OF OPERATOR double=%lu bytes\n", sizeof(d));

3. Explain about Precedence, Associativity and Expression evaluation.

Ans:-

Precedence, associativity, and order of evaluation are concepts that determine how operators and
operands are grouped and evaluated in expressions:

 Precedence: The priority for grouping operators with operands. Operators with higher
precedence are evaluated first.

 Associativity: The order for grouping operands with operators that have the same
precedence. Associativity can be left-to-right or right-to-left.

 Order of evaluation: The sequence in which operands are evaluated.

Understanding these concepts is important for writing efficient and correct code. Parentheses can be
used to override precedence and associativity

C: In C, precedence determines the order in which operators are evaluated, and associativity
determines the order in which operators with the same precedence are evaluated.

4. Write a C program to find the maximum of two numbers using a ternary operator.

ANS:-
#include <stdio.h>

int main() {

int a,b;

printf("Enter two integers: ");

scanf("%d%d", &a,&b);

( a>b) ? printf("%d is greater.", a) : printf("%d is larger.", b);

return 0;

5. Draw a flowchart to find the largest of two numbers.

6. Write a C program to swap two variables without using third variable


Ans:-

#include<stdio.h>

int main()

int x, y;

printf("Input value for x & y: \n");

scanf("%d%d",&x,&y);

printf("Before swapping the value of x & y: %d %d",x,y);

x=x+y;

y=x-y;

x=x-y;

printf("\nAfter swapping the value of x & y: %d %d",x,y);

return 0;

7.Explain about the various steps involved in creating and running a C program.

Ans-

The steps for creating and running a C program include:

 Writing the code: Open a text editor or IDE and create a new file with a .C extension.

 Compilation: The compilation process converts the source code into machine code. This
process includes four stages:

o Preprocessing: Expands macros and includes header files.

o Compilation: The preprocessed source code is converted to machine code, and the
compiler checks for errors.

o Assembly: The compiler's assembly code is translated into object code.

o Linking: The object code is converted into an executable format.

 Execution: The operating system loads the executable file into memory, and the program
begins to execute
8.What is meant by Operator? List the types of Operators and explain any four operators with a C
program

Ans:- An operator is a fundamental tool or sign used to perform mathematical and logical operations
in programming languages. Here are some types of operators in C and their examples:

 Arithmetic operators

Used to perform mathematical operations on operands, such as addition, subtraction, multiplication,


division, and modulo. Examples of arithmetic operators include:

 −: Subtracts the value of the second operand from the first

 \*: Multiplies the two operands

 /: Divides the operand in the numerator by the operand in the denominator

 %: Gives out the remainder for an integer division

 ++: Increases the value of a variable by 1

 Relational operators

Also known as Comparison Operators, these compare the values of the two operands. The result of
the comparison is either true or false. Examples of relational operators include:

 == Checks if the values of two operands are equal or not

 != Checks if the values of two operands are equal or not

 >: Checks if the value of left operand is greater than the value of right operand

 <: Checks if the value of left operand is less than the value of right operand

9.Define type casting and explain in detail about implicit and explicit type casting with example
programs?

Type casting is the process of converting a variable from one data type to another. There are two
types of type casting: implicit and explicit:

 Implicit type casting

Also known as widening conversion, this is when the compiler automatically converts a smaller type
to a larger type size. This happens when there is no loss of data.

 Explicit type casting

This is when a programmer manually converts a larger type to a smaller type size. This is used when
there is a possibility of data loss
In C, the compiler can automatically change one data type to another based on the program's
requirements. For example, if an integer (int) value is assigned to a float variable (floating point), the
compiler will automatically convert the int value into a float value

//Example: Explicit conversion

#include<stdio.h>

void main()

int a = 25, b = 13;

float result;

result = a/b; // display only 2 digits after decimal point

printf("(Without typecasting) 25/13 = %.2f\n", result );

result = (float)a/b; // display only 2 digits after decimal point

printf ("(With typecasting) 25/13 = %.2f\n", result);

//Example :Implict Conversion

#include<stdio.h>

int main()

int i=3;

float b;

b=i;

printf("the value of b is =%d",b);

return 0;

1.Write a C program to find the maximum of three numbers

Ans:-

#include <stdio.h>

void main( )

{
int a, b, c;

printf("Enter 3 numbers...:\n ");

scanf("%d%d%d",&a, &b, &c);

if(a > b)

if(a > c)

printf(" %d is the greatest\n",a);

else

printf("%d is the greatest\n",c);

else

if(b > c)

printf("%d is the greatest\n",b);

else

printf("%d is the greatest \n",c);

printf("\n End of prog");

}.
2. Write a C program to find the sum of digits of a given number

Ans:-

#include <stdio.h>

void main()

int n, temp, r=0,sum=0;

printf("\n Enter an integer: \n");

scanf("%d", &n);

temp = n; /* original number is stored at temp */

while (n > 0)

r = n % 10;

sum=sum+r; // sum of Individual Numbers

n = n/10;

printf("\n Given number is = %d\n", temp);

printf("\n Sum of individual digits of a given number is:%d", sum);

3.Write a C program to find out the maximum element from an array

Ans:

#include<stdio.h>

main()

int a[50];

int n,i,max;

printf("how many elements");

scanf("%d",&n);
printf("enter the number of elements");

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

scanf("%d",&a[i]);

max=a[0];

for(i=1;i<n;i++)

if(a[i]>max)

max=a[i];

printf("max=%d",max);

4.Write in detail about any five string handling functions with examples

Ans:

#include<stdio.h>

#include<string.h>

void main ()

char str1[50]="Hello";

char str2[50]="World";

char str3[50];

int len;

/* copy str1 into str3 */

strcpy(str3, str1);

printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */

strcat( str1, str2);

printf("strcat( str1, str2): %s\n", str1 );


/* total lenghth of str1 after concatenation */

len=strlen(str1);

printf("strlen(str1) : %d\n",len);

5.Explain in detail about declaring two dimensional arrays, reading elements and displaying the
elements of it.

Ans:-

6 Write a C program to test whether the given number is a prime or not

// C Program to check for prime number using

// Simple Trial Division


#include <stdbool.h>

#include <stdio.h>

int main() {

int n = 29;

int cnt = 0;

// If number is less than/equal to 1,

// it is not prime

if (n <= 1)

printf("%d is NOT prime\n", n);

else {

// Check for divisors from 1 to n

for (int i = 1; i <= n; i++) {

// Check how many number is divisible

// by n

if (n % i == 0)

cnt++;

// If n is divisible by more than 2 numbers

// then it is not prime

if (cnt > 2)

printf("%d is NOT prime\n", n);

// else it is prime

else

printf("%d is prime", n);


}

return 0;

7 Explain in detail about pre- test/Entry Controlled and post- test/Exit controlled loops with
example programs.

Ans:-

In looping, the set statement executes until the condition becomes false.

There are mainly two types of loops:

1. Entry Controlled loops: In this type of loops the test condition is tested before entering the
loop body. For Loop and While Loop are entry-controlled loops.

2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the
end of loop body. Therefore, the loop body will execute atleast once, irrespective of whether
the test condition is true or false. do – while loop is exit-controlled loop.
Types of Loops

There are 3 types of Loop in C language, namely:

1. while loop

2. for loop

3. do while loop

while loop

Syntax :

while(condition)

statements;

It is completed in 3 steps.

Variable initialization (e.g. int x = 0)

Condition (e.g. while(x <= 10))

Variable increment or decrement (x++ or x-- or x = x + 2 )

Working while loop

In while loop, condition is executed first, If the condition is true the body loop will executed , again
check the condition if true the body loop will be executed this process will be continue until the
condition false then the loop is terminated,

Note: while loop can be called as an entry control loop


Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )

int x;

x = 1;

while(x <= 10)

printf("%d\t", x); /* do x = x+1, increment x by 1*/

x++;

}// while close

}// main close

Output:

1 2 3 4 5 6 7 8 9 10

do…while loop

Syntax:

do{

statement (s);

} while(condition);

Working do-while loop


In do-while loop, the body of the loop is executed first without testing conditions. At the end of the
loop, test condition in the while statement is evaluated. If the condition is true, the program
continues to evaluate the body of the loop once again. This process continues as long as the
condition is true. When the condition becomes false, the loop is terminated,

Note: do..While loop can be called as an exit control loop.

Example: Program to print first 3 natural numbers

#include <stdio.h>

int main()

int j=0;

do

printf("Value of variable j is: %d\n", j);

j++;

} while (j<=3);

return 0;

Output

value of variable j is: 0

Value of variable j is: 1

Value of variable j is: 2

Value of variable j is: 3


For
loop

Syntax of for loop:

for (initialization; condition test; increment or decrement)

Statements // body of loop

The for loop is executed as follows:

1. It first evaluates the initialization code.

2. Then it checks the condition expression.


3. If it is true, it executes the for-loop body.

4. Then it evaluates the increment/decrement again check the condition follows from step 2.

5. When the condition expression becomes false, it exits the loop.

Example 1: WAP to ask the


integer number n and calculate the sum of all natural numbers from 1 to n.

#include<stdio.h>

void main()

int n, i, sum=0;

printf("Enter any number :\n ");

scanf("%d",&n);

for(i=1; i<=n; i++)


{

sum = sum + i;

printf("The Sum of Natural Numbers = %d\n ",sum);

Output

Enter any number : 5

The Sum of Natural Numbers = 15

8 Explain in detail about decision making statements with suitable examples.

Branching (Decision making) statement

 When we need to execute a block of statements only when a given condition is true then we
use decision making statement

Decision-making by supporting the following statements,

1. if statement

2. switch statement

1. if statement

if statement having 4 ways

1. Simple if

2. if..else,

3. nested if..else

4. else..if. ladder

simple if statement:

If the condition/expression is "true" statement inside block will be executed,

if condition is "false" then statement inside block will skipped i.e. not executed, statement outside
block executed.
if(expression)

Statement_inside;

Statement_outside;

Example 1:

// Program to display the lowest of two numbers

#include<stdio.h>

void main()

int x =20;

int y =22;

if(x<y)

printf("Variable x is less than y");

printf(“\n End of program \n”);


}

Example 2:

// Program to display a number if it is negative

#include <stdio.h>

void main()

int n;

printf("\n Enter an integer:\n ");

scanf("%d", &n);

if (n< 0) // true if number is less than 0

printf("You entered %d is negative \n", n);

printf("End of statement\n");

output

Enter an integer: -2

You entered -2 is negative

End of statement

2. if...else statement

Syntax:

if(expression)

statement block1;

else

statement block2;
}

If the expression is true, the statement-block1 is executed, else statement-block1 is skipped and
statement-block2 is executed.

Example 1: Write a program to check whether the given number is odd or even.

#include<stdio.h>

void main()

int n;

printf("Enter any Number :\n ");


scanf("%d", &n);

if(n%2 == 0)

printf("%d is Even Number", n);

else

printf("%d is Odd Number", n);

Printf(“\n End of program \n”);

Output:

Enter any Number : 60

60 is Even Number

End of program

3. Nested if....else statement

 Condition in condition is called nested if ..else statement

Syntax:

if( expression1 )

if( expression2 )

statement block1;

else

statement block2;
}

else

statement block3;

if expression1 is false then statement-block3 will be executed, otherwise the execution continues and
enters inside the first if to perform the check for the next if block, where if expression 2 is true the
statement-block1 is executed otherwise statement-block2 is executed.

Flow chart for Nested if....else statement

Example 1: Write a program to find greatest number among the 3 numbers.


#include <stdio.h>

void main( )

int a, b, c;

printf("Enter 3 numbers...:\n ");

scanf("%d%d%d",&a, &b, &c);

if(a > b)

if(a > c)

printf(" %d is the greatest\n",a);

else

printf("%d is the greatest\n",c);

else

if(b > c)

printf("%d is the greatest\n",b);

else

printf("%d is the greatest \n",c);

Printf(“\n End of prog”);

}// main
Output:

Enter 3 numbers...:

12

12 is the greatest

3. else if ladder

if(expression1)

statement block1;

elseif(expression2)

statement block2;

elseif(expression3 )

statement block3;

}
else

default statement;

Statement_Next;The expression is tested from the top (of the ladder) downwards. As soon as a true
condition is found, the statement associated with it is executed.

Flow chart for else if ladder


Example 1: WAP a program to get the percentage and print the division;

Conditions:

if percentage >=75, Division = Distinction

if percentage<75 and >=60, Division = First

if percentage < 60 and >=40, Division = Second

if percentage < 40 and >=35, Division = Third

Otherwise fail.

#include<stdio.h>

void main()

int per;

printf("\nEnter your percentage : \n");

scanf("%d",&per);

if(per>=75)

printf("Division = Distinction\n");

else if(per < 75 && per>=60)

printf("Division = First\n");

else if(per<60 && per>=45)

printf("Division = Second\n");

else if(per<45 && per >=35)

printf("Division = Third\n");

else

printf("Division = Fail ...\n ");

printf(“\n End of program\n”);

}
Output:

Enter your percentage: 68

Division = First

End of program

9.Write a C program to implement matrix multiplication.

#include<stdio.h>

void main()

int a[10][10],b[10][10],c[10][10];

int r1,c1,r2,c2;

int i,j,k;

int sum=0;

printf("enter rows & columns of a\n ");

scanf("%d%d",&r1,&c1);

printf("enter rows & columns of b\n ");

scanf("%d%d",&r2,&c2);

if(c1==r2)

{ /*Reading array a elements*/

printf("enter a elements");

for(i=0;i<r1;i++)
{ for(j=0;j<c1;j++)

scanf("%d",&a[i][j]);

/*Reading array b elements*/

printf("enter b elements\n");

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

for(j=0;j<c2;j++)

scanf("%d",&b[i][j]);

/*Matrix multiplication logic */

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

for(j=0;j<c2;j++)

{ sum=0;

for(k=0;k<c1;k++)

sum=sum+a[i][k]*b[k][j];

c[i][j]=sum;

/*Display resultant array c elements*/

printf("display c\n ");

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

for(j=0;j<c2;j++)
{

printf("%d\t",c[i][j]);

printf("\n");

else

printf("Multiplication not possible");

1.Define Pointer? What are the types of Pointers? Explain with examples.

 The pointer in C language is a variable which stores the address of another variable.

 This variable can be of type int, char, array, function, or any other pointer.

 The size of the pointer depends on the architecture. However, in 32-bit architecture the size
of a pointer is 2 byte, in 64-bit architecture the size of a pointer is 4 byte.

 A Pointer in C is used to allocate memory dynamically i.e. at run time.

Syntax :

data_type *var_name;

where

 data_type any datatype like int,char, float..

 var_name any user defined name.

Example : int *p; char *p;

Where, * is used to denote that “p” is pointer variable and not a normal variable.

Consider the following example to define a pointer which stores the address of an integer.
int n = 10;

int* p = &n;

// Variable p of type pointer is pointing to the address of the variable n of type integer.

Pointer Example

An example of using pointers to print the address and value is given below.

int n=50;

int *p;

p=& n;

p=address of n, *p=50(i.e *(&n)=50)

int a[50], p=a p=&a[0];

TYPES OF POINTERS

1. NULL Pointer

 A pointer that is not assigned any value but NULL is known as the NULL pointer.

 If you don't have any address to be specified in the pointer at the time of declaration, you
can assign NULL value. It will provide a better approach.

int *p= NULL; //initialize the pointer as null.

In the most libraries, the value of the pointer is 0 (zero).

// The example NULL pointer

#include <stdio.h>

int main()

{
// Null Pointer

int *ptr = NULL;

printf("\n The value of ptr is %p", ptr);

return 0;

Output:

The value of ptr is

2. Wild Pointer

A pointer which has not been initialized to anything (not even NULL) is known as wild pointer.

int *p; // by default garbage address

Program:

int main()

int *p; /* wild pointer */

int x = 10;

// p is not a wild pointer now

p = &x;

return 0;

Note: NULL vs Void Pointer – Null pointer is a value, while void pointer is a type

3. Dangling Pointers in C

Dangling pointer is a pointer pointing to a memory location that has been free (or deleted).

4. Void pointer

 Void pointer is a pointer which is not associate with any data types.
 It points to some data location in storage means points to the address of variables. It is also
called general purpose/universal pointer.

Syntax:

void *variable_name;

Ex: void *p;

Program:

#include<stdlib.h>

void main()

int x = 4;

float y = 5.5;

void *ptr; //A void pointer

ptr = &x;

printf("\n Integer variable is = %d\n", *( (int*) ptr) );

ptr = &y; // void pointer is now float

printf("\nFloat variable is= %f\n", *( (float*) ptr) );

Output:

Integer variable is = 4

Float variable is= 5.50000

2. Explain the concept of Pointer to Pointer with example.

Pointer to Pointer VARIABLE

The syntax of declaring a double pointer is given below.

int **p2; // pointer to a pointer which is pointing to an integer.


#include<stdio.h>

void main()

int number=50;

int *p;//pointer to int

int **p2;//pointer to pointer

p=&number;//stores the address of number variable

p2=&p;

printf("Address of number variable is %u \n",&number);

printf("Address of number variable is %x \n",p);

printf("Value of number variable is %d \n",*p);

printf("Address of p variable is %x \n",p2);

printf("Value of p variable is %d \n",**p2);

Output:

Address of number variable is fff4

Address of number variable is fff4

Value of number variable is 50

Address of p2 variable is fff2

Value of number variable is 50

3. Write a C Program to demonstrate Pointers to Arrays


#include <stdio.h>

void main()

int i;

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

int *p = a; // same as int*p = &a[0]

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

printf("%d\n", *p);

p++;

4. Write a C Program to demonstrate Pointers to Structures.

#include <stdio.h>

struct person

char name[30];

int age;

float weight;

};

void main()

struct person p, *p1;


p1 = &p; //pointer to structure

printf("Enter name:\n ");

scanf("%s", &p1->name);

printf("\nEnter age: ");

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

printf("\n Enter weight: ");

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

printf("\n Displaying person details:\n");

printf("\nName: %s", p1->name);

printf("\n Age: %d\n", p1->age);

printf("\n weight: %f\n", p1->weight);

Output:

Enter Name: Amit

Enter age: 21

Enter weight:61.5

Name: Amit

Age: 21

weight:61.5

5. Explain the concept of Self -referential -Structures with example.

Definition:
Self referential a structure definition which includes/contain at least one member that is a pointer to
the structure variable of same structure is called self referential structure

Syntax:

struct name

member 1;

member 2;

...

struct name *pointer;

};

Example:

Usage of self referential structures in linked list

 Self-referential structures are very useful in applications that involve linked data structures,
such as lists and trees.

 Static data structure such as array where the number of elements that can be inserted in the
array is limited by the size of the array.
 Self-referential structure can dynamically be expanded or contracted.

 Operations like insertion or deletion of nodes in a self- referential structure involve simple
and straight forward alteration of pointers.

Linked List (singly linked list)

A linear linked list illustration:

A linear linked list is a chain of structures where each node points to the next node to create a list.

To keep track of the starting node's address a dedicated pointer (referred as start pointer) is used.

The end of the list is indicated by a NULL pointer. In order to create a linked list of integers, we define
each of its element (referred as node) using the following declaration.

struct node_type

int data;

struct node_type *next;

};

struct node_type *start = NULL;

You might also like