Tuesday, November 5, 2024

Chapter : 4 Programming in C

LONG ANSWER QUESTIONS (8 MARKS)

1.    2081 Q. No. 16 Write a C program that uses structures to represent details of five books (title, author, publisher, and price) and prints them out. [8]

2.    2081 Q. No. 16 OR Discuss the concept of binary file handling in C programming and explain how putw() and getw() functions facilitate binary input/output operations. Give examples. [8]

3.    2080 GIE Set A Q. No. 16 What is a structure? Write a program to store five students' information (ID, Name, DOB, and phone) and display them using structure. [2+6]

4.    2080 GIE Set A Q. No. 16 OR What is a pointer? Write a program to read and write data from a file using file handling functions. [3+5]

5.    2080 GIE Set B Q. No. 16 Write a program to store five employees' records (EID, Name, Post, and Department) and display them using structure. [8]

6.    2080 GIE Set B Q. No. 16 OR Describe file handling modes in C. Write a C program to create and write data into a file.  [4+4]

7.    2080 Q. No. 16 Write the advantage of a pointer. Write a C program to enter the radius of a football and find the area of the football by using a user-defined function. [3+5]

8.    2080 Q. No. 16 OR Define the structure.   Write a C program using structure to input staff ID, name, and the salary of 50 staff. Display staff ID, name, and salary of those staff whose salary ranges from 25 thousand to 40 thousand. [2+6]

9.    2079 GIE Set A Q. No. Write a C program to enter name, grade, age, and address of 10 students in a structure and display the information. [8]

10.2079 GIE Set A Q. No. 16 OR Describe the file handling concept in C. Write a C program to enter names and addresses of the students and store them in a data file "student.dat". [3+5]

     ANS:




11.  2079 GIE Set B Q. No. 16 Define function. Write a program to generate the factorial of a given number using a recursive function in C programming. [3+5] 


Rules for Naming a Variable in C:

  1. Can only contain letters (A-Z, a-z), digits (0-9), and underscores (_).

    • student_age, num1, total_marks

    • student-age (hyphen not allowed)

  2. Must begin with a letter or an underscore (_), but not a digit.

    • _temp, data1

    • 1number (cannot start with a digit)

  3. Cannot be a C keyword (reserved word).

    • int, float, return (invalid because they are reserved words)

  4. Case-sensitive (uppercase and lowercase are different).

    • Total, total, and TOTAL are three different variables.

  5. Should not contain spaces.

    • studentMarks

    • student marks (space is not allowed)


4.2 Functions

4.2.1 Concept of library and user defined functions and advantages

 Function:

A function in C is a self-contained block of statements that performs a specific task. A function is executed when it is called in the program.

Advantages of Functions:

  1. Reusability: Use the same code multiple times.
  2. Modularity: Break the program into smaller parts.
  3. Easy Maintenance: Fix or update one function without affecting others.
  4. Clear and Readable: Makes the program easy to understand.

Differences Between Library Functions and User-Defined Functions in C

Aspect

Library Functions

User-Defined Functions

Definition

Predefined functions provided by C standard libraries, like <stdio.h> or <math.h>.

Functions created by the programmer to perform specific tasks.

Availability

Available by default in the C standard library; no need for user implementation.

Need to be defined by the user before being used.

Examples

printf(), scanf(), strlen(), sqrt().

int add(int a, int b).

Ease of Use

Easy to use; just include the required header file and call the function.

Requires time and effort to define and ensure correctness.

Customization

Not customizable; their behavior is predefined.

Fully customizable to meet the specific needs of a program.

Some important worked out examples:

Q1) WAP in C to find sum of two number(integer) using user defined function.


Q2) 
Write a C program to enter the radius of a football and find the area of the football by using a user-defined function.

 Q 3) Write a C program to enter an integer(number) and find whether that number is even or odd using a user-defined function.


Q4) Write a C program to enter an integer(number) and find whether that number is positive, negative or zero using a user-defined function.

4.2.5 Concept of Recursion: factorial and Fibonacci problems

A recursive function in C is a function that calls itself to solve a problem. It consists of two main parts: the base case and the recursive case as follows:
a) The base case is the condition that stops the recursion. It is the simplest form of the problem that can be solved directly without any further recursion. 
b) The recursive case is where the function calls itself with a modified version of the original problem.

Factorial of a given number using recursive function:

WAP in C to find the nth term of a Fibonacci series using recursive function:


WAP in C to generate Fibonacci series using recursive function:


4.3 Structure: Definition, Declaration, Initialization, Accessing, and Size of structure

A structure in C is a user-defined data type that allows grouping variables of different types under a single name. This helps to logically organize and manage related data. It is defined and declared using the ‘struct’ keyword followed by the structure name and a set of curly braces.

For example:

struct Student

{

    int id;

    float marks;

} s1;

 

Key Points about Structure:

1. Definition of Structure

The definition specifies the structure's layout, i.e., its members and their types.

Syntax:

struct StructureName

{

    dataType member1;

    dataType member2;

    ...

};

Example:

struct Student {

    int id;         

    float marks;    

};

 

2. Declaration of Structure

