0% found this document useful (0 votes)
87 views159 pages

Chapter 4 - Programming in C

Uploaded by

Biplove Pokhrel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
87 views159 pages

Chapter 4 - Programming in C

Uploaded by

Biplove Pokhrel
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 159

Chapter 4: Programming in

By
Er. Raj Kiran Chhatkuli
What is C?
• C is a high level language and there is no need for any architecture
knowledge; it’s in normal English form.
• C is a compiler because it can translate the whole program at a time so
we can call it a compiler.
• C is structured programming language.
• It is called also procedural oriented programming language, function
oriented language, module programming language.
• It is simple, reliable and easy to use.
Features of C
• C is a computer language and a programming tool which has grown popular
because programmers preferred it. It is a tricky language but a masterful one.
The C programming languages has the following features:
i) It has small size.
ii) It has extensive use of function call.
iii) It is a strong structural language having powerful data definition methods.
iv) It has low level (Bit Wise) programming available.
v) It can handle low level activities.
vi) Pointer makes it very strong for memory manipulations.
vii) It has level constructors.
viii) It can produce efficient programs.
ix) It can be complied on variety of computers.
Advantages and Disadvantages
Advantage
• It is machine independent programming language.
• It is easy to learn and implement C language.
• It can be implemented from mobile device to mainframe computers.
• It is the mother of all modern programming language.
Disadvantage
• There is no runtime checking.
• It has poor error detection systems.
• On large programs, it is hard to fix errors.
• It does not support modern programming methodologies oriented programming
language.
Preprocessor and its types
• The compiler of C has a preprocessor built into it.
• Lines that begin with # are called pre-processor directives.
• Each C program must start with proper header files (i.e.) starting with
'#', sign, 'include' and a header file name enclosed within triangle
brackets.
Header file
• A file that is defined to be included at the beginning of a program in C
language that contains the definitions of data types and declarations of
variables used by the functions in the program is called header file.
• Header files commonly contain forward declarations of classes, subroutines,
variables, and other identifiers.
• The header file in c is called standard library functions.
• The entire header file has the extension .h
• A header file is used to define constants, variables, macros and functions that
may be common to several applications.
• The updating and reading data of any function can be performed by using the
header files.
Header File Description Main Functions
stdio.h Standard input and output fpen(), fclose(), rename(), gets(), puts(), getchar(),
scanf(), printf() etc.

conio.h Old MS-DOS compiler header file, used for getch(), getche()
console input & output.

math.h Mathematical calculation in C program. sin(x), cos(x), log(x), pow(x,2), sqrt(x), cbrt(x),
ceil(x), floor(x) etc.

complex.h Complex arithmetic cpow(x,p), csqrt(x), ctan(x), ctanh(x), cabs(x)

string.h String / Words manipulation function strlen(y), strcpy(z,y), strcmp(z,y), strcat(z,y),


strupr(y), strlwr(y) etc.

ctype.h Character manipulation type header file toupper(y), tolower(y), isupr(y), isspace(),
isalnu(y), toascii(y) etc.

stdlib.h General purpose standard library. rand(), malloc(), calloc(), abort(), exit() abs(),
free() etc.
Character set used in C
• A group of alphabetic, numeric and other characters that have some
relationship with C programming language and recognized by
compiler is called Character set.
Identifiers
Identifiers can be defined as the name of the variables, functions, arrays,
structures etc created by the programmer. They are the fundamentals
requirement of any language. The identifiers are defined according to
the following rules:
• Identifiers consists letters and digits.
• First character must be an alphabet or underscore.
• Upper case and lowercase are allowed but not same, i.e. Text not same
as text.
• Only one special character underscores (_) will used. For example, int
a_b; Where a and _b are valid identifiers.
Keywords
Keywords are the reserved words which have standard, predefined
meaning in C language. Keywords cannot be used as names for the
variables or other user defined program elements. There are 32
keywords available in C. common examples are as follows.
Tokens
• In a C source code, the basic element recognized by the compiler is
known as tokens. A token is source program text that the compiler
does not break down into components elements.
• The keywords like int, float, if, for etc.
• Identifiers like main, printf, void etc.
• Constants like a,b,c etc.
• String literals like name, address, phone etc.,and
• Operators like &&, ! etc.
• Punctuation characters such as [ , ] , { , } , ( , ) , ; , : are also tokens.
Data types
• It is the set of keywords to declare variables.
• A set of data that specifies the possible range of values in a program
and stored in memory are called data types.
• Data types are used to define variables before use it.
Variable
• Variable are simply names that can change the value while executing a program.
• It allocates memory space inside a memory of computer.
• A variable can have only one value assigned to it in every time of execution of
the program. Its value can change in different executions.
Rules for variable declaration
• They must always begin with a letter, although some systems permit underscore
as the first character.
• White space is not allowed.
• A variable should not be a keyword
• It should not contain any special characters.
Types of variable
Numeric Variable:
• The variable that store numeric data only is called numeric variable.
The numeric data may be whole number or fractional number. Examples
are integer, floating point and double.
String Variable:
• The variable that stores character data only is called string variable.
• The string data may be single character or string.
• Examples are character, array of character (string), table of string.
Constant variable
• A constant is fixed entity.
• It does not change its value during the entire program execution.
Constants can be classified as:
1. Integer constants
2. Floating point constants
3. Character constants
4. String constants
5. Symbolic Constants
6. Escape sequence constants
Specifier
• The input and output data are formatted by specific pattern. These
Patterns are generated by using specific tokens in C programs. These
tokens used to format data are called specifier. Most of the specifier
used by printf and scanf functions. Types of mostly used specifier are
explained below.
• Escape Sequence: They are a type of specifier. These non printable
characters are used to format text on the output screen. These escape
sequence character are place after backslash \.
Format Specifier
• The output and input data are display and receive in specific pattern.
Format specifier uses the token % and character(s) after it. It is used to
format for all types of data i.e. integer, float, character and string
Operator
• An operator is a symbol that operates on a certain data type.
• The operator generally remains between the two operands.
• An expression is a combination of variables, constants, and operators
written according to the syntax of the language.
• The data items that operators act upon are called operands.
Types of operator
1. Arithmetic Operator(Binary Operator)
2. Relational Operator (Comparison Operator)
3. Logical Operator (Boolean Operator)
4. Assignment Operator
5. Increment and Decrement Operators (Unary Operator)
6. Conditional Operator (Ternary Operator)
7. Bitwise Operator
8. Comma Operator
9. Size of Operator
Library function
• The special functions that are well defined in C programming
languages are called library functions such as printf(), scanf(),strlen(),
sqrt(), tolower(), toupper(), getchar(), putchar() etc.
Control structures
• Control structures are those programming constructs which control the
flow of program statements execution in a program.
• Types of Control Structure
i) Branching / Decision ( Selective Control Structure)
ii) Looping (Repetitive Control Structure)
iii) Jumping (Unconditional Control Structure)
Decision (Selective) Control Structure
• It is mainly used for decision making. It is also called conditional statements.
• Selection is made on the basis of condition. We have options to go when the given
condition is true or false. The flow of program statements execution is totally directed
by the result obtained from checking condition.
Types
a) Conditional Statements
i. if statements:
• It is used to execute an instruction or block of instructions only if a condition is fulfilled.
Syntax:
if(condition) {
Statements;
}
WAP to read a number and find even or odd
by using if().
#include<stdio.h>
#include<conio.h>
void main() {
int a,r;
printf("enter the number");
scanf("%d",&a);
r=a%2;
if(r==0){
printf("number is even %d",a);
}
if(r!=0) {
printf("number is odd %d",a);
}
getch();
}
ii) if else statements
• If the condition is true then the if() portion statements are evaluated
otherwise else part of the statements are evaluated.
Syntax:
if( condition){
Block of statements;
}
else{
Block of statements;
}
WAP input any two numbers and display the
largest one.
#include<stdio.h>
#include<conio.h>
void main(){
int a,b;
printf("enter the number");
scanf("%d",&a);
printf("enter the number");
scanf("%d",&b);
if(a>b){
printf("A is greatest number",a);
}
else{
printf("B is greatest number",b);
}
getch();
}
iii) if() else if() statements

