0% found this document useful (0 votes)
1 views15 pages

Pop Module 5 Answer

The document provides an overview of various programming concepts in C, including unions, structures, file handling, and pointers. It includes definitions, syntax, examples, and explanations of how to use these concepts effectively. Additionally, it contains sample programs demonstrating the implementation of these concepts in practical scenarios.

Uploaded by

sachinsbs1913
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)
1 views15 pages

Pop Module 5 Answer

The document provides an overview of various programming concepts in C, including unions, structures, file handling, and pointers. It includes definitions, syntax, examples, and explanations of how to use these concepts effectively. Additionally, it contains sample programs demonstrating the implementation of these concepts in practical scenarios.

Uploaded by

sachinsbs1913
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/ 15

POP MODULE 5 QUESTIONS WITH

ANSWERS

1. What is Union? Give it’s syntax differentiate Union


and Structure’s ?
Ans :
Union:- A union is a special data type available in C that allows to
store different data types in the same memory location.
Syntax :
union union_name {
datatype field_name;
datatype field_name;
// more variables
};

Difference between Structure and Union


Structure Union
Keyword The Keyword struct is used to The keyword union is used to
define the Structure define a union.
Size When a variable is associated when a variable is associated
with a structure, the compiler with a union, the compiler
allocates the memory for each allocates the memory by
member. The size of structure is considering the size of the
greater than or equal to the sum largest memory. So, size of
of sizes of its members. union is equal to the size of
largest member.
Memory Each member within a structure Memory allocated is shared by
is assigned unique storage area individual members of union.
of location.
Value Altering Altering the value of a member Altering the value of any of the
will not affect other members of member will alter other member
the structure. values.
Initialization of Several members of a structure Only the first member of a
Members can initialize at once. union can be initialized.

2. Explain with an example Array of Structure’s and


Array within Structure ?
Ans:
Array of Structures :
• It is a collection of structure variables
• Syntax:
struct tag_namestructure_variable[size];
• To store the information of 10 students consisting of name and
usn.
struct student
{
char name[30];
int roll_no;
float marks;
};
Example :

#include<stdio.h>
struct employee
{
char name[20];
float salary;
int empno;
};
void main()
{
struct employee e[10];
int n,i;
printf("Enter no.of employees\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter details of employee %d \n",i+1);
printf("Enter name, salary and employee_number\n");
scanf("%s%f%d",e[i].name,&e[i].salary,&e[i].empno);
}
for(i=0;i<n;i++)
{
printf("\nDetails of employee %d \n",i+1);
printf("Entered name salary and employee_number is:-
\n");
printf("%s\t%f\t%d",e[i].name, e[i].salary,e[i].empno);
}
}

3. Write a note on Structure’s and Function’s ?


Ans:
Definition of Structure :
Structure is a collection of elements of same or different data types
under a single name.

Structure Definition:
Syntax:
struct tagName
{
datatype member1;
datatype member2;
------------
------------
datatype membern;
};

Example :
struct employee
{
char name[20];
float salary;
int empno;
};

Structures and Functions :- Structures can be passed to


functions and returned from it. Passing structures to functions
can be done in the following ways
– Passing individual members
#include <stdio.h>

struct Rectangle {
int length;
int width;
};

void displayArea(int length, int width) {


int area = length * width;
printf("Area: %d\n", area);
}

int main() {
struct Rectangle rect = {10, 5};
displayArea(rect.length, rect.width); // Passing individual
members
return 0;
}

4. What is a File ? Explain different modes of File with


example .
Ans:
A file is a place on the disk where a group of related data is stored.

• Modes :
• Files in C can be opened in different modes using the fopen()
function, which specifies how the file will be accessed.
Text Modes:

1. "r": Open for reading. File must exist.


2. "w": Open for writing. If the file exists, it is cleared; otherwise, a
new file is created.
3. "a": Open for appending. Adds data to the end of the file.
Creates a new file if it doesn’t exist.
4. "r+": Open for both reading and writing. File must exist.
5. "w+": Open for reading and writing. Clears the file if it exists or
creates a new one.
6. "a+": Open for reading and appending. Adds data at the end of
the file.
Binary Modes:
Same as text modes but include "b" (e.g., "rb", "wb") to indicate
binary file handling.

Examples:
1. Write Mode ("w"):
FILE *file = fopen("example.txt", "w");
fprintf(file, "Hello, World!");
fclose(file);

2. Read Mode ("r"):


FILE *file = fopen("example.txt", "r");
char data[100];
fscanf(file, "%s", data);
printf("%s", data);
fclose(file);

3. Append Mode ("a"):


FILE *file = fopen("example.txt", "a");
fprintf(file, "\nAdding more text.");
fclose(file);

5. Write a C program to copy the content’s from one file


to another .
Ans:

#include <stdio.h>

int main() {
FILE *sourceFile, *targetFile;
char sourceFileName[100], targetFileName[100];
char ch;
printf("Enter the source file name: ");
scanf("%s", sourceFileName);
printf("Enter the target file name: ");
scanf("%s", targetFileName);
sourceFile = fopen(sourceFileName, "r");
if (sourceFile == NULL) {
printf("Error: Source file does not exist or cannot be
opened.\n");
return 1;
}
targetFile = fopen(targetFileName, "w");
if (targetFile == NULL) {
printf("Error: Target file cannot be opened or created.\n");
fclose(sourceFile);
return 1;
}
while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, targetFile);
}
printf("File copied successfully.\n");
fclose(sourceFile);
fclose(targetFile);
return 0;
}

Sample Input/Output:

Input:
Enter the source file name: source.txt
Enter the target file name: target.txt