After defining a structure, we can declare variables of the structure type.

Syntax:

struct StructureName variableName;

Example:

struct Student s1;  

 

3. Initialization of Structure

We can initialize a structure during declaration or later in the program.

a. Initialization at Declaration:

Syntax:

struct StructureName variableName = {value1, value2, ...};

Example:

struct Student s1 = {101, 87.5};

b. Initialization After Declaration:

We can assign values to members individually:

s1.id = 101;

s1.marks = 87.5;

 

4. Accessing Members of a Structure

To access individual members of a structure, use the dot operator (.).

Syntax:

structureVariable.memberName

Example:

printf("ID: %d", s1.id);

printf("Marks: %.f", s1.marks);

 

5. Size of Structure

The size of a structure is determined by the sizes of its members and compiler-imposed padding for alignment.

Syntax:

sizeof(struct StructureName)

Example:

printf("Size of Student structure: %d bytes", sizeof(struct Student));


4.3 Union vs Structure in C:

Both unions and structures are user-defined data types in C that allow grouping of different data types. However, they have significant differences in how they store data and how their members are accessed.

Structures:

Ø  Definition: A structure is a user-defined data type that allows combining data items of different types.

Ø  Memory Allocation: Each member of a structure has its own memory location.

Ø  Size: The total size of a structure is the sum of the sizes of its members, including any padding bytes added for alignment.

Ø  Access: All members can be accessed individually and simultaneously.

Ø  Example:

struct Person {

    char name[50];

    int age;

    float height;

}s1;

Unions:

Ø  Definition: A union is a user-defined data type that allows storing different data types in the same memory location.

Ø  Memory Allocation: All members of a union share the same memory location. The size of a union is equal to the size of its largest member.

Ø  Size: The total size of a union is the size of its largest member.

Ø  Access: Only one member can be accessed at a time, as they share the same memory location.

Ø  Example:

union Data {

    int i;

    float f;

    char str[20];

}s1;

Some important worked out examples:

Q1) Write a C program that uses structures to represent details of five books (title, author, publisher, and price) and prints them out. 

1.    Q2) Write a C program using structure to input staff ID, name, and the salary of 50 staff. Display staff ID, name, and salary of those staff whose salary ranges from 25 thousand to 40 thousand. 


Q3) Write a C program to enter name, grade, age, and address of 10 students in a structure and display the information. 

Q4) Develop a program in C using structure to ask the information of any 12 students with roll number, name and marks scored in sub1, sub2, and sub3. Also, display them in proper format along with the calculation of total and percentage. [Note: the full mark of each subject is 100].

#include <stdio.h>
#include <conio.h>
struct student
{
    int rn;
    char name[20];
    int sub1, sub2, sub3;
    int total;
    float percent;
};
void main()
{
    struct student s[12];
    int i;
    clrscr();
    for (i = 0; i < 12; i++)
    {
printf("Roll Number: ");
scanf("%d", &s[i].rn);
printf("Name: ");
scanf("%s", s[i].name);
printf("Marks in Subject 1: ");
scanf("%d", &s[i].sub1);
printf("Marks in Subject 2: ");
scanf("%d", &s[i].sub2);
printf("Marks in Subject 3: ");
scanf("%d", &s[i].sub3);
s[i].total = s[i].sub1 + s[i].sub2 + s[i].sub3;
s[i].percent = s[i].total / 3.0;
    }
    printf("\nROLLNO\tNAME\tSUB1\tSUB2\tSUB3\tTOTAL\tPERCENTAGE");
    for (i = 0; i < 12; i++)
    {
printf("\n%d\t%s\t%d\t%d\t%d\t%d\t%f",
       s[i].rn, s[i].name, s[i].sub1, s[i].sub2, s[i].sub3, s[i].total, s[i].percent);
    }
    getch();
}

4.4 Pointers

In C programming, a pointer is a variable that stores the memory address of another variable. Instead of holding data directly, it holds the address of the variable where the data is stored.

Advantages of using pointers in C programming:

a)       Efficient Memory Management: Allows direct access to memory for dynamic allocation and deallocation.

b)      Pass-by-Reference: Enables functions to modify actual variable values, improving performance.

c)       Dynamic Data Structures: Essential for creating and managing structures like linked lists and trees.

d)    Memory Sharing: Allows multiple parts of a program to share and manipulate the same data.

e)    Faster Array Access

f)     Interfacing with Hardware

Key Points about Pointers:

Declaration: A pointer is declared by placing an asterisk * before the pointer variable name.

Syntax:

dataType *pointerName;

Example:

int *ptr;

This declares a pointer ptr that can point to an integer variable.

Initialization: A pointer is initialized with the address of a variable using the address-of operator &.

Example:

int x = 10;

int *ptr = &x;

Here, ptr holds the address of x.

Dereferencing: The value at the memory address pointed to by the pointer can be accessed using the dereference (indirection) operator *.

Example:

printf("%d", *ptr);                                                             

This prints the value of x, which is 10.

For Example:

Here’s a simple C program to find the sum of two numbers using pointers:

#include <stdio.h>    

#include <conio.h>    

void main()

