0% found this document useful (0 votes)
10 views12 pages

Untitled Document

The document explains nested structures in programming, detailing types such as nested if-else statements, loops, and switch statements with examples. It also covers how to pass structures to functions in C, including passing by value and by reference, along with examples for each method. Additionally, the document describes file handling functions in C, command line arguments, and provides example programs for employee information storage, file creation and operations, and file content copying.

Uploaded by

2024cse.r229
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)
10 views12 pages

Untitled Document

The document explains nested structures in programming, detailing types such as nested if-else statements, loops, and switch statements with examples. It also covers how to pass structures to functions in C, including passing by value and by reference, along with examples for each method. Additionally, the document describes file handling functions in C, command line arguments, and provides example programs for employee information storage, file creation and operations, and file content copying.

Uploaded by

2024cse.r229
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/ 12

2)Explain nested structures with example

_Nested Structures:_

In programming, a nested structure refers to a structure or control statement that is placed


inside another structure or control statement. This allows for more complex logic and
decision-making processes.

_Types of Nested Structures:_

1. *Nested If-Else Statements*: An if-else statement is placed inside another if-else


statement.
2. *Nested Loops*: A loop is placed inside another loop.
3. *Nested Switch Statements*: A switch statement is placed inside another switch
statement.

_Example 1: Nested If-Else Statements_

Suppose we want to determine the grade of a student based on their score.


```
if (score >= 90) {
if (score >= 95) {
printf("Grade: A+\n");
} else {
printf("Grade: A\n");
}
} else if (score >= 80) {
printf("Grade: B\n");
} else {
printf("Grade: C\n");
}
```
In this example, the inner if-else statement checks if the score is greater than or equal to 95,
and if so, prints "Grade: A+". If not, it prints "Grade: A".

_Example 2: Nested Loops_

Suppose we want to print a matrix of numbers.


```
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) {
printf("%d ", i * j);
}
printf("\n");
}
```
In this example, the inner loop prints the numbers from 1 to 3, multiplied by the current row
number. The outer loop iterates over the rows.
_Example 3: Nested Switch Statements_

Suppose we want to determine the type of vehicle based on its make and model.
```
switch (make) {
case "Toyota":
switch (model) {
case "Camry":
printf("Vehicle type: Sedan\n");
break;
case "Corolla":
printf("Vehicle type: Compact Car\n");
break;
default:
printf("Unknown model\n");
}
break;
case "Honda":
switch (model) {
case "Civic":
printf("Vehicle type: Compact Car\n");
break;
case "Accord":
printf("Vehicle type: Sedan\n");
break;
default:
printf("Unknown model\n");
}
break;
default:
printf("Unknown make\n");
}
```
In this example, the inner switch statement checks the model of the vehicle, based on the
make. If the make is Toyota, it checks if the model is Camry or Corolla. If the make is Honda,
it checks if the model is Civic or Accord.
3) Describe how to pass structure to function with a example
_Passing a Structure to a Function:_

In C programming, a structure can be passed to a function in two ways:

1. *Passing by Value:* The entire structure is passed to the function, and any changes made
to the structure within the function do not affect the original structure.
2. *Passing by Reference:* A pointer to the structure is passed to the function, and any
changes made to the structure within the function affect the original structure.

_Example: Passing a Structure by Value_


```
#include <stdio.h>

// Define a structure
struct Student {
char name[50];
int age;
float marks;
};

// Function to display student information


void displayStudent(struct Student s) {
printf("Name: %s\n", s.name);
printf("Age: %d\n", s.age);
printf("Marks: %.2f\n", s.marks);
}

int main() {
// Create a structure variable
struct Student student1 = {"John Doe", 20, 85.50};

// Pass the structure to the function by value


displayStudent(student1);

return 0;
}
```

In this example, the `displayStudent` function takes a `struct Student` as an argument and
displays the student's information. The `student1` structure is passed to the function by
value, which means that a copy of the structure is created and passed to the function.

_Example: Passing a Structure by Reference_

```
#include <stdio.h>

// Define a structure
struct Student {
char name[50];
int age;
float marks;
};

// Function to display and modify student information


void modifyStudent(struct Student *s) {
printf("Original Name: %s\n", s->name);
strcpy(s->name, "Jane Doe"); // Modify the name
printf("Modified Name: %s\n", s->name);
}

int main() {
// Create a structure variable
struct Student student1 = {"John Doe", 20, 85.50};

// Pass the structure to the function by reference


modifyStudent(&student1);

return 0;
}
```

In this example, the `modifyStudent` function takes a pointer to a `struct Student` as an


argument. The function displays the original name, modifies the name, and displays the
modified name. The `student1` structure is passed to the function by reference using the
address-of operator `&`. Any changes made to the structure within the function affect the
original structure.

fopen(),fgets(),fput()
Here's an explanation of the file handling functions `fopen()`, `fgets()`, and `fputs()`:

fopen()
The `fopen()` function is used to open a file in a specific mode. It returns a file pointer that
can be used to perform various file operations.