• When we have two or more condition to be checked in a series we can use if else if
statement. It is also known as multiple conditional statement or multipath conditional
statement /if else ladder.
Syntax:
if(condition 1){
Statements 1; }
else if(condition 2) {
Statement 2; }
else if(condition n-1) {
Statement n-1; }
else {
Statement n; }
}
WAP to find the largest number among three
input number .
#include<stdio.h>
#include<conio.h>
void main(){
int a,b,c;
printf("\n Enter any three number");
scanf("%d",&a,&b,&c);
if(a>b&&a>c){
printf("\n Largest number is %d",a); }
else if(b>a&&b>c){
printf("\n Largest number is %d", b); }
else{
printf("\n Largest number is %d",c); }
getch(); }
iv. Nested if else statements
• An entire if else statement written within the body of if part or else part of another if else statement is
called nested if else statement. It is used when a condition is to be checked inside another condition at a
time in the same program to make decision.
Syntax,
if(condition 1){
if(condition 2){
Statements 1; }
else {
Statements 2; }
}
else {
Statement 3;
}
• WAP that reads marks of five subject and calculate total mark and
percentage. Also awards the division on the basis of following criteria.

Percentage division
p>=75 distinction
p>=60 and <75 first
p>=45 and <60 second
p>=35 and <45 third
otherwise failed
#include<stdio.h>
#include<conio.h>
void main() {
int eng,nep,comp,acc,eco,total;
Float per;
printf("Enter the five subject mark");
scanf("%d %d %d %d %d",&eng,&nep,&comp,&acc,&eco);
total=eng+nep+comp+acc+eco;
per=total/5;
if(eng>=35&&nep>=35&&comp>=35&&acc>=35%%eco>=35){
if(per>=75) {
printf("\n Distinction");
else if(per>=60){
printf("\n First");
}
else if(per>=45){
printf("\n Second");
}
else{
printf("\n Third");
}
}
else{
printf("\n You are failed");
}
getch();
}
b) Switch case statements
• The switch statement can be used instead of multiple if() else conditional statements.
• The switch control statement is mainly used to generate menu based programs.
Syntax:
Switch(expression 1)
{
Case condition 1:
Statements ….
break;
.
.
Case condition n-1:
Statements…….
break;
default:
statement n;
}
WAP which reads any two integer values from user and calculates sum,
difference and product using switch case statement.