{        

    int a, b, sum;

    int *ptr1 = &a;      // Declares a pointer to an integer and initializes it with the address of a.

    int *ptr2 = &b;      // Declares a pointer to an integer and initializes it with the address of b.

    clrscr();       

    printf("Enter first number: "); 

    scanf("%d", ptr1);              

    printf("Enter second number: ");       // Prints the prompt "Enter second number: " to the console.

    scanf("%d", ptr2);               // Reads an integer input from the user and stores it in the variable pointed to by ptr2 (b).

    sum = *ptr1 + *ptr2;        // Adds the values pointed to by ptr1 and ptr2, and stores the result in the variable sum.

    printf("The sum of %d and %d is: %d\n", *ptr1, *ptr2, result);       // Prints the sum of the two numbers to the console.

    getch();          

}

4.4.4 Call by value and Call by reference

Call by Value:

Ø  Definition: A method of passing arguments to a function where the actual value of the argument is copied to the function's parameter.

Ø  Effect: Changes made to the parameter within the function do not affect the original variable.

Ø  Usage: Suitable for small or simple data types where modifying the original data is not required.

Example: 

#include <stdio.h>

#include <conio.h>

void swap(int a, int b);         // Function declaration

void main() 

{

    int a, b;

    clrscr(); 

    printf("Enter 1st number: ");

    scanf("%d", &a);

    printf("Enter 2nd number: ");

    scanf("%d", &b);

    swap(a, b);                 // Call by value

    printf("\nValue of 1st number after swap: %d", a);

    printf("\nValue of 2nd number after swap: %d", b);

    getch();

}

void swap(int a, int b)     // Function definition

{

    int temp;

    temp = a;

    a = b;

    b = temp;

}


Call by Reference:

Ø  Definition: A method of passing arguments to a function where the reference (address) of the argument is passed to the function's parameter.

Ø  Effect: Changes made to the parameter within the function affect the original variable.

Ø  Usage: Suitable for large or complex data types where modifying the original data is required.

Example: 

#include <stdio.h>

#include <conio.h>

void swap(int *a, int *b);      // Function declaration

void main() 

{

    int a, b;  

    clrscr(); 

    printf("Enter 1st number: ");

    scanf("%d", &a);

    printf("Enter 2nd number: ");

    scanf("%d", &b);

    swap(&a, &b);             // Call by reference

    printf("\nValue of 1st number after swap: %d", a);

    printf("\nValue of 2nd number after swap: %d", b);

    getch(); 

}

void swap(int *a, int *b)       // Function definition

{

    int temp;

    temp = *a;

    *a = *b;

    *b = temp;

}


4.5   Working with File








#include <stdio.h>

#include <conio.h>

void main() {

    int num, i;

    FILE *fptr;

    clrscr();

    fptr = fopen("numbers.bin", "wb");

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

    {

        putw(i, fptr);

    }

    fclose(fptr);

    fptr = fopen("numbers.bin", "rb");

    printf("Numbers in the file:\n");

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

    {

        num = getw(fptr);

        printf("%d\n", num);

    }

    fclose(fptr);

    getch();

}

Explanation:

In this example:

  1. The file is opened in "wb+" mode for both writing and reading.
  2. The putw() function writes 10 integers (from 1 to 10) to the file.
  3. The file is reopened in "rb" mode for reading.
  4. The getw() function reads and prints the integers from the file.

This should give a clear demonstration of how putw() and getw() functions facilitate binary input/output operations.


Most Important worked out 

examples:

Q1) Write a program to create and write(store) data into a file.

                                                                       OR

        Write a program to enter name, roll number and age of a student and store them in a data 
         file "student.dat".

Ans: 


Q2) Write a program to read and display(print) data from a file.

                                                                                    OR

        Write a program to display name, age and roll number of student reading from a file   
        "student.dat".

Ans:


Q3) 
Write a program to enter name, age and roll number of 10 students and store them in file "student.dat". Read and display the content of the file in an appropriate format.
         Ans:

4) Write a program to enter name, age and roll number of the students (n students) and store them in file "student.dat". Read and display the content of the file in an appropriate format.
Ans:
5) Write a program to enter name, age and roll number of the students and store them in file "student.dat". The program should ask the user to continue or not (until the user say 'NO'). When finished, read and display the content of the file in an appropriate format.
Ans:


4.5.2Sequential and Random File:
In C programming, sequential and random access refer to different ways of accessing and manipulating files. 
1. Sequential Access:
Sequential access means reading or writing data in a sequential order from the start to the end of the file. This is useful for situations where the data is processed in the order it appears.
Functions used in sequential file are as follows:
fopen() - Opens the file.
fread() - Reads data from the file in sequence.
fwrite() - Writes data to the file in sequence.
fclose() - Closes the file when done.

2. Random Access:
Random access allows direct access to any part of the file without needing to read through other parts of it. This is helpful when you need to access or modify specific data within a file directly.
Functions used in random file are as follows:
fseek(FILE *file, long offset, int whence) - Moves the file pointer to a specific location.
ftell(FILE *file) - Returns the current position of the file pointer.
rewind(FILE *file) - Resets the file pointer to the beginning of the file.




THE END

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home