0% found this document useful (0 votes)
33 views33 pages

CP 3

The document is a question paper for a C programming course, featuring questions on various topics such as data types, operators, loops, structures, arrays, and functions. It includes both theoretical questions and practical programming tasks, such as calculating simple and compound interest and matrix multiplication. The paper is divided into two parts, with Part A containing short answer questions and Part B requiring detailed explanations and coding examples.

Uploaded by

Sathya
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)
33 views33 pages

CP 3

The document is a question paper for a C programming course, featuring questions on various topics such as data types, operators, loops, structures, arrays, and functions. It includes both theoretical questions and practical programming tasks, such as calculating simple and compound interest and matrix multiplication. The paper is divided into two parts, with Part A containing short answer questions and Part B requiring detailed explanations and coding examples.

Uploaded by

Sathya
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/ 33

22CS103 C PROGAMMING FOR ELECTRICAL ENGINEERS

3RD QUESTION PAPER APRIL-MAY 2024


Part A
2 Marks:
1) Differentiate between keywords and identifiers.

2) Define ternary operator in C.


The ternary operator, also known as the conditional operator, is a powerful tool in C
programming. The ternary operator takes three arguments: a conditional expression, a
result if the condition is True, and a result if the condition is False. The ternary
operator is represented by the “? :” symbol and can be used to simplify and make your
code more readable and efficient.
Syntax:
(<Exp –1 >?<Exp-2>:<Exp-3>);

3) State the use of preprocessor directive.


4) How can we initialize a string? Give an example.
Strings can be initialized directly by assigning a string literal to a char array.
For example: char greeting[] = "Hello, world!"

5) Compare library functions and user defined functions.

6) How do we create an array using pointer in C?


• When an array in declared, the complier allocates a base address and sufficient
amount of storage to contain all the elements of the array in contiguous memory
locations.
• The base address memory location 06 the first element (index 0) of the array.
• The complier also defines the Array name as a constant pointer to the first element.
• Eg: int x [5] = {1,2,3,4,5};

7) If we have structure B nested inside structure A, when do we declare structure


B?
When you have structure B nested inside structure A, you declare structure B before
you declare structure A. This is because when structure A contains structure B, the
compiler needs to know what structure B is before it can refer to it inside the
definition of A.
For Examle:
struct B {
int b;
};
struct A {
struct B b_instance;
int a;
};

8) Write syntax for union with an example.


Syntax:
union union_name {
datatype field_name;
datatype field_name;
// more variables
};

Eg:
union test {
Int x, y;
};

9) Mention the different methods of solving systems of equations.


• For small systems, Gaussian Elimination or Cramer's Rule is commonly used due to
their simplicity and directness.
• For larger systems, LU Decomposition or Iterative Methods are often more efficient.
• Matrix Inversion can be used but is computationally expensive for large systems.

10) What is simultaneous equation? Give an example.

• A simultaneous equation refers to a set of equations that are solved together because
they share common variables. The goal is to find values for these variables that satisfy
all the equations in the system simultaneously.

• In other words, a simultaneous equation is a system of equations where the unknowns


appear in more than one equation, and the solution is a set of values that satisfy each
equation at the same time.

For Example:
Linear simultaneous equations: The equations are linear, meaning each equation is of
the form ax+by+cz=dax + by + cz = dax+by+cz=d, where aaa, bbb, and ccc are
constants, and xxx, yyy, and zzz are the variables.
Non-linear simultaneous equations: The equations involve non-linear terms, such as
squares or higher powers of variables (e.g., x2+y2=1x^2 + y^2 = 1x2+y2=1).
Part B
16 marks:
11. a) i) Summarize various data types in C.
Data types:
Data type specifies which type of data that we are storing in a variable. There are 3 types of
data types.
⦁ Primary or primitive or fundamental data types
⦁ User defined data types
⦁ Derived data types

i) Primary data types:


There four fundamental data types.
⦁ Integer
⦁ Floating point
⦁ Character
⦁ Double precision floating point