#include<stdio.h>
#include<conio.h>
void main(){
int a,b,c,ch;
printf("enter the two number");
Scanf("%d",&a,&b);
printf("\n 1. Sum");
printf("\n 2. Difference");
printf("\n 3. Product");
printf("\n Enter your choice");
Scanf("%d",&ch);
switch(ch){
case 1:
c=a+b;
Printf("\n Sum of two number is %d,c);
break;
case 2:
c=a-b;
printf("\n difference of two number is %d,c);
break;
case 3:
c=a*b;
printf("\n product of two number is %d,c);
break;
default:
printf("\n Wrong choice");
}
getch();
1. Looping Statement
• The looping statement is also called repetitive or iterative control
structure. Looping statements are the conditional control flow
statements that repeats a certain portion of the program either a
specified number of times or until a particular condition is satisfied or
true.
Types of loop:
i) For Loop
ii) While Loop
iii) Do while Loop
1. For Loop
• The execution of for loop until the condition is true. The for loop is a
entry control loop because it checks the condition at entry point.
Syntax:
for( initialization; condition; increment/ decrement)
{
// statements
}
Write a program to print the natural number
from 1 to 10.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
{
printf("/n%d",i);
}
getch();
}
Write a program to display even number from
1 to 20 and display their sum also.
#include<stdio.h>
#include<conio.h>
void main() {
int i, s=0;
for(i=1;i<=20; i=i+2)
{
printf("/n even number are %d",i);
s=s+i;
}
printf("sum of even number is %d", s);
getch();
}
Write a program to find out sum of the cubes
of first 10 numbers.
# include<stdio.h>
# include<conio.h>
void main()
{
int i,c, sum=0;
for(i=1;i<=10;i++)
{
c=i*i*i;
sum=sum+c;
}
printf("/n sum of cube is %d", sum);
getch();
}
Nested for loop:
• When for loop is declared inside another for loop is called nested for loop.
• The life of the inner for loop is depending over the outer for loop.
• If the outer for loop condition is true then inner for loop is evaluated.
• And will executes all the statements until condition is true if the inner for loop to be false then
the outer for loop condition is reevaluated and so on.
For example:
for( initialization; condition; increment/ decrement)
{
for( initialization; condition; increment/ decrement)
{
// statemetns
}
}
Display the following output.
10 20 30 40 50
10 20 30 40 50
10 20 30 40 50
10 20 30 40 50
10 20 30 40 50
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; ++i) {
for (int j = 1; j <= 5; ++j) {
printf("%d\t", j * 10);
}
printf("\n");
}
return 0;
}
WAP to display the following output.
55555
4444
333
22
1
#include <stdio.h>
int main() {
int i, j;
for (i = 5; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("%d", i);
}
printf("\n");
}
return 0;
}
for (i = 5; i >= 1; --i) {
Iteration 1: i = 5
for (j = 1; j <= i; ++j) {
• Inner loop starts with j = 1, and as long as j is less than or equal to i (which is 5 in
this case), it executes the loop body.
printf("%d", i);
• Prints the value of i (5) five times because the inner loop runs five times.
Output: 55555
Iteration 2: i = 4
for (j = 1; j <= i; ++j) {
• Inner loop starts with j = 1 and runs four times because i is now 4.
printf("%d", i);
• Prints the value of i (4) four times.
Output: 55555
4444
#include <stdio.h>
int main() {
int row = 5; // Number of rows
while (row >= 1) {
int col = row;
while (col >= 1) {
printf("%d", row);
col--;
}
printf("\n");
row--;
}
return 0;
}
• Step 1: Initial state
row = 5
• Step 2: First iteration of the outer loop (row = 5)
Inner loop (col = 5): Print 5
Inner loop (col = 4): Print 5
Inner loop (col = 3): Print 5
Inner loop (col = 2): Print 5
Inner loop (col = 1): Print 5
Print newline character
row = 4
Output: 55555
Step 3: Second iteration of the outer loop (row = 4)
Inner loop (col = 4): Print 4
Inner loop (col = 3): Print 4
Inner loop (col = 2): Print 4
Inner loop (col = 1): Print 4
Print newline character
row = 3
Output: 55555
4444
While Loop
• The while loop is also a entry control loop.
• While loop first checks whether the initial condition is true or false and
finding it to be true, it will enter the loop and execute the statement.
Syntax
initialization;
while(condition)
{
// statement
increment/decrement
}
Write a program to print even number from 1
to 100.
#include <stdio.h>
int main() {
int number = 2; // Starting from 2, the first even number
while (number <= 100) {
printf("%d\n", number);
number += 2; // Increment by 2 to get the next even number
}
return 0;
}
Do while loop
• This loop is an exit control loop. This loop runs at least the once even
though the termination condition is set to false. This loop test the condition
at exit point hence it is called exit control loop.
• The syntax of the loop is similar to while loop.
• Initialization:
do
{
// statement
increment/decrement
} while(condition);
Write a program to display odd number from
100 to 1.
#include <stdio.h>
int main() {
int number = 99; // Starting from 99, the first odd number less than 100
do {
printf("%d\n", number);
number -= 2; // Decrement by 2 to get the next odd number
} while (number >= 1);
return 0;
}
Write a program to read the employee name, address for the N employee and display by
using while loops.

#include <stdio.h>
int main() {
int num;
char ename[20], eadd[30];
printf("\nEnter the number of employees: ");
scanf("%d", &num);
while (num > 0) {
printf("\nEnter the name and address:\n");
scanf("%s %s", ename, eadd);
printf("Name: %s\nAddress: %s\n", ename, eadd);
num = num - 1;
}
return 0;
}
The jump Statements
i) break statements
ii) continue statements
iii) goto statements