_Syntax:_ `FILE *fopen(const char *filename, const char *mode)`

- `filename`: The name of the file to be opened.


- `mode`: The mode in which the file should be opened. Some common modes are:
- `r`: Open the file for reading.
- `w`: Open the file for writing. If the file already exists, its contents will be deleted.
- `a`: Open the file for appending. If the file already exists, new data will be added to the
end of the file.
- `r+`: Open the file for both reading and writing.
- `w+`: Open the file for both reading and writing. If the file already exists, its contents will
be deleted.
- `a+`: Open the file for both reading and appending. If the file already exists, new data will
be added to the end of the file.

_Return Value:_ If the file is opened successfully, `fopen()` returns a file pointer. Otherwise, it
returns `NULL`.

fgets()
The `fgets()` function is used to read a line of text from a file.

_Syntax:_ `char *fgets(char *str, int n, FILE *stream)`


- `str`: The array where the line of text will be stored.
- `n`: The maximum number of characters that can be read, including the null character.
- `stream`: The file pointer from which the line of text will be read.

_Return Value:_ If a line of text is read successfully, `fgets()` returns the `str` pointer.
Otherwise, it returns `NULL`.

fputs()
The `fputs()` function is used to write a string of text to a file.

_Syntax:_ `int fputs(const char *str, FILE *stream)`

- `str`: The string of text to be written to the file.


- `stream`: The file pointer to which the string of text will be written.

_Return Value:_ If the string of text is written successfully, `fputs()` returns a non-negative
value. Otherwise, it returns `EOF`.

Here's an example code snippet that demonstrates the use of these functions:
```
#include <stdio.h>

int main() {
FILE *file = fopen("example.txt", "w+");
if (file == NULL) {
perror("Error opening file");
return 1;
}

char str[] = "Hello, World!";


fputs(str, file);

rewind(file);

char buffer[20];
fgets(buffer, sizeof(buffer), file);
printf("Read line: %s\n", buffer);

fclose(file);
return 0;
}
```
This code opens a file, writes a string of text to the file using `fputs()`, reads a line of text
from the file using `fgets()`, and prints the read line to the console.