Integer:
'C' provides three different classes of integers.
They are
⦁ int
⦁ short int
⦁ long int
Floating point types:
Floating point or real numbers are stored in 32 bits (on all 16 bit and 32 bit machines) with 6
bits precision.
3 classes of floating point types:
⦁ float
⦁ double
⦁ long double
Character types:
A single character can be defined as a character type data.
ii) User defined data types:
'C' supports a feature known as “type definition” that allows users to define an identifier that
would represent an existing data type.
The user defined data type identifier can later be used to declare variables. General form:
typedef type identifier
where type is any existing data type, identifier is a new name given to the data type.

iii) Derived data types:


Derived data types are those that are defined in terms of other data types, called base types.
Derived types may have attributes, and may have element or mixed content. Instances of
derived types can contain any well-formed XML that is valid according to their data type
definition. They may be built-in or user-derived.
Empty data set:
The void is an empty data type with no value or operations. This can be used in functions
and pointers.

ii) Illustrate different types of operators available in C programming with an example.


An Operator is a symbol that operates on a certain data type. The data items that
operators act upon are called operands. Some operators require two operands, some
operators act upon only one operand. In C, operators can be classified into various
categories based on their utility and action.
1. Arithmetic Operator 5. Increment & Decrement Operator
2. Relational Operator 6. Conditional Operator
3. Logical Operator 7. Bitwise Operator
4. Assignment Operator 8. Comma Operator
1. Arithmetic Operators

The Arithmetic operators performs arithmetic operations. The Arithmetic operators can
operate on any built in data type. A list of arithmetic operators are
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division and % Modulo division
2. Relational Operators

Relational Operators are used to compare arithmetic, logical and character expressions.
The Relational Operators compare their left hand side expression with their right hand
side expression. Then evaluates to an integer. If the Expressio is false it evaluate to
“zero”(0) if the expression is true it evaluate to “one”
Operator Meaning
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to
= = Equal to
! = Not Equal to
3. Logical Operators

A logical operator is used to evaluate logical and relational expressions. The logical
operators act upon operands that are themselves logical expressions. There are three
logical operators.
Operators Expression
&&Logical AND
||Logical OR
!Logical NOT
4. Assignment Operator
An assignment operator is used to assign a value to a variable. The most commonly used
assignment operator is =. The general format for assignment operator is : <Identifer> = <
expression >

5. Increment & Decrement Operator


The increment/decrement operator act upon a Single operand and produce a new value
is also called as “unary operator”. The increment operator ++ adds 1 to the operand and
the Decrement operator – subtracts 1 from the operand.

Syntax:
< operator >< variable name >;
The ++ or – operator can be used in the two
ways.

Example :

++ a; Pre-increment (or) a++ Post increment


—a; Pre-decrement (or) a— Post decrement

6. Conditional operator (or) Ternary operator (? :):


It is called ternary because it uses three
expression. The ternary operator acts like If-
Else construction.
Syntax:
( <Exp –1 > ? <Exp-2> : <Exp-3> );
7. Bit wise Operator

A bitwise operator operates on each bit of data. This bitwise operator can be divided into
three categories.
i. The logical bitwise operators.
ii. The shift operators
iii. The one’s complement operator.

8. Comma Operator
A set of expressions separated by using commas is a valid construction in c language.
Example :int i, j;

b) i) Discuss in detail about the looping statements using C programming.

Definition:
A loop is defined as a block of statements which are repeatedly executed for certain
number of times.
Terms used in loop:
• loop variable
• initialization
• test condition
• incrimination/decrimination
Loop variable: It is a variable used in the loop.
Initialization: It is the first step in which starting and final values is assigned to the
loop variable. Each time the updated value is checked by the loop itself.
Test condition: It is used to test the condition.
Incrimination/Decrimination: It is the numerical value added to or subtracted from the
variable in each round of the loop.
Two ways of loop control structures:

Entry controlled loop and Exit controlled loop Entry


Three types of loop control structures:

• For loop
• While loop
• Do-while loop

For loop:

• For loop allows to execute a set of instructions repeatedly until the certain
becomes false.
• Assigning variable values, incrementation or decrementation and condition
checking is done in for statement only, where as other control structures are not
offered all these features in one statement.
Syntax:

Eg:

........

........
int i, sum=0, n ;

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

sum = sum + i;

printf (“sum = %d”, sum);


}

........

........

Program: /* To find factorial for given number */

#include<stdio.h>
#include<conio.h
> main ( )
{
int n, fact=1,i; clrscr ( );
printf ("enter the number for factorial=");
scanf ("%d", &n);
for (i=1; i<=n; i++)
{
fact = fact*i;
}
printf ("The factorial is=%d", fact); getch();
}
Output:
Enter the number for factorial=5
The factorial is=120
While loop:
The while is an entry-controlled loop statement. The test-condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test-
condition is once again evaluated and if it is true, the body is executed once again. This
process of repeated execution of the body continues until the test-condition finally become
false and the control is transferred out of the loop. On exit, the program continues with the
statement immediately after the body of the loop.
Syntax:

Eg:
........

........

int n, sum=0, i =1;

printf (“Enter n numbers: ”);

scanf (“ %d”, &n );

while ( i <= n)

sum = sum +i;


i++;
}

printf (“\n Sum = %d\n”, sum );


........

........
Program: /* To find sum of individual digits */
#include<stdio.h>

#include<conio.h

> main()

int s,n=0,r;

clrscr();

printf("Enter a value ");

scanf("%d",&s); while(s!=0)

r=s%10;

n=n+r; s=s/10;

printf("Sum of digits = %d",n);


getch();

Output:

Enter a value 456 Sum of digits=15

Do-while loop:

• The do-while, the condition is checked at the end of the loop.


• The do-while loop will execute at least one time even if the condition is false initially.
• The do-while loop executes until the condition becomes false.
Syntax:

Eg:

........

........

do

printf (“ \n CSE is the best department “); i++;


}

while ( i<=5)

........

........

Program:

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

int main()
{
int a=0,b=1,c,s=0;
clrscr ( );
printf ( "Enter a value ");
scanf ("%d",&c);
printf ("%d %d ",a,b);
do
{
s=a+b;
a=b;
b=s;
printf (" %d ",s); s=a +b;

}
while (s<=c);
getch ( );
}
Output:
Enter a value 23 0 1 1 2 3 5 8 13 21

ii) Write a C program to calculate simple interest and compound interest


#include<stdio.h>
float Simple(float a,float b,float n)
{
float simple=0,i;
for(i=0;i<b;i++)
simple=simple+(a*(n/100)); //(p*t*r)/100 p-amount t-year r-percentage
return simple;
}
float Compound(float a,float b,float n)
{
float i,compound=0;
for(i=0;i<b;i++)
{
compound=compound+(a*(n/100)); //p(1+r)^t p-amount t-year r-percentage
a=a+(a*(n/100));
}
return compound;
}
int main()
{
float a,b,i,n;
int c;
printf("Enter the amount :");
scanf("%f",&a);
printf("Enter the year :");
scanf("%f",&b);
printf("Enter the percentage:");
scanf("%f",&n);
printf("\nSimple Interest =%.2f",Simple(a,b,n));
printf("\nCompound Interest=%.2f",Compound(a,b,n));
return 0;
}

Output:
Enter the amount :100000
Enter the year 10
Enter the percentage:12

Simple Interest =120000.00


Compound Interest=210584.81

12)a) i) Interpret how to declare and accessing an array element with an example.