1) break statements:
• The break statement is used to terminate loop or to exist form a
switch. it can be used within a for, while, do while switch statement.
OUTPUT: 1234
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
printf("%d", i);
}
return 0;
}
The continue Statement
• It skips the remaining statements in the body a while, for or
do ......while structure it proceeds with the next iteration of the loop.
• The continue statement is used to by pass the execution of the further
Statements
Example:
OUTPUT: 12345689
#include <stdio.h>
int main() {
int num;
for (num = 1; num <= 9; num++) {
if (num == 7) {
continue;
}
printf("%d", num);
}
printf("\n");
return 0;
}
Go to statement
The goto statement is used to send the pointer to the specified label.
If the label is not defined then the goto statement will not work.
Example:
#include <stdio.h>
void main() {
int num;
Lab:
printf("Enter a number: ");
scanf("%d", &num);
if (num < 100) {
printf("Mark can't be less than 100\n");
goto Lab;
} else {
printf("Valid mark\n");
}
getchar(); // Use getchar() instead of getch()
}
WAP to input any value and display the that
value in reverse order.
#include <stdio.h>
void main() {
int i, r, n, x;
printf("Enter a number: ");
scanf("%d", &n);
x = 0;
while (n > 0) {
r = n % 10;
x = x * 10 + r;
n = n / 10;
}
printf("\nReverse number is %d", x);
getchar(); // Use getchar() instead of getch()
}
WAP to input positive number and find its
factorial number.
#include <stdio.h>
int main() {
int i, n, f = 1;
printf("Enter a number: ");
scanf("%d", &n);
if (n > 0) {
for (i = n; i >= 1; i--) {
f = f * i;
}
printf("\nThe factorial value is %d", f);
} else {
printf("\nIt is not a positive number");
}
return 0;
}
WAP to display the Fibonacci series. 1 1 2 3 5
8 13 …………………n.
#include <stdio.h>
int main() {
int i, n;
int first = 1, second = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: %d %d ", first, second);
for (i = 3; i <= n; ++i) {
next = first + second;
printf("%d ", next);
first = second;
second = next;
}
return 0;
}
WAP read a number and to check the number
is prime or not.
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 2) {
printf("%d is not a prime number.\n", num);
return 0; }
for (int i = 2; i * i <= num; ++i) {
if (num % i == 0) {
printf("%d is not a prime number.\n", num);
return 0;
} }
printf("%d is a prime number.\n", num);
return 0;
}
WAP to find out even number from 1 to 100
and find their sum also.
#include <stdio.h>
int main() {
int sum = 0;
for (int i = 2; i <= 100; i += 2) {
printf("%d ", i);
sum += i;
}
printf("\nSum of even numbers: %d\n", sum);
return 0;
}
WAP to input a number and find out that
number is palindrome or not.
#include <stdio.h>
int main() {
int num, reversedNum = 0, originalNum, remainder;
printf("Enter a number: ");
scanf("%d", &num);
// Save the original number
originalNum = num;
// Reverse the number
while (num != 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10; }
// Check if the number is a palindrome
if (originalNum == reversedNum) {
printf("%d is a palindrome.\n", originalNum); }
else {
printf("%d is not a palindrome.\n", originalNum); }
return 0; }
WAP to input a positive number and find out
the sum of its individual digits.
#include <stdio.h>
int main() {
int num, originalNum, sum = 0, digit;
printf("Enter a positive number: ");
scanf("%d", &num);
// Save the original number
originalNum = num;
// Calculate the sum of individual digits
while (num > 0) {
digit = num % 10;
sum += digit;
num /= 10;
}
printf("The sum of digits of %d is: %d\n", originalNum, sum);
return 0;
}
WAP to input a number and check it is
Armstrong number or not.
#include <stdio.h>
#include <math.h>
int main() {
int num, originalNum, sum = 0, digit, numOfDigits = 0;
printf("Enter a number: ");
scanf("%d", &num);
// Save the original number
originalNum = num;
// Calculate the number of digits
while (num != 0) {
num /= 10;
numOfDigits++;
}
// Reset num to the original number
num = originalNum;
// Calculate the sum of powered digits
while (num > 0) {
digit = num % 10;
sum += pow(digit, numOfDigits);
num /= 10;
}
// Check if the number is an Armstrong number
if (originalNum == sum) {
printf("%d is an Armstrong number.\n", originalNum);
} else {
printf("%d is not an Armstrong number.\n", originalNum);
}
return 0;
}
WAP to display the multiplication table of
given number.
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Multiplication Table for %d:\n", num);
for (int i = 1; i <= 10; ++i) {
printf("%d x %d = %d\n", num, i, num * i);
}
return 0;
}
WAP to display all prime numbers upto 1000.
#include <stdio.h>
int isPrime(int num) {
if (num < 2) {
return 0; // Not prime for numbers less than 2
}
for (int i = 2; i * i <= num; ++i) {
if (num % i == 0) {
return 0; // Not prime if a factor is found
} }
return 1; // Prime otherwise
}
int main() {
printf("Prime numbers up to 1000:\n");
for (int i = 2; i <= 1000; ++i) {
if (isPrime(i)) {
printf("%d\n", i);
} }
return 0; }
WAP to display all perfect square numbers
from 100 to 500.
#include <stdio.h>
#include <math.h>
int main() {
printf("Perfect square numbers from 100 to 500:\n");
for (int i = 10; i <= 22; ++i) {
int square = i * i;
if (square >= 100 && square <= 500) {
printf("%d\n", square);
}
}
return 0;
}
Arrays and String Function
Arrays : An array is a collection of data of the similar type all of which are referred by a
single variable name. For example, instead of using 50 individual variables to store
name of 50 students, we can use an array to store name of 50 students.
Advantage of arrays:
- It is easier for handling similar types of data in a program.
- It is efficient for solving problems like sorting, searching, indexing etc.
- It is easier to solve matrix related problems.
- Graphics manipulations can be easily be done using array.
Disadvantages of arrays:
- It is not possible to hold dissimilar type of data in an array.
- It is difficult to visualize the multi dimensional array.
- It is static in nature so it is difficult to define the size of array during running time.
There are two types:
One/signal dimensional:
• The values on an array variable assigned in one row and more than one
column are called signal dimensional array.
Syntax: type array_name[max. size];
Example int n[10];
int age[]= {18,12,19,20,16,16,17};
• Two/Double dimensional:
• Two dimensional arrays are capable of storing data in multiple row and
columns.
Syntax: type array_name[No.Rows] [No.Cols];
Example int n[10][5];
int matrix[3][3]= {{0,1,2},{3,4,5},{6,7,8}};
Write a program to read 5 students marks and
display them.
#include <stdio.h>
int main() {
int i, marks[5];
printf("Enter marks for 5 students:\n");
for (i = 0; i < 5; i++) {
printf("Enter marks for student %d: ", i + 1);
scanf("%d", &marks[i]);
}
printf("\nStudent Marks:\n");
for (i = 0; i < 5; i++) {
printf("Student %d: %d\n", i + 1, marks[i]);
}
return 0;
}
Write a program to input 5 numbers with constant values initialization
in array to display the sum.