Output:
File copied successfully.
1. Explain structure declaration and how structure
member are accessed with example?
Ans:
Declaration of a Structure :-
A structure is declared using the keyword struct followed by
structure name and variables are declared within a structure
The structure is usually declared before the main( ) function.
Syntax : -

struct structure_name
{
datatype member 1;
datatype member 2;
datatype member 3;
…………………..
…………………..
datatype member n;
};

Accessing Members of Structures:


• The member of structure is identified and accessed using the dot
operator(.)
• The link between a member and a variable is established using
the member operator ‘.’ which is also known as ‘dot operator’ or
‘period operator’.
Syntax is :
struct_variable.membername;

Example : Consider the structure definition and initialization as


shown below:
struct employee
{
char name[10];
float salary ;
int empno;
};
struct employee e = { “Raj”,1000,1};
e.name can access the string “Raj”
e.salary can access the value 1000
e.empno can access the value of 1

(OR)

#include<stdio.h>
struct employee
{
char name[20];
float salary;
int empno;
};
void main()
{
struct employee e;
printf("Enter name, number and salary of employee\n");
scanf("%s%d%f", e.name, &e.empno, &e.salary);
//reading details
printf("Entered name number and salary of employee is\n");
printf("%s \t%d \t%f", e.name, e.empno, e.salary); //
printing details
}

2. Implement a structure to read, write and compute


average marks and the student scoring above and
below average of class N students?
Ans:

#include <stdio.h>

struct Student {
char name[50];
int marks;
};

int main() {
int n, i;
float total = 0, average;

printf("Enter the number of students: ");


scanf("%d", &n);

struct Student students[n];

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


printf("Enter name of student %d: ", i + 1);
scanf("%s", students[i].name);
printf("Enter marks of %s: ", students[i].name);
scanf("%d", &students[i].marks);
total += students[i].marks;
}
average = total / n;
printf("\nAverage Marks: %.2f\n", average);

printf("\nStudents scoring above average:\n");


for (i = 0; i < n; i++) {
if (students[i].marks > average) {
printf("%s\n", students[i].name);
}
}

printf("\nStudents scoring below average:\n");


for (i = 0; i < n; i++) {
if (students[i].marks < average) {
printf("%s\n", students[i].name);
}
}

return 0;
}

Sample Input/Output:
INPUT:
Enter the number of students: 3
Enter name of student 1: Alice
Enter marks of Alice: 85
Enter name of student 2: Bob
Enter marks of Bob: 70
Enter name of student 3: Charlie
Enter marks of Charlie: 90

OUTPUT:
Average Marks: 81.67

Students scoring above average:


Alice
Charlie

Students scoring below average:


Bob

3. Explain fopen(), fclose(), fscanf(), and fprintf() with


syntax and example program considering all above
functions?
Ans:
fopen(): Creates a new file/Opens an existing file for use.
Syntax: FILE *fp;
fp = fopen(“filename”, “mode”);

fclose(): Closes a file which has been opened for use.


Syntax: fclose(file_pointer);

fscanf(): Reads a set of data values to a file.


Syntax: fscanf(fp, “control string”, list);

fprintf(): Writes a set of data values to a file


Syntax: fprintf(fp, “control string”, list);

Example Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
printf("Enter source file path: ");
scanf("%s", path);
file = fopen(path, "r");
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
characters = words = lines = 0;

while ((ch = fgetc(file)) != EOF)


{
characters++;

if (ch == '\n' || ch == '\0’)


lines++;
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0’)
words++;
}
printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
fclose(file);
return 0;
}

4. What are enumeration variable? How are they


declared?
Ans:
An enumeration variable is a user-defined data type in C that
consists of integral constants. It is used to assign names to a set of
related constants, making the code more readable and manageable.
Enumeration is declared using the enum keyword
Syntax:
enum EnumName {
constant1,
constant2,
constant3,
...
};

5. Define pointer. Explain pointer variable declaration and


initialization with suitable example .
Ans:
Pointer: - A pointer is a variable which holds address of another
variable or a memory-location

Declaration and Initialization of pointers :- The operators used


to represent pointers are
– Address Operator (&)
– Indirection Operator (*)

Syntax :-
ptr_data_type *ptr_var_name;
ptr_var_name = &var_name;
where var_name is a variable whose address is to be stored in the
pointer.

Example :-
int a=10;
int *ptr;
then
ptr = &a;
*ptr = a;

Here ptr is a pointer holding the address of variable ‘a’ and *ptr
holds the value of the variable a.

#include<stdio.h>
void main()
{
int *ptr;
int x=22;
printf("Addres of x= %d\n",&x);
printf("Content of x= %d\n",x);
ptr=&x; printf("Addres of pointer= %d\n",ptr);
printf("Content of pointer= %d\n",*ptr);
}

6. Develop a program using pointers to compute sum,


mean and standard deviation of all the elements stored
in an array.
Ans:
#include <stdio.h>
#include <math.h>

void calculateStats(int *arr, int size, double *sum, double


*mean, double *std_dev) {
double variance = 0;
for (int i = 0; i < size; i++) {
*sum += arr[i];
}
*mean = *sum / size;
for (int i = 0; i < size; i++) {
variance += pow(arr[i] - *mean, 2);
}
*std_dev = sqrt(variance / size);
}

int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);

int arr[n];
printf("Enter elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

double sum = 0, mean = 0, std_dev = 0;


calculateStats(arr, n, &sum, &mean, &std_dev);

printf("Sum: %.2lf\nMean: %.2lf\nStandard Deviation:


%.2lf\n", sum, mean, std_dev);
return 0;
}

- SACHIN
- MOHAMMED MAZZ
(E – section ACET)

You might also like