Chapter : 4 Programming in C
Rules for Naming a Variable in C:
-
Can only contain letters (A-Z, a-z), digits (0-9), and underscores (_).
-
✅
student_age,num1,total_marks -
❌
student-age(hyphen not allowed)
-
-
Must begin with a letter or an underscore (_), but not a digit.
-
✅
_temp,data1 -
❌
1number(cannot start with a digit)
-
-
Cannot be a C keyword (reserved word).
-
❌
int,float,return(invalid because they are reserved words)
-
-
Case-sensitive (uppercase and lowercase are different).
-
Total,total, andTOTALare three different variables.
-
-
Should not contain spaces.
-
✅
studentMarks -
❌
student marks(space is not allowed)
-
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:
- Reusability: Use
the same code multiple times.
- Modularity:
Break the program into smaller parts.
- Easy Maintenance: Fix
or update one function without affecting others.
- 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
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 the sum of the sizes of all its members (plus padding if any).
Syntax:
sizeof(struct StructureName)
Example:
printf("Size of Student structure: %d bytes", sizeof(struct
Student));
6. Array of Structure
An array of structure is a collection of structure variables of the same type.
Syntax:
s[3] is an array that can store 3 student records.id and marks.
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:
Ø 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 to store 10 student records with fields
for roll numbers, names, and marks in computer science. Process and display the
roll numbers, names, and marks of students.
Ans:
#include <stdio.h>
struct student
{
int rn, marks;
char name[20];
};
int main()
{
struct student s[10];
int i;
for (i = 0; i < 10; i++)
{
printf("\nEnter details for
Student %d:\n", i + 1);
printf("Enter
Roll Number: ");
scanf("%d",
&s[i].rn);
printf("Enter
Name: ");
scanf("%s",
s[i].name);
printf("Enter
Marks in Computer Science: ");
scanf("%d",
&s[i].marks);
}
printf("\nThe Detail of Students in
Tabular Form:\n");
printf("\nROLL
NO\tNAME\tMARKS");
for (i = 0; i < 10; i++)
{
printf("\n%d\t%s\t%d",
s[i].rn, s[i].name, s[i].marks);
}
return 0;
}
Example Output:
Enter details for Student 1
Enter Roll Number: 101
Enter Name: Madhav
Enter Marks in Computer Science: 99
.............
Enter Roll Number: 110
Enter Name: Ramesh
Enter Marks in Computer Science: 90
The Detail of Students in Tabular Form:
ROLL NO NAME MARKS
101 Madhav
99
........ …….. …
110 Ramesh 90
PQ) Write a C program that reads the account_number, name and address of ten customers from users and displays the account_number, name and address of these customers using Array and structure.
Q2) 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]
Ans:
#include <stdio.h>
struct staff
{
int id;
char name[30];
float salary;
};
int main()
{
struct staff
s[50];
int i;
for(i = 0; i <
50; i++)
{
printf("\nEnter details of staff %d\n", i + 1);
printf("Enter Staff ID: ");
scanf("%d", &s[i].id);
printf("Enter Name: ");
scanf("%s", s[i].name);
printf("Enter Salary: ");
scanf("%f", &s[i].salary);
}
printf("\nThe
Details of Staff with Salary between 25000 and 40000:\n");
printf("\nID\tNAME\tSALARY");
for(i = 0; i <
50; i++)
{
if(s[i].salary
>= 25000 && s[i].salary <= 40000)
{
printf("\n%d\t%s\t%.2f", s[i].id, s[i].name, s[i].salary);
}
}
return 0;
}
Example Output:
Enter details of staff 1
Enter Staff ID: 101
Enter Name: Ram
Enter Salary: 30000
..............
Enter details of staff 50
Enter Staff ID: 150
Enter Name: Sita
Enter Salary: 45000
The Details of Staff with Salary between 25000 and 40000:
ID NAME
SALARY
101 Ram
30000.00
...... ......
......
150 Hari
38000.00
PQ1) Create a structure to store the name and salary of 100 employees and display the names of the employee getting salary between 10000 and 25000.
PQ2) Write a C program using structure that reads the account_number, name and balance of ten customers from users and displays the details of those customers whose account contain more than 1 lakh.
Q3) 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].
Ans:
#include <stdio.h>
struct student
{
int roll;
char name[30];
int sub1;
int sub2;
int sub3;
int total;
float percentage;
};
int main()
{
struct student
s[12];
int i;
for(i = 0; i <
12; i++)
{
printf("\nEnter details of student %d\n", i + 1);
printf("Enter Roll Number: ");
scanf("%d", &s[i].roll);
printf("Enter Name: ");
scanf("%s", s[i].name);
printf("Enter Marks in Subject 1: ");
scanf("%d", &s[i].sub1);
printf("Enter Marks in Subject 2: ");
scanf("%d", &s[i].sub2);
printf("Enter Marks in Subject 3: ");
scanf("%d", &s[i].sub3);
s[i].total =
s[i].sub1 + s[i].sub2 + s[i].sub3;
s[i].percentage = (s[i].total / 300.0) * 100;
}
printf("\nThe
Details of Students with Total and Percentage:\n");
printf("\nROLL\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].roll,
s[i].name,
s[i].sub1,
s[i].sub2,
s[i].sub3,
s[i].total,
s[i].percentage);
}
return 0;
}
Example Output:
Enter details of student 1
Enter Roll Number: 101
Enter Name: Madhav
Enter Marks in Subject 1: 85
Enter Marks in Subject 2: 90
Enter Marks in Subject 3: 80
...............
Enter details of student 12
Enter Roll Number: 112
Enter Name: Ramesh
Enter Marks in Subject 1: 75
Enter Marks in Subject 2: 80
Enter Marks in Subject 3: 85
The Details of Students with Total and Percentage:
ROLL NAME SUB1 SUB2 SUB3 TOTAL PERCENTAGE
101 Madhav 85
90 80
255 85
...... ...... ......
..... ...... ...... .....
112 Ramesh 75
80 85
240 80
PQ) Write a program to enter the roll number, name and five subject marks of student and calculate and display total using structure.
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:
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:
- The file is opened in "wb+" mode for both writing and reading.
- The putw() function writes 10 integers (from 1 to 10) to the file.
- The file is reopened in "rb" mode for reading.
- 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.
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.
