Definition: An array is a collection of similar data types in which each element is located
in separate sequence memory location.
Characteristics of array:
Declaration int a [5] ---- > creation of 5 variables of integer types in the memory.
Instead of declaring five variables for five values, the programmer can define them in an
array.
All the elements of an array share the same name, and they distinguished from one
another with the help of an element number.
The elements in an array plays major role for calling each element.
Eg: int a[5] = {1,3,5,7,9};
Calling array elements
a [0] refers to 1st element i.e. 1
a [1] refers to 2nd element i.e. 3
a [2] refers to 3rd element i.e. 5
a [3] refers to 4th element i.e. 7
a [4] refers to 5th element i.e. 9
Any particular element of an array can be modified separately without disturbing other
elements.
int a[5] = {1,3,5,7,9};
if a programmer needs to replace 5 with 10, programmer need not require to
change all other numbers expects 5. To carry out this task the statement a[2] = 10 can be
used. Here, the other elements are not disturbed.

ii) Write a C program to find the product of the matrix.


#include <stdio.h>
void input(int d[3][3]) {
int i, j;
for(i = 0; i < 3; i++) { for(j
= 0; j < 3; j++) {
scanf("%d", &d[i][j]);
}
}
}

void main() {
int a[3][3], b[3][3], c[3][3], i, j, k;
printf("Enter the elements for matrix 1:\n"); input(a);
printf("Enter the elements for matrix 2:\n");
input(b);
for(i = 0; i < 3; i++) { for(j
= 0; j < 3; j++) {
int sum = 0;

for(k = 0; k < 3; k++) { sum


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

c[i][j] = sum;
}
}

printf("Multiplication of the given two matrices:\n");


for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", c[i][j]);
}

printf("\n");
}
}
Output:

Enter the elements for matrix 1:


123
234
345

Enter the elements for matrix 2:


234
567
123

Multiplication of the given two matrices:


15 21 27
23 32 41
31 43 55

b)i) Define sorting. State the differences between linear search and binary search.

Sorting is the process of arranging a collection of items (such as numbers, strings, or


objects) in a specific order. The most common orderings are:

1. Ascending order: Items are arranged from the smallest to the largest, such as numbers
sorted from least to greatest or words sorted alphabetically from A to Z.
2. Descending order: Items are arranged from the largest to the smallest, such as
numbers sorted from greatest to least or words sorted alphabetically from Z to A.
ii) Write a C program to count the number of characters, spaces, vowels, constants and
other using string functions.

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

{
char a[20],b[20]; int
i,n,v=0,c=0,s=0;
printf("Enter the string:");
scanf("%[^\n]%*c",a);
n=strlen(a);
strcpy(b,a);
strlwr(b);
for(i=0;i<n;i++)

{
if(b[i]=='a'||b[i]=='e'||b[i]=='i'||b[i]=='o'||b[i]=='u')
v++;
else if(a[i]==' ')
s++;
else
c++;

}
printf("\nNo of length in the string :%d",n);
printf("\nNo of characters in the string :%d",n-s);
printf("\nNo of spaces in the string :%d",s);
printf("\nNo of vowels in the string :%d",v);
printf("\nNo of consonants in the string :%d",c);
printf("\nLower of the string :%s",b);
printf("\nUpper of the string :%s",strupr(b));

}
Output:
Enter the string: book
No of length in the string 4
No of characters in the string 4
No of spaces in the string 0
No of vowels in the string 2
No of consonants in the string 2
Lower of the string : book
Upper of the string : BOOK

13) a) i)Explain the purpose of function prototype.


Function prototype is a declaration statement that identifies function with function
name, data type, a list of a arguments. All the function need to be declared before they
are used. (i.e. called)
Syntax: returntype functionname (parameter list);
• Return type data type of return value. It can be int, float, double, char, void etc.
• Function name - name of the function
• Parameter type list -It is a comma separated list of parameter types.
Example: int add(int a, int b);
Function declaration must be terminated with a semicolon (;).
Types of function prototypes:
1. Function with no arguments and no return values
2. Function with arguments and no return values
3. Function with arguments and one return values
4. Function with no arguments and with return values
Prototype 1: Function with no arguments and no return values
This function doesn't accept any input and doesn't return any result.
These are not flexible.
Program
#include<stdio.h>
#include<conio.h>
void show(); //function prototype
void main() {
show(); //function call
getch();
}
void show()//function definition
{
printf("Hai \n");
}
Output:
Hai