#include <stdio.h>
int main() {
int i, numbers[5] = {10, 20, 30, 40, 50};
int sum = 0;
for (i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("The sum of the numbers is: %d\n", sum);
return 0;
}
Write a program to input the age of 20 students and count the number of students having
age in between 20 to 25.
#include <stdio.h>
int main() {
int i, age[20], count = 0;
printf("Enter the age of 20 students:\n");
for (i = 0; i < 20; i++) {
printf("Enter age for student %d: ", i + 1);
scanf("%d", &age[i]);
// Check if age is between 20 and 25 (inclusive)
if (age[i] >= 20 && age[i] <= 25) {
count++;
}
}
// Display the count
printf("\nThe number of students with age between 20 and 25 is: %d\n", count);
return 0;
}
Write a program to find the largest number among 'n' numbers.
#include <stdio.h>
int main() {
int n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Declare an array of size n
int numbers[n];
// Input the numbers
printf("Enter %d numbers:\n", n);
for (i = 0; i < n; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &numbers[i]);
}
// Find the largest number
int largest = numbers[0];
for (i = 1; i < n; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
printf("The largest number is: %d\n", largest);
return 0;
}
Write a program to read a matrix, store it in array and display it.
#include <stdio.h>
int main() {
int rows, cols;
// Input the number of rows and columns
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Declare a 2D array for the matrix
int matrix[rows][cols];
// Input the matrix elements
printf("Enter the matrix elements:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element at position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
} }
// Display the matrix
printf("\nThe entered matrix is:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]); }
printf("\n"); }
return 0; }
Write a program to accept the age of 10 different employees and count
the no. of employee.
i) Whose age is more than or equal to 60
ii) Whose age is less than 35
#include <stdio.h>
int main() {
int i, ages[10];
int countAbove60 = 0, countBelow35 = 0;
// Input the ages of 10 employees
printf("Enter the ages of 10 employees:\n");
for (i = 0; i < 10; i++) {
printf("Enter age for employee %d: ", i + 1);
scanf("%d", &ages[i]);
// Count employees based on age criteria
if (ages[i] >= 60) {
countAbove60++;
} else if (ages[i] < 35) {
countBelow35++;
}
}
// Display the counts
printf("\nThe number of employees aged 60 or above: %d\n",
countAbove60);
printf("The number of employees aged below 35: %d\n", countBelow35);
return 0;
}
Write a program to store N numbers in array and print out the sum with the entire
array variable.
#include <stdio.h>
int main() {
int i, N;
// Input the number of elements
printf("Enter the number of elements: ");
scanf("%d", &N);
// Declare an array of size N
int numbers[N];
// Input the numbers
printf("Enter %d numbers:\n", N);
for (i = 0; i < N; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &numbers[i]);
}
// Calculate the sum of the numbers
int sum = 0;
for (i = 0; i < N; i++) {
sum += numbers[i];
}
// Display the entire array and the sum
printf("\nThe entered array is: ");
for (i = 0; i < N; i++) {
printf("%d ", numbers[i]);
}
printf("\nThe sum of the numbers is: %d\n", sum);
return 0;
}
Write a program to accept 10 different numbers in array and sort
in descending order.
#include <stdio.h>
int main() {
int i, j, temp, numbers[10];
// Input 10 different numbers
printf("Enter 10 different numbers:\n");
for (i = 0; i < 10; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &numbers[i]);
}
// Sort the array in descending order using simple bubble sort
for (i = 0; i < 10 - 1; i++) {
for (j = 0; j < 10 - i - 1; j++) {
if (numbers[j] < numbers[j + 1]) {
// Swap if the current element is smaller than the next element
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
// Display the sorted array
printf("\nThe array in descending order is: ");
for (i = 0; i < 10; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
Write a program to store twelve numbers in double dimensional
array and print out the values in table with row wise addition.
#include <stdio.h>
int main() {
int i, j, numbers[3][4], rowSum;
// Input twelve numbers into a 2D array
printf("Enter twelve numbers for a 3x4 matrix:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
printf("Enter number for position (%d, %d): ", i + 1, j + 1);
scanf("%d", &numbers[i][j]);
}
}
// Print the matrix in table format
printf("\nThe matrix is:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
printf("%d\t", numbers[i][j]);
}
printf("\n");
}
// Calculate and print the row-wise addition
printf("\nRow-wise addition:\n");
for (i = 0; i < 3; i++) {
rowSum = 0;
for (j = 0; j < 4; j++) {
rowSum += numbers[i][j];
}
printf("Sum of row %d: %d\n", i + 1, rowSum);
}
return 0;
}
WAP to enter elements for 2x2 matrix and display its transpose.
#include <stdio.h>
int main() {
int matrix[2][2], transpose[2][2], i, j;
// Input elements for the 2x2 matrix
printf("Enter elements for a 2x2 matrix:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("Enter element for position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}

return 0;
}
// Display the original matrix
printf("\nThe original matrix is:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
// Calculate the transpose
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Display the transpose
printf("\nThe transpose of the matrix is:\n");
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
printf("%d\t", transpose[i][j]);
}
printf("\n");
}
WAP to enter elements for 3x3 matrix and display its sum.
#include <stdio.h>
int main() {
int matrix[3][3], i, j, sum = 0;
// Input elements for the 3x3 matrix
printf("Enter elements for a 3x3 matrix:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("Enter element for position (%d, %d): ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
// Display the original matrix
printf("\nThe original matrix is:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d\t", matrix[i][j]);
sum += matrix[i][j];
}
printf("\n");
}
// Display the sum of elements
printf("\nThe sum of elements in the matrix is: %d\n", sum);
return 0;
}
String Function:
• The strings are manipulated by specific string function.
• These are inbuilt functions and defined within string.h header file.
1. strlen( ):
• It returns the number of character present in the string.
• Syntax: strlen(string);
Write a program to store string in array
variable and find the length.
#include <stdio.h>
#include <string.h>
int main() {
int length;
char n[] = "Everest";
length = strlen(n);
printf("\nString: %s", n);
printf("\nLength: %d", length);
return 0;
}
2. strrev( ): It helps to reverse the character of the string.
Syntax:strrev(string);
3. strupr( ): It converts lowercase letters in string to uppercase.
Syntax:strupr(string);
4. strlwr( ): It converts uppercase letters in string to lowercase.
Syntax:strlwr(string);
5. strcpy( ): It is used to copy the content of one string to another.
Syntax:strcpy(target,source);
6. strcat( ): It is used to concatenate source string to the target string.
Syntax:strcat(target,source); or strcat(source,target);
7. strcmp( ): It compares two strings on following basis.
Syntax:strcmp(string1,string2)
Write a program to show use of
strcpy,strrev,strupr and strlwr.
# include<stdio.h>
# include<conio.h>
# include<string.h>
void main( )
{
char source[25];
char target[25];
printf("Enter the any word"):
gets (source);
strcpy(target,source);
printf("Copied word is= %s \n",target);
printf("Reverse word is=%s \n",strrev(source));
printf("Word with capital letters= %s \n",strupr(source));
printf("Word with small letters= %s \n",strlwr(source));
}
Strcpy
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char target[20];
strcpy(target, source);
printf("Source string: %s\n", source);
printf("Copied string: %s\n", target);
return 0;
}
Reverse
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int length = strlen(str);
printf("Original string: %s\n", str);
for (int i = 0; i < length / 2; i++) {
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
printf("Reversed string: %s\n", str);
return 0;
}
toupper
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "Hello, World!";
int length = 0;
while (str[length] != '\0') {
length++;
}
printf("Original string: %s\n", str);
for (int i = 0; i < length; i++) {
str[i] = (char)toupper(str[i]);
}
printf("Uppercase string: %s\n", str);
return 0;
}
Write a program to read two strings in array
and concatenate string.
#include <stdio.h>
#include <string.h>
int main() {
char source[20] = "Rajesh";
char target[10] = " Hamal";
strcat(source, target);
printf("Concatenated string: %s\n", source);
return 0;
}
Write a program to read two strings in array and compare two
strings and check that string is palindrome or not.
#include<stdio.h>
#include<string.h>
int isPalindrome(char str[]) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length - i - 1]) {
return 0;
} }
return 1; // Palindrome }
int main() {
char string1[20];
printf("Enter a word: ");
scanf("%s", string1);
if (isPalindrome(string1)) {
printf("Palindrome\n");
} else {
printf("Not palindrome\n"); }
return 0;
Function
Functions are the building block of statements, which takes some data, manipulate
them and can return a value. Bug free function can be used repeatedly from other
part of the program. There are two types of functions:
1. Library Functions (built in or ready made): C has the facilities to provide
library function for performing some operation. These functions are present in the c
library and they are predefined.
for eg.
a. scanf( );
b. printf( );
c. getchar( );
d. putchar( );
2. User Defined functions (Defined by user according to need): user can creates their own
function for performing this type of a function are called user define function.
Syntax of user defined functions
# include<stdio.h>
# include<conio.h>
void main( )
{
function ( );
..............
.............
}
function ( )
{
body of the function
}
WAP to calculate simple interest using
function
#include <stdio.h>
float interest(); // function declaration
int main() {
float si;
si = interest(); // function call
printf("Simple interest is %.2f\n", si);
return 0;
}
float interest() { // function definition
float p, t, r, i;
printf("Enter Principal, Time, and Rate: ");
scanf("%f%f%f", &p, &t, &r);
i = (p * t * r) / 100;
return i; // function return value
}
WAP to calculate area of rectangle using
function
#include <stdio.h>
int area(void); // Function declaration
int main() {
int a;
a = area();
printf("Area is %d\n", a);
return 0;
}
int area() { // Function definition
int l, b, ar;
printf("Enter length and breadth: ");
scanf("%d%d", &l, &b);
ar = l * b;
return ar;
}
Advantages of function
1. Big programs can be divided into smaller module using functions.
2. Program development will be faster.
3. Program debugging will be easier and faster.
4. Use of functions reduce program complexity.
5. Program length can be reduced through code reusability.
6. Use of functions enhance program readability.
7. Several developer can work on a single project.
8. Functions are used to create own header file i.e mero.h
9. Functions can be independently tested.
Write a program to find out the area of circle
through given radius as argument using function.
#include<stdio.h>
float area(float);
int main() {
float rad, res;
printf("Enter the radius of a circle: ");
scanf("%f", &rad);
res = area(rad);
printf("Your required area is %f\n", res);
return 0;
}
float area(float a) {
float mm, pi = 3.14;
mm = pi * a * a;
return mm;
}
Write a program in C to create a function to pass two numbers
as an argument and to return a sum to the calling function.
#include<stdio.h>
int add(int, int);
int main() {
int a, b, c;
printf("Enter any two numbers: ");
scanf("%d%d", &a, &b);
c = add(a, b);
printf("The sum of a and b is = %d\n", c);
return 0;
}
int add(int x, int y) {
int sum;
sum = x + y;
return sum;
}
Write a program to find out sum and square of two
input number without passing arguments function.
#include <stdio.h>
int sum();
int square();
void main() {
sum();
square();
}
int sum() {
int a, b, result;
printf("Enter any two numbers: ");
scanf("%d%d", &a, &b);
result = a + b;
printf("Sum is = %d\n", result);
return result;
}
int square() {
int a, result;
printf("Enter any number: ");
scanf("%d", &a);
result = a * a;
printf("Square is = %d\n", result);
return result;
}
Recursive Function
• The function which performs recursion is called recursive function.
Recursion is a process by which a function calls itself repeatedly until
some specified condition has been satisfied.
• Those function which calls itself is known as recursive function and
the concept of using recursive functions to repeat the execution of
statements as per the requirement is known as recursion.
• The criteria for recursive functions are:
1. The function should call itself.
2. There should be terminating condition so that function calling will
not be for infinite number of time.
Write a program to calculate factorials by
using recursion process.
#include <stdio.h>
int fact(int);
void main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("The factorial of %d is %d\n", n, fact(n));
}
int fact(int n) {
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}
Write a program read a number and make the sum of
individual digits & print using recursion technique.
#include <stdio.h>
int sum(int);
void main() {
int n;
printf("Enter any number: ");
scanf("%d", &n);
printf("The sum of individual digits is %d\n", sum(n)); }
int sum(int n) {
int a;
if (n > 0) {
a = n % 10;
n = n / 10;
return a + sum(n);
} else {
return 0; } }
Accessing a Function
• There are two types of accessing a function.
1. Call by value:
Only the values of arguments are same to the function and any change
made to the formal arguments do not change the actual arguments.
Write a C program try to exchange two values
by using call by value accessing function.
#include <stdio.h>
int swap(int, int);
int main() {
int a, b;
a = 10;
b = 20;
printf("Value of a=%d and b=%d\n", a, b);
a = swap(a, b);
printf("Value of a=%d and b=%d\n", a, b);
return 0;
}
int swap(int x, int y) {
int r;
r = x;
x = y;
y = r;
return x; // Return the modified value of x
}
Call by reference
• When we pass address to a function the parameters receiving the
address should be pointer.
• The process of calling a function by using pointer to pass the address
of the variable is known as call by reference.
Call by Value:
1. Data Passed:
1. In call by value, the actual values of the variables are passed to the function.
2. The function receives a copy of the data, and any modifications made inside the function do not
affect the original data outside the function.
2. Memory Usage:
1. Since a copy of the data is passed, it requires more memory because both the original and the copy
exist in memory.
3. Performance:
1. It may be less efficient for large data structures as copying data takes time.
Call by Reference:
4. Data Passed:
1. In call by reference, the memory addresses (references) of the variables are passed to the function.
2. The function operates directly on the memory locations of the original data.
5. Memory Usage:
1. It is more memory-efficient as it doesn't involve copying the data. The function works with the
original data directly.
6. Performance:
1. Typically more efficient, especially for large data structures, as there's no need to duplicate the
data.
Write a C program to exchange two values by
using call by reference accessing function
#include<stdio.h>
void swap(int *, int *);
int main() {
int a, b;
a = 10;
b = 20;
printf("Value of a=%d and b=%d\n", a, b);
swap(&a, &b);
printf("Value of a=%d and b=%d\n", a, b);
return 0;
}
void swap(int *x, int *y) {
int r;
r = *x;
*x = *y;
*y = r;
}
Structure
• Structure is a collection of variables under a single name.
• As an example, if we want to store data with multiple data types like
roll number, student name, address, phone number and class of a
student then C supports structure which allows us to wrap one or more
variables with different data types.
• Each variable in structure is called a structure member. To define a
structure, we use struct keyword.
Syntax: struct struct_name
{
Structure_members(s);
};
Structure Declaration
struct student
{
int roll;
char name[50];
int age;
char section;
float height;
};
We can also declare a structure
struct student
{
int roll;
char name[50];
int age;
char section;
float height;
} s1,s2;
We can also declare array of variables at a time of declaring a structure as:
struct student
{
int roll;
char name[50];
int age;
char section;
float height;
} s[100];
Union
• Unions like structure contain members whose individual data types may
differ from one another.
• However the member that composes a union all share the same storage
area within the computer memory were as each member within a
structure is assigned its own unique storage area.
Syntax:
Union union_name
{
Union_member (s);
}
Structure vs Union
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
union Data {
int intValue;
float floatValue;
char stringValue[20];
};
int main() {
struct Person person1;
strcpy(person1.name, "John");
person1.age = 25;
person1.height = 5.9;
union Data data1;
data1.intValue = 42;
printf("Person: %s, %d years old, %.2f feet tall\n", person1.name, person1.age, person1.height);
printf("Data - Integer Value: %d\n", data1.intValue);
return 0;
}
Write a C program to read different structure variables and display them.
#include<stdio.h>
struct student {
int roll;
char name[30];
char section;
float height;
};
void main() {
struct student s1;
printf("\nEnter roll number: ");
scanf("%d", &s1.roll);
printf("\nEnter name: ");
scanf("%s", s1.name); // Use %s for string input
printf("\nEnter section: ");
scanf(" %c", &s1.section); // Note the space before %c to consume the newline character
printf("\nEnter height: ");
scanf("%f", &s1.height);
printf("\nYou have entered:\n");
printf("Roll Number: %d\nName: %s\nSection: %c\nHeight: %f\n",
s1.roll, s1.name, s1.section, s1.height);
}
Write a program that reads different names and addresses into the
computer and rearrange the names into alphabetical order using the
structure variables.
#include <stdio.h>
#include <string.h>
struct student {
char name[50];
char address[50];
};
int main() {
int i, j, n;
printf("\nHow many records do you want to store? ");
scanf("%d", &n);
struct student s[200], t;
// Input loop
for (i = 0; i < n; i++) {
printf("\nEnter name of the student: ");
getchar(); // Consume the newline character left by the previous scanf
fgets(s[i].name, sizeof(s[i].name), stdin);
// Remove the newline character from the name
s[i].name[strcspn(s[i].name, "\n")] = '\0';
printf("Enter address of the student: ");
fgets(s[i].address, sizeof(s[i].address), stdin);
// Remove the newline character from the address
s[i].address[strcspn(s[i].address, "\n")] = '\0';
}
// Sorting names in alphabetical order
for (i = 0; i < n; i++) {
for (j = 0; j < n - 1; j++) {
if (strcmp(s[j].name, s[j + 1].name) > 0) {
t = s[j];
s[j] = s[j + 1];
s[j + 1] = t;
}
}
}
printf("\n\nThe records of the students after sorting\n");
printf("\nName\t\tAddress");

// Display sorted records


for (i = 0; i < n; i++) {
printf("\n%s\t\t%s", s[i].name, s[i].address);
}
return 0;
}
Pointer
• A pointer is a variable that a points to a references a memory location
where data is stored.
• Each memory cell in the computer has an address which can be used
to access its location.
• A pointer variable points to a memory location rather than a value.
• We can access and change the contents of the memory location.
• A pointer variable contains the memory location of another variable.
• The asterisk tells the compiler that you are creating a pointer variable.
• The pointer declaration syntax is as shown below.
• Pointer_type *pointer_variable_name;
For e.g: int *p;
Address (&) and indirection (*) operator
• The address (&) operator and immediately preceding variable returns the
address of the variable associated with it. Hence, the address of (&)
operator returns the address of memory location in which the variable is
stored. The indirection (*) operator is used to extract value from the
memory location stored in the particular memory location whose address is
stored in pointer variable. The syntax of declaring address operator to
pointer variable is as follows.
• Pointer_variable = &variable_name;
For Example:
int *ptr, num=25;
ptr = &num;
Write a complete program to display address and value of the pointer variable.
#include<stdio.h>
void main() {
int *p;
int age = 17;
p = &age;
printf("\nValue of age is %d", age); // Output: 17
printf("\nValue of age is %d", *p); // Output: 17
printf("\nValue of age is %d", *(&age)); // Output: 17
printf("\nAddress of age is %p", (void *)p); // Output: Address of the pointer variable
printf("\nAddress of age is %p", (void *)&age); // Output: Address of the age variable
}
Note: void * type is a generic pointer type that can hold the address of any data type
Write a C program to increment pointer.
#include<stdio.h>
void main() {
int n[] = {10, 20, 30, 40};
int *aptr = n;
int i;
printf("\nPointer notation\n");
for (i = 0; i < 4; i++) {
printf("*(aptr+%d) = %d\n", i, *(aptr + i));
}
}
Write a program to pass pointer variable to function sum them and display after
returning it.
#include<stdio.h>
int add(int *p, int *k);
void main() {
int a, b, c = 0;
printf("\nEnter two numbers: ");
scanf("%d %d", &a, &b);
c = add(&a, &b);
printf("\nSum of two numbers %d and %d is %d", a, b, c);
}
int add(int *x, int *y) {
int r;
r = *x + *y;
return r;
Write a C program to assign array, place these array in pointer variable and
display array value along with its address.
#include<stdio.h>
void main() {
int i, arr[10];
int *ptr[10];
// Assign values to the array
for (i = 0; i < 10; i++) {
arr[i] = i + 1;
}
// Place the array in pointer variables
for (i = 0; i < 10; i++) {
ptr[i] = &arr[i];
}
// Display array values along with their addresses
for (i = 0; i < 10; i++) {
printf("\nValue arr[%d]: %d stored at address: %p", i, arr[i], (void *)ptr[i]);
}
}
#include<stdio.h>
int main() {
int a = 10, *b, **c;
b = &a;
c = &b;
printf("\nValue of a is %d", a); // Output: 10
printf("\nValue of a is %d", *b); // Output: 10
printf("\nValue of a is %d", **c); // Output: 10
printf("\nAddress of a is %u", b); // Output: Address of 'a'
printf("\nAddress of a is %u", &a); // Output: Address of 'a'
printf("\nAddress of b is %u", c); // Output: Address of 'b'
printf("\nAddress of b is %u", &b); // Output: Address of 'b'
return 0;
}
Advantage of Pointer

• Runtime memory creation.


• Runtime memory deletion.
• Hard Access through pointer.
• Data Structure Based Pointer.
• Applications of Pointer Ms-word, Excel, Access, SQL.
Working with files
• Data file much application required that information be written is
stored on the memory device in the form of a data file.
• Thus, data file access and alter that information whenever information
in C.
Sequential and Random Access File
Sequential Access File:
• The sequential access files allow reading the data from the file in one after
another i.e. in sequence. There is no predefined order for accessing data file.
All the processes are declare and assigned by the compiler during run time
of the program.
Random Access File:
• The random access files allow reading data from any location in the file.
Sometimes, we need to read data file from reverse, middle and from specific
location. To achieve this, C defines a set of functions to manipulate the
position of the file. The inbuilt function fseek( ), lseek( ), rewind( ) and ftell(
) are the some of the common examples of random access files.
Opening, Reading, Writing and Appending
on/from Data File
• Once the file pointer has been declared, the next step is to open file.
There is an inbuilt function to open a file. The function fopen( ) is
used to create a steam for use and links of new open file. This function
return a file pointer and takes two parameter one for name of file and
other for mode for the file.
• The syntax is as follows;
FILE *f;
f = fopen ("file_name.extension", "mode_of_open");
• The modes of the data file are as follows:
Functions
1. fputc= Store character into the file.
2. fputs= Store string in to the file.
3. fgetc= fetch character from the file.
4. fgets= fetch string from the file.
5. fwrite= store data (structure) in to the file.
6. fread= fetch data (structure) from the file.
7. fprintf= store data in to file.
8. fscanf= fetch variable from the file.
Opening a data file
Syntax:
FILE *fptr
fptr = fopen (“filename” , “mode”)
Where, File name can be “library.txt”, “student.dat” ..etc
Mode:
“w” to write/store data in a data file.
“r” to display/read/retrieve/access data from a datafile.
“a” to add/append data in existing datafile.
Store/write data
Syntax:
fprintf(fptr , ”format specifiers” ,variables);
Eg; suppose if we want to store name, disease, age and bed number of a
patient then, it is written
as
fprintf(fptr , ”%s %s %d %d”, n, d, a, b);
Where, variable are initialized as:
char n[10], d[10];
int a, b;
Create a datafile “patient.txt” and store name, disease, age and bed number
of a patient.
#include<stdio.h>
int main() {
char n[10], d[10];
int a, b;
FILE *fptr;
fptr = fopen("patient.txt", "w");
if (fptr == NULL) {
printf("Error opening the file.\n");
return 1; // Return an error code
}
printf("Enter name, disease, age, and bed number: ");
scanf("%s %s %d %d", n, d, &a, &b);
fprintf(fptr, "%s %s %d %d\n", n, d, a, b);
fclose(fptr);
return 0;
}
#include<stdio.h>
int main() {
char n[10], d[10];
int a, b;
FILE *fptr;
fptr = fopen("patient.txt", "w");
if (fptr == NULL) {
printf("Error opening the file.\n");
return 1; }
printf("Enter name, disease, age, and bed number: ");
scanf("%s %s %d %d", n, d, &a, &b);
fprintf(fptr, "%s %s %d %d\n", n, d, a, b);
fclose(fptr);
// Open the file in read mode
fptr = fopen("patient.txt", "r");
if (fptr == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Display the contents of the file
printf("\nContents of patient.txt:\n");
while (fscanf(fptr, "%s %s %d %d", n, d, &a, &b) != EOF) {
printf("Name: %s, Disease: %s, Age: %d, Bed Number: %d\n", n, d, a, b);
}
// Close the file
fclose(fptr);
return 0;
Create a datafile “student.txt” and store name, class and marks obtained in 3
different subject until user press “y” / as per user requirement.
#include <stdio.h>
#include <string.h>
int main() {
char n[10], ch[3];
int c, e, ne, m;
FILE *fptr;
fptr = fopen("student.txt", "w");
if (fptr == NULL) {
printf("Error opening the file.\n");
return 1; // Return an error code
}
do {
printf("Enter name, class, and 3 marks: ");
if (scanf("%s %d %d %d %d", n, &c, &e, &ne, &m) != 5) {
printf("Invalid input. Please enter the data correctly.\n");
return 1; // Return an error code
}
fprintf(fptr, "%s %d %d %d %d\n", n, c, e, ne, m);
printf("Press Y to continue: ");
scanf("%s", ch);
} while (strcmp(ch, "Y") == 0 || strcmp(ch, "y") == 0);
fclose(fptr);
return 0;
}
A datafile “student.txt” contain name, class and marks obtained in 3
different subject of few students. Write a C program to add 200 more
records.
#include<stdio.h>
int main() {
char n[10];
int c, e, ne, m, i;
FILE *fptr;
fptr = fopen("student.txt", "a");
if (fptr == NULL) {
printf("Error opening the file.\n");
return 1; // Return an error code
}
for (i = 1; i <= 200; i++) {
printf("Enter name, class, and 3 marks for student %d:\n", i);
if (scanf("%s %d %d %d %d", n, &c, &e, &ne, &m) != 5) {
printf("Invalid input. Please enter the data correctly.\n");
fclose(fptr);
return 1; // Return an error code
}
fprintf(fptr, "%s %d %d %d %d\n", n, c, e, ne, m);
}
fclose(fptr);
printf("Records added successfully.\n");
return 0;
}
Read/Display/retrieve/access data from a datafile
Syntax:
fscanf(fptr , ”format specifiers” ,variables);

Eg; suppose if we want to display/read name, disease, age and bed


number of a patient from data
file then, it is written as
fscanf(fptr , ”%s %s %d %d”, n, d, &a, &b);
Where, variable are initialized as:
char n[10], d[10];
int a,b;
A datafile “student.txt” contain name, class and marks obtained in 3
different subject of few students. Write a C program to read and
display only records whose name is Ram.
#include <stdio.h>
#include <string.h>
void toLowercase(char *str) {
for (int i = 0; str[i] != '\0'; ++i) {
str[i] = tolower(str[i]);
}
}
int main() {
char n[10];
int c, e, ne, m;
FILE *fptr;
// Provide the correct path or ensure the file is in the same directory
fptr = fopen("student.txt", "r");
if (fptr == NULL) {
perror("Error opening the file");
return 1; // Return an error code
}
printf("Records for students named Ram:\n");
while (fscanf(fptr, "%s %d %d %d %d", n, &c, &e, &ne, &m) != EOF) {
// Convert the name to lowercase for case-insensitive comparison
toLowercase(n);
// Compare the lowercase name with "ram"
if (strcmp(n, "ram") == 0) {
printf("%s %d %d %d %d\n", n, c, e, ne, m);
}
}
fclose(fptr);
return 0;
}
Write a C program to read N students record store them in data file and
display the content in appropriate format by using fprintf and fscanf function.
#include<stdio.h>
void main() {
FILE *f;
int i, rn, n;
char name[25], add[35];
f = fopen("ratna.txt", "w");
if (f == NULL) {
printf("Error opening the file for writing.\n");
return; // Return without processing if there's an error
}
printf("\nHow many records?");
scanf("%d", &n);
printf("Enter %d student roll number, name, and address:\n", n);
for (i = 0; i < n; i++) {
scanf("%d %s %s", &rn, name, add);
fprintf(f, "%d\t%s\t%s\n", rn, name, add);
}
fclose(f);
printf("\nThe %d data records\n", n);
f = fopen("ratna.txt", "r");
if (f == NULL) {
printf("Error opening the file for reading.\n");
return; // Return without processing if there's an error
}
while (fscanf(f, "%d %s %s", &rn, name, add) != EOF) {
printf("\n%d\t%s\t%s", rn, name, add);
}
fclose(f);
Fwrite vs Fprintf
Structure vs Pointer
Break vs Continue
Array vs Pointer

You might also like