[Explain about command line argument with example


Command Line Arguments:_

Command line arguments are values passed to a program when it is executed from the
command line. These arguments can be used to customize the behavior of the program,
provide input data, or specify options.

_Command Line Argument Syntax:_

The syntax for passing command line arguments to a program is as follows:

```
program_name argument1 argument2 ... argumentN
```

- `program_name` is the name of the executable program.


- `argument1`, `argument2`, ..., `argumentN` are the command line arguments passed to the
program.

_Accessing Command Line Arguments in C:_

In C, command line arguments can be accessed using the `argc` and `argv` parameters of
the `main()` function.

- `argc` (argument count) is an integer that represents the number of command line
arguments passed to the program, including the program name.
- `argv` (argument vector) is an array of character pointers that contains the command line
arguments as strings.

_Example Program:_
```
#include <stdio.h>

int main(int argc, char *argv[]) {


printf("Number of arguments: %d\n", argc);

for (int i = 0; i < argc; i++) {


printf("Argument %d: %s\n", i, argv[i]);
}

return 0;
}
```
_Let's Compile and Run the Program:_

Compile the program using the command:


```
gcc program.c -o program
```
Run the program with some command line arguments:
```
./program hello world 123
```
_Output:_
```
Number of arguments: 4
Argument 0: ./program
Argument 1: hello
Argument 2: world
Argument 3: 123
```
In this example, the program prints the number of command line arguments and each
argument as a string. The `argc` variable represents the number of arguments, and the
`argv` array contains the arguments as strings.
[12/25, 1:03 PM] M N CHETHAN: Write a c program to store and retrieve 3 employees
information using structures
[12/25, 1:03 PM] Meta AI: Here is a simple C program that uses structures to store and
retrieve information about 3 employees:

```
#include <stdio.h>
#include <string.h>

// Define a structure for employee information


struct Employee {
char name[50];
int age;
float salary;
};

int main() {
// Declare an array of 3 Employee structures
struct Employee employees[3];

// Function to input employee information


void inputEmployee(struct Employee *emp) {
printf("Enter name: ");
fgets(emp->name, sizeof(emp->name), stdin);
emp->name[strcspn(emp->name, "\n")] = 0; // Remove newline character

printf("Enter age: ");


scanf("%d", &emp->age);
getchar(); // Consume newline character

printf("Enter salary: ");


scanf("%f", &emp->salary);
getchar(); // Consume newline character
}

// Function to display employee information


void displayEmployee(struct Employee emp) {
printf("Name: %s\n", emp.name);
printf("Age: %d\n", emp.age);
printf("Salary: %.2f\n", emp.salary);
}

// Input employee information


for (int i = 0; i < 3; i++) {
printf("Enter information for Employee %d:\n", i + 1);
inputEmployee(&employees[i]);
}

// Display employee information


printf("\nEmployee Information:\n");
for (int i = 0; i < 3; i++) {
printf("Employee %d:\n", i + 1);
displayEmployee(employees[i]);
printf("\n");
}

return 0;
}
```

Here's a breakdown of the program:

1. We define a `struct Employee` to store information about each employee, including their
name, age, and salary.
2. We declare an array `employees` to store information about 3 employees.
3. We define two functions: `inputEmployee` to input employee information and
`displayEmployee` to display employee information.
4. We use a loop to input information for each employee using the `inputEmployee` function.
5. We use another loop to display the information for each employee using the
`displayEmployee` function.

When you run this program, it will prompt you to input information for 3 employees and then
display the information for each employee.

.Write a c program to create a new file and perform write and read operations

Here is a simple C program that creates a new file, writes data to it, and then reads the data
back from the file:

```
#include <stdio.h>
#include <stdlib.h>

int main() {
// Create a new file
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
perror("Error creating file");
return 1;
}

// Write data to the file


char *data = "Hello, World!";
fprintf(file, "%s\n", data);

// Close the file


fclose(file);

// Open the file for reading


file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file for reading");
return 1;
}

// Read data from the file


char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}

// Close the file


fclose(file);

return 0;
}
```

Here's a breakdown of the program:

1. We include the necessary header files, `stdio.h` and `stdlib.h`.


2. We create a new file called `example.txt` using the `fopen` function in write mode (`"w"`).
3. We write the string `"Hello, World!"` to the file using the `fprintf` function.
4. We close the file using the `fclose` function.
5. We reopen the file in read mode (`"r"`).
6. We read the data from the file using the `fgets` function and store it in a buffer.
7. We print the data from the buffer to the console.
8. We close the file again.
When you run this program, it will create a new file called `example.txt`, write the string
`"Hello, World!"` to it, and then read the data back from the file and print it to the console.

.Write a c program to copy the content of one file to another file

Here is a simple C program that copies the content of one file to another file:

```
#include <stdio.h>
#include <stdlib.h>

int main() {
// File names
char sourceFile[100];
char destinationFile[100];

// Prompt user for file names


printf("Enter source file name: ");
scanf("%s", sourceFile);
printf("Enter destination file name: ");
scanf("%s", destinationFile);

// Open source file in read mode


FILE *source = fopen(sourceFile, "r");
if (source == NULL) {
perror("Error opening source file");
return 1;
}

// Open destination file in write mode


FILE *destination = fopen(destinationFile, "w");
if (destination == NULL) {
perror("Error opening destination file");
fclose(source);
return 1;
}

// Copy content from source file to destination file


char c;
while ((c = fgetc(source)) != EOF) {
fputc(c, destination);
}

// Close files
fclose(source);
fclose(destination);
printf("File copied successfully!\n");

return 0;
}
```

Here's a breakdown of the program:

1. We include the necessary header files, `stdio.h` and `stdlib.h`.


2. We prompt the user to enter the names of the source and destination files.
3. We open the source file in read mode (`"r"`).
4. We open the destination file in write mode (`"w"`).
5. We copy the content from the source file to the destination file using a loop that reads
each character from the source file and writes it to the destination file.
6. We close both files.
7. We print a success message to the console.

When you run this program, it will prompt you to enter the names of two files. It will then
copy the content of the first file to the second file.

10 What is a structure? Explain the definition, initialization and accessing of structure


variables

What is a Structure?*

In C programming, a structure (also known as a struct) is a collection of variables of different


data types that are stored together in memory. A structure allows you to group related
variables together, making it easier to organize and manipulate data.

*Definition of a Structure*

A structure is defined using the `struct` keyword followed by the name of the structure and
the variables that make up the structure. The general syntax is:
```
struct structure_name {
data_type variable1;
data_type variable2;
...
data_type variableN;
};
```
For example:
```
struct Person {
int age;
char name[20];
float height;
};
```
*Initialization of Structure Variables*

Structure variables can be initialized in several ways:

1. *Direct Initialization*: You can initialize structure variables directly when you declare them.
```
struct Person person = {25, "John Doe", 175.5};
```
1. *Initialization using Designated Initializers*: You can use designated initializers to initialize
specific members of the structure.
```
struct Person person = {.age = 25, .name = "John Doe", .height = 175.5};
```
1. *Initialization using a Function*: You can write a function that initializes the structure
variables.
```
void initPerson(struct Person *p) {
p->age = 25;
strcpy(p->name, "John Doe");
p->height = 175.5;
}

struct Person person;


initPerson(&person);
```
*Accessing Structure Variables*

You can access structure variables using the dot (`.`) operator or the arrow (`->`) operator.

1. *Dot Operator*: Use the dot operator to access structure variables when you have a
structure variable.
```
struct Person person;
person.age = 25;
```
1. *Arrow Operator*: Use the arrow operator to access structure variables when you have a
pointer to a structure.
```
struct Person person;
struct Person *p = &person;
p->age = 25;
```
In summary, structures are a way to group related variables together in C programming. You
can define a structure, initialize its variables, and access them using the dot or arrow
operator.

You might also like