Prototype 2: Function with arguments and no return values


Arguments are passed through the calling function. The called function operates on the
values but no result is sent back.
Program
#include<stdio.h>
#include<conio.h>
void show(int);
void main()
{
int a;
printf("Enter the value for a \n");
scanf("%d", &a); show(a);
getch();
}
void show(int x)
{
printf("Value=%d", x);
}
Output:
Enter the value for a: 10
Value = 10

Prototype 3: Function with arguments and return values


Arguments are passed through the calling function The called function operates on the
values.
Program
#include<stdio.h>
#include<conio.h>
float circlearea(int);
void main()
{
int r;
float area;
printf("Enter the radius \n");
scanf("%d",&r);
area=circlearea(r);
printf("Area of a circle=%d\n", area);
getch();
}
int circlearea(int r1)
{
return 3.14* rl * rl;
}
Output:
Enter the radius 2
Area of circle = 12.000
Prototype 4: Function with no arguments and with return values
This function doesn't accept any input and doesn't return any result.
The result is returned back to the calling function.
Program
#include<stdio.h>
#include<conio.h>
float circlearea();
void main()
{
float area;
area=circlearea();
printf("Area of a circle=%d\n", area);
getch();
}
int circlearea()
{
int r=2;
return 3.14 * r* r;
}
Output:
Enter the radius 2
Area of circle = 12.000.
ii) Write a C program to compute the power of a given number using a (10) user-
defined function. The function should get the base and exponent values as inputs from
the user and return the value of the power of the base raised to the exponent value.
Program: #include
<stdio.h> #include
<math.h>
int power(int b,int e)
{

int i=0,r=1;
while(i<e)

r*=b;
i++;
}
return r;
}
void main()
{
int b,e;
printf("Enter the base and exponent:");scanf("%d,%d",&b,&e);
printf("Power of the given number:%d",power(b,e));
}
Output :

Enter the base and exponent:3,2


Power of the given number:9

b) i) Annotate pointer. Explain pointer arithmetic with relevant examples.


A Pointer is a derived data type in c. It is built from one of the fundamental data types
available in c.
Pointers contain memory address as their values.
Memory addresses are the locations in the computer memory where program instructions
and data are stored.
Pointer is a variable; its value is also stored in the memory in another location.
Computer system --- > 64 k memory. Start : 0 Last : 65535
Every byte has unique address, location have its own address number.

Eg:
int num = 134;
where,
num ---- > Variable
134 ---- > Value
5000 ---- > Address
Since a pointer is a variable it is value is also stored the memory in another location. Suppose
we assign the address of quantity to a variable p.

Variable Value Address

num 179 5000

P 5000 5048

In C/C++, a pointer is declared using the * operator, and it points to a variable of a specific
type:

int* ptr; // Pointer to an integer


Here, ptr is a pointer that can store the address of an int variable.
To assign an address to a pointer, the & operator (address-of operator) is used:

int a = 10;
int* ptr = &a; // ptr holds the address of a

To access the value stored at the address the pointer is pointing to, the * operator
(dereference operator) is used

int value = *ptr; // value = 10 (value at address ptr)

Pointer Arithmetic:
Pointer arithmetic involves manipulating the memory address stored in a pointer. You can
perform arithmetic operations like addition, subtraction, and comparison with pointers.
However, pointer arithmetic is done relative to the type the pointer is pointing to, rather than
directly on the memory address values.

Program:
#include<stdio.h>
int main ( )
{
int * p, sum, i;
int x [5] = { 5, 9, 6, 3, 7};
i= 0;
p = x;
printf(“Element Value Address /n /n “};
while (i <5)
{
printf(“ x [%d] %d %u /n”, i, *p, p);
i + +, p + +;
}
Output:
Element Value Address
X [0] 5 166
X [1] 9 168
X [2] 6 170
X [3] 3 172
X [4] 7 174

ii) Write a program to swap two numbers using call by value and call by reference.
Program:

#include <stdio.h>
void swap(int *a,int *b)
{

*a = *a + *b;

*b = *a - *b;

*a = *a - *b;
printf("\nAfter Swapping\na=%d\tb=%d",*a,*b);
}
void main()
{

int a,b;
printf("Enter the values of a and b:");scanf("%d,%d",&a,&b);
printf("Before Swapping\na=%d\t b=%d",a,b);
swap(&a,&b);
}

Output:

Enter the values of a and b:2,5


Before Swapping
a=2 b=5
After Swapping
a=5 b=2
14) a) i) How can we pass structures as parameters to functions? Illustrate with
an example.
1. Passing Structures by Value
When a structure is passed by value to a function, a copy of the entire structure is
created. Changes made to the structure inside the function will not affect the original
structure outside the function.
Example:
#include <stdio.h>

struct Person {
int age;
float height;
};
void printPersonInfo(struct Person p) {
printf("Age: %d, Height: %.1f\n", p.age, p.height);
// Modifying the structure inside the function
p.age = 30;
p.height = 6.0;
}

int main() {
struct Person person1 = {25, 5.9};
printPersonInfo(person1);
printf("After function call - Age: %d, Height: %.1f\n",
person1.age, person1.height);
return 0;
}
Explanation:
The structure person1 is passed to printPersonInfo() by value. This means that
the function works with a copy of person1, so modifications to p inside the function
do not affect the original person1.

2. Passing Structures by Reference (Using Pointers)


In C, structures are passed by reference using pointers. This allows the function to
modify the original structure, as the function works directly with the address of the
structure.
Example:
#include <stdio.h>

struct Person {
int age;
float height;
};
void modifyPersonInfo(struct Person* p) {
p->age = 35;
p->height = 6.2;
}

int main() {
struct Person person1 = {25, 5.9};
modifyPersonInfo(&person1);

printf("After function call - Age: %d, Height: %.1f\n",


person1.age, person1.height);

return 0;
}

Explanation:
The structure person1 is passed to modifyPersonInfo() by reference using a
pointer. The &person1 sends the memory address of person1, and the function can
modify the actual structure at that memory location. Inside the function, the arrow
operator (->) is used to access the structure's members and modify them.

3. Passing Structures by Reference (Using Reference Type — C only supports


pointers, not references)
In C, there's no concept of references as in C++ (i.e., you cannot pass a structure
directly as a reference). The only way to pass a structure by reference in C is by using
pointers, as demonstrated in the second example above.

ii) Create a structure called student that would contain name, regno and (10)
marks of five subjects and percentage. Write a C program to read the details of
name, regno and marks of five subjects for 30 students, calculate the percentage
and display the name, regno, marks of the subjects and percentage of each
student.

Program:
#include<stdio.h>
struct student

char name[20]; long


int regno;
int marks[5]; float
percentage;
};
void main()
{

int n,i,j;

printf("Enter the number of students:");scanf("%d",&n);


struct student s[n];
for(i=0;i<n;i++)
{

int sum=0;

printf("Enter the name of the student%d :",i+1);


getchar();
fgets(s[i].name,20,stdin);
printf("Enter the register number of the
student%d:",i+1);scanf("%ld",&s[i].regno);
for(j=0;j<5;j++)
{

printf("Enter the student%d mark%d :",i+1,j+1);


scanf("%d",&s[i].marks[j]);
sum+=s[i].marks[j];
}

s[i].percentage=(float)sum/5.00;
printf("\n");
}
for(i=0;i<n;i++)
{

printf("\n\nDetails of student%d",i+1);
printf("\nName :%sRegister Number:%ld",s[i].name,s[i].regno);
for(j=0;j<5;j++)
printf("\nMarks%d :%d",j+1,s[i].marks[j]);
printf("\nPercentage :%.2f%",s[i].percentage);
}
}

Output:

Enter the number of students:2


Enter the name of the student1 :Muthukumar
Enter the register number of the student1:2244035
Enter the student1 mark1 99
Enter the student1 mark2 99
Enter the student1 mark3 99
Enter the student1 mark4 99
Enter the student1 mark5 99

Enter the name of the student2 :Preethi


Enter the register number of the student2:2244041
Enter the student2 mark1 100
Enter the student2 mark2 100
Enter the student2 mark3 100
Enter the student2 mark4 100
Enter the student2 mark5 100

Details of student1
Name :Muthukumar
Register Number:2244035
Marks1 :99
Marks2 :99
Marks3 :99
Marks4 :99
Marks5 :99
Percentage :99.00

Details of student2
Name :Preethi
Register Number:2244041
Marks1 :100
Marks2 :100
Marks3 :100
Marks4 :100
Marks5 :100
Percentage :100.00

b) i) Interpret array of structures with relevant example.


We can also declare an array of structures.
Recall the syntax of an array:
type array_name[size];
type can any C type including struct type.

The array of structures can be simply manipulated as arrays of simple data types.

Example:

typedef struct

char name[20];

int age;
} person;

person class[5];

strcpy(class[0].name, “John”);

class[0].age = 19;

strcpy(class[1].name, “Sara”);

class[1].age = 18;

.name .age

class[0] John 19
class[1] Sara 18
class[2] David 20
class[3] Mary 21
class[4] Paul 18

Syntax:
To define an array of structures, first define the structure type, and then declare the
array of that type.
struct StructureName {
// Members of the structure
data_type member1;
data_type member2;
// Other members
};
// Declare an array of structures
struct StructureName arrayName[size];
Here, size represents the number of structures in the array.
Example:

#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};

int main() {
// Declare an array of 3 structures of type Person
struct Person people[3];

// Assign values to each element of the array (each structure)


// Person 1
strcpy(people[0].name, "Alice");
people[0].age = 25;
people[0].height = 5.5;

// Person 2
strcpy(people[1].name, "Bob");
people[1].age = 30;
people[1].height = 5.9;

// Person 3
strcpy(people[2].name, "Charlie");
people[2].age = 22;
people[2].height = 5.8;

// Access and print values for each structure in the array


for (int i = 0; i < 3; i++) {
printf("Person %d\n", i + 1);
printf("Name: %s\n", people[i].name);
printf("Age: %d\n", people[i].age);
printf("Height: %.2f\n\n", people[i].height);
}

return 0;
}

Output:
Person 1
Name: Alice
Age: 25
Height: 5.50

Person 2
Name: Bob
Age: 30
Height: 5.90

Person 3
Name: Charlie
Age: 22
Height: 5.80

ii) Write a C program to read and display the contents of a file.

#include <stdio.h>
int main()

FILE *fp;
char buffer[100];

fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("Reading content from the file:\n");
while (fgets(buffer, 100, fp) != NULL)

printf("%s", buffer);
}

fclose(fp); return
0;
}
Output:

The file is open successfully.

15. b) Develop a C program to compute numerical integration and numerical


differentiation using arrays.

#include <stdio.h>
#include <math.h>

float integrate(float a,float b,float c,float d)// coff power ul ll


{
float e;
if(b==0)
e=a*(c-d);
else
e=(a / (b+1) )*(pow((c),(b+1)) - pow((d),(b+1)));
return e;

}
float differentiate(float x,float h,float a,float b)
{

float e;
e=(a*(pow(h,b))-a*(pow(x,b)))/(h-x);
return e;
}

int main()
{

int n,c[n],i,a,ul,ll; float


s1=0,h,x,s2=0;
printf("Enter the degree of equation :");
scanf("%d",&n);
for(i=n;i>0;i--)
{

printf("Enter the x^%d coefficent :",i);scanf("%d",&c[i]);


}
printf("Enter the constant coefficent:");scanf("%d",&c[0]);
printf("Entered f(x)=");
for(i=n;i>1;i--)
printf("%dx^%d+",c[i],i);
printf("%dx+",c[1]);printf("%d",c[0]);

printf("\n1.Numerical Integration\n2.Numerical differentiation\nEnter your


choice:");scanf("%d",&a);
switch(a)
{

case 1:

printf("Enter the upper limit:");scanf("%d",&ul);


printf("Enter the lower limit:");scanf("%d",&ll);
for(i=n;i>=0;i--)
s1+=integrate(c[i],i,ul,ll);
printf("%.2f",s1);
break;
case 2:
printf("Enter the point 1:");scanf("%f",&x);
printf("Enter the point 2:");scanf("%f",&h);
for(i=0;i<=n;i++)

{
s2+=differentiate(x,h,c[i],i);
}

printf("Numerical differentiation for the given function is %.2f",s2);


break;
default:

printf("Invalid choice");
}
return 0;
}

Output 1:
Enter the degree of equation :3
Enter the x^3 coefficent :1
Enter the x^2 coefficent :2
Enter the x^1 coefficent :3
Enter the constant coefficent:4
Entered f(x)=1x^3+2x^2+3x+4
1.Numerical Integration
2.Numerical differentiation
Enter your choice:1
Enter the upper limit:1
Enter the lower limit:0
6.08
Output 2:
Enter the degree of equation :1 3
Enter the x^3 coefficent :1
Enter the x^2 coefficent :2
Enter the x^1 coefficent :3
Enter the constant coefficent:4
Entered f(x)=1x^3+2x^2+3x+4
1.Numerical Integration
2.Numerical differentiation
Enter your choice:2
Enter the point 1:1
Enter the point 2:2
Numerical differentiation for the given function is 16.00

a) Develop a C program to solve system of simple differential equations using arrays


and functions.

#include <stdio.h>

// Define the number of steps and the step size


#define STEPS 1000
#define STEP_SIZE 0.01

// Function definitions for the system of differential equations


// Example: dy1/dt = -y1 + y2
// Example: dy2/dt = -y2 + y1

// Derivative functions f1 and f2


double f1(double t, double y1, double y2) {
return -y1 + y2; // Example equation 1: dy1/dt = -y1 + y2
}

double f2(double t, double y1, double y2) {


return -y2 + y1; // Example equation 2: dy2/dt = -y2 + y1
}

// Euler's method to solve the system of ODEs


void solveSystem(double y1[], double y2[], double t[], int steps, double h) {
// Initial values of y1 and y2 at t = 0
y1[0] = 1.0; // Initial condition y1(0) = 1
y2[0] = 0.0; // Initial condition y2(0) = 0

// Iterate over the time steps to compute the solution


for (int i = 0; i < steps - 1; i++) {
t[i+1] = t[i] + h; // Update the time at the next step

// Update y1 and y2 using Euler's method


y1[i+1] = y1[i] + h * f1(t[i], y1[i], y2[i]);
y2[i+1] = y2[i] + h * f2(t[i], y1[i], y2[i]);
}
}

int main() {
// Declare arrays for y1, y2, and t (time)
double y1[STEPS], y2[STEPS], t[STEPS];

// Initial time value


t[0] = 0.0;

// Solve the system using Euler's method


solveSystem(y1, y2, t, STEPS, STEP_SIZE);

// Print the results


printf("Time\tY1\t\tY2\n");
for (int i = 0; i < STEPS; i++) {
printf("%.2f\t%.4f\t%.4f\n", t[i], y1[i], y2[i]);
}
return 0;
}

Output:
Time Y1 Y2
0.00 1.0000 0.0000
0.01 1.0000 0.0100
0.02 0.9999 0.0200
...
9.99 -0.1481 -0.1480

You might also like