Problem Solving Using C
Problem Solving Using C
in)
#include <stdio.h>
int main()
{
printf (“Hello world!”);
return 0;
}
www.myanatomy.in 2
C Program Example-1
//Program to print an integer number
#include <stdio.h>
int main()
{
int num = 6;
printf (“The number is = %d”, num);
return 0;
}
www.myanatomy.in 3
C Program Example-2
//Program to declare a variable, read the value and print the stored value
#include <stdio.h>
int main()
{
int num;
printf(“Enter an integer number:”);
scanf(“%d”, &num); //Lets enter 6
printf (“The entered number is = %d”, num);
return 0;
}
Output: Enter an integer number: 6
The entered number is = 6
www.myanatomy.in 4
C Program Example-3
//Program to read two integer from keyboard and print the sum of two
integer
#include <stdio.h>
int main()
{
int num1, num2, sum; //Declaration of 2 variables
printf(“Enter two integer numbers:”);
scanf(“%d %d”, &num1, &num2); //Lets enter 3 and 4
sum = num1+num2;
printf (“The sum of two integer is = %d”, sum);
return 0;
}
Output: Enter two integer numbers: 3 4
The sum of two integer is = 7
www.myanatomy.in 5
Data Types and Input Output
Identifier:
"Identifiers" or "symbols" are the names you supply for variables, types,
functions, and labels in your program.
Identifier names must differ in spelling and case from any keywords.
You cannot use keywords as identifiers; they are reserved for special use.
You create an identifier by specifying it in the declaration of a variable,
type, or function.
In the example below, num is an identifier for an integer variable, and
main and printf are identifier names for functions.
www.myanatomy.in 6
Data Types and Input Output
Identifier:
#include <stdio.h> Once declared, you can use the
int main() identifier in later program statements
to refer to the associated value.
{
int num=5;
if(num != 0)
printf(“NOT ZERO\n");
}
www.myanatomy.in 7
Data Types and Input Output
Variable:
A variable is nothing but a memory area
int no = 5;
used to store data. 5
Each variable must be represented with 100 no
a unique name. For example, int no = 2;
Here, no is the name of the variable In the above declaration, int
which contains the integer value 2. is the data type, no is the
variable name, 5 is the value
The value stored can be changed,
stored at no, and 100 is the
hence it is called variable.
address of the memory
Each variable is associated with an location.
address.
www.myanatomy.in 8
Data Types and Input Output
Data Types:
A data type defines the type of values a variable can store. In C
programming, every variable is associated with a data type.
Each data type requires different amount of memory.
For example; a variable declared as integer can store only integer values.
In C, data types are categorized into three groups; primitive, user defined
and derived type.
Void data type has no value or operator and it does not provide a result to
its caller. But void comes under Primitive data types.
www.myanatomy.in 9
Data Types and Input Output
Data Types:
www.myanatomy.in 10
Data Types and Input Output
Primary Data Types:
Primary data types are also known as the fundamental data types
because they are pre-defined or they already exist in the C language.
All the other types of data types (derived and user-defined data types)
are derived from these data types. Primary data types in C are of 4
types: int, char, float, and double.
Data Type Memory(bytes) Range Format Specifier
www.myanatomy.in 12
Data Types and Input Output
Derived Data Types:
Derived data types are derived from the primitive or fundamental data types. There are
mainly 3 types of derived data types in C.
Derived Data Types: Array
An array is a group of similar kinds of finite entities of the same type. These
entities or elements can be referred to by their indices respectively. The indexing
starts from 0 to (array_size-1) conventionally. An array can be one-dimensional,
two-dimensional, or multidimensional.
Syntax: data_type array_name[size]; Example: int my_array[5];
In the above example, int is the data type, my_array is the name of the array and
5 is the size of the array.
my_array
0 1 2 3 4 13
www.myanatomy.in
Data Types and Input Output
www.myanatomy.in 14
Data Types and Input Output
//Program to read two integer from keyboard and print the sum of two
integer
#include <stdio.h>
int main()
{
int num1, num2, sum; //Declaration of 2 variables
printf(“Enter two integer numbers:”);
scanf(“%d %d”, &num1, &num2); //Lets enter 3 and 4
sum = num1+num2;
printf (“The sum of two integer is = %d”, sum);
return 0;
}
Output: Enter two integer numbers: 3 4
The sum of two integer is = 7
www.myanatomy.in 15
Expressions and Operators
These are two types of Arithmetic Operators in C.
• Binary
• Unary
Binary Arithmetic Operators
• This type of operator operates on two of the operands.
• A typical binary operator appears in this format with its operands:
operand1 operator operand2
Operator Description Example
% The modulus operator and the remainder after the division of an integer var = Y % X = 0 16
Expressions and Operators
Unary Arithmetic Operators
• This type of operator operates only on one operand.
• A typical unary operator appears in the following format with its operand:
operator operand
Operator Description Example
17
Expressions and Operators
Relational and Logical Operators #include <stdio.h>
int main()
• Relational operators are used to compare two values {
in C language. It checks the relationship between two int x = 10;
int y = 28;
values. If relation is true, it returns 1. However, if the
if(x==y)
relation is false, it returns 0. printf("Both variables are equal");
• Here is the table of relational operators in C language: if(x>y)
printf("x is greater than y");
Operators Operator Name if(x<y)
printf("x is less than y");
== Equal to if(x!=y)
printf("x is not equal to y ");
> Greater than if(x<=y)
printf("x is lesser or equal to y");
< Less than if(x>=y)
printf("x is greater or equal to y ");
!= Not equal to return 0;
}
Output:
>= Greater than or equal to x is less than y
x is not equal to y
<= Less than or equal to x is lesser or equal to y 18
Expressions and Operators
Relational and Logical Operators #include <stdio.h>
int main()
• Logical operators are used to perform logical operations.
{
It returns 0 or 1 based on the result of condition, whether int x = 10;
its true or false. These operators are used for decision int y = 28;
making in C language. int a = 15;
• Here is the table of logical operators in C language,
int b = 20;
if(x<y && a==b)
Operators Meaning of Results printf("x is less than y AND a is equal to b");
Operators if(x<y || a==b)
printf("x is less than y OR a is equal to b");
&& Logical AND True when all
if(!x)
operands are true
printf("x is zero");
|| Logical OR True only if either one return 0;
operand is true }
20
Expressions and Operators
Precedence and Associativity of operators
Associativity is only used when there are two or more operators of same precedence.
The point to note is associativity doesn’t define the order in which operands of a single operator are
evaluated.
Comma has the least precedence among all operators and should be used carefully
Syntax : #include<stdio.h>
int main()
if(condition) {
{ int i = 20;
// Statements to execute if. if (i > 10)
// condition is true. {
} printf("10 is less than 10“};
}
//remaining statements printf(“Out side if block“);
//remaining code }
www.myanatomy.in 22
If Statement
if-else statement: C program to illustrate If-else statement
Syntax : #include<stdio.h>
int main()
if(condition) {
{ int i = 20;
// Statements to execute if. if (i > 10)
// condition is true. {
} printf(“20 is greater than 10“);
}
else else
{ {
//Execute this code printf( “20 is less than 10”);
} }
//remaining statements return 0;
//remaining code }
www.myanatomy.in 23
If Statement
if-else-if statement: C program to illustrate If-else-if statement
Syntax : #include<stdio.h>
int main()
if(condition) {
{ int i = 50;
// This if (i == 10)
statement; printf("i is 10“);
} else if (i == 15)
printf("i is 15“);
else if(condition) else if (i == 20)
{ printf("i is 20“);
//Execute this code; else
} printf("i is not present“);
else }
//this statement;
//remaining code
www.myanatomy.in 24
If Statement
nested-if statement:
Syntax :
if (condition1)
{
// Executes this
if (condition2)
{
// Executes this
}
}
www.myanatomy.in 25
If Statement
nested-if statement: #include <stdio.h>
int main()
C program to illustrate nested-if statement {
int i = 20;
if (i <100)
{
if (i < 15)
printf(“i is smaller than 15\n”);
if (i < 12)
printf(“i is smaller than 12 too\
n”);
else
printf(“i is greater than 15”);
}
return 0;
}
www.myanatomy.in 26
Conditional 0perators and Switch Statement
Conditional Operator:
• The conditional operator is also known as a ternary operator. The conditional statements
are the decision-making statements which depends upon the output of the expression. It is
represented by two symbols, i.e., '?' and ':'.
• As conditional operator works on three operands, so it is also known as the ternary operator.
• The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else'
statement is also a decision-making statement.
Syntax of a conditional operator
expression1? expression2: expression3;
Meaning of the above syntax.
• In the above syntax, the expression1 is a Boolean condition that can be either true or false value.
• If the expression1 results into a true value, then the expression2 will execute.
• The expression2 is said to be true only when it returns a non-zero value.
• If the expression1 returns false value then the expression3 will execute.
• The expression3 is said to be false only when it returns zero value.
www.myanatomy.in 27
Conditional 0perators and Switch Statement
Conditional Operator Example:
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional operator
return 0;
}
Output:
Enter your age 12
not eligible for voting
www.myanatomy.in 28
Conditional 0perators and Switch Statement
Switch Statement:
• The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple
operations for the different possible values of a single variable called switch variable. Here, We can define
various statements in the multiple cases for the different values of a single variable.
• The syntax of switch statement in c language is given below:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
www.myanatomy.in} 29
Conditional 0perators and Switch Statement
Switch Statement:
Rules for switch statement in C language
• The switch expression must be of an integer or character type.
• The case value must be an integer or character constant.
• The case value can be used only inside the switch statement.
• The break statement in switch case is not must. It is optional. If there is no break statement found in the
case, all the cases will be executed present after the matched case. It is known as fall through the state of
C switch statement.
www.myanatomy.in 30
Conditional 0perators and Switch Statement
Switch Statement: #include<stdio.h> Output
int main(){ enter a number:4
int number=0;
number is not equal to 10, 50 or 100
printf("enter a number:");
scanf("%d",&number); enter a number:50
switch(number){ number is equal to 50
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or
100");
}
www.myanatomy.in return 0; 31
Loop Control Structure
In programming, sometimes we need to execute a block of code multiple times.
Loops come into use when we need to repeatedly execute a block of statements.
Loops are handy because they save time, reduce errors, and they make code more
readable.
There are three types of loop in C; for, while, and do-while.
for loop is used when we know exactly how many times a block of code need to be
executed.
while loop execute a block of code as long as a specified condition is satisfied.
while loop is used when you don’t know exactly how many times the block of code needs
to be executed.
The do-while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.
www.myanatomy.in 32
Loop Control Structure
for loop:
Syntax:
Statement 1 is executed (one time) before the execution of the code block. It is an initialization
statement.
Statement 2 defines the condition for executing the code block. It is a conditional statement.
Statement 3 is executed (every time) after the code block has been executed. It is a updating
statement.
www.myanatomy.in 33
Loop Control Structure
for loop:
www.myanatomy.in 34
Loop Control Structure
for loop example:
Write a C program to display MyAnatomy five times? Output: MyAnatomy
#include <stdio.h> MyAnatomy
int main() MyAnatomy
{ MyAnatomy
int i, n=5; MyAnatomy
for (i = 0; i < n; i++)
{
printf(“MyAnatomy”);
}
return 0;
}
Syntax:
while (condition)
{
// code block to be
executed
}
www.myanatomy.in 36
Loop Control Structure
while loop example-1:
// C program to illustrate while loop Output: MyAnatomy
#include <stdio.h> MyAnatomy
int main( ) MyAnatomy
{ MyAnatomy
int i = 1;
while (i < 5)
{
printf(“MyAnatomy “);
i++;
}
return 0;
}
www.myanatomy.in 37
Loop Control Structure
while loop example-2:
// C Program to display even numbers from 10 to 20 Output: 10 12 14 16 18 20
#include <stdio.h>
int main()
{
int i = 10;
while (i <= 20)
{
printf(“%d”,i);
i+=2;
}
return 0;
}
www.myanatomy.in 38
Loop Control Structure
do-while loops:
Syntax:
do
{
// code block to be
executed
}
while (condition)
www.myanatomy.in 39
Loop Control Structure
do-while loop example-1:
www.myanatomy.in 40
Loop Control Structure
www.myanatomy.in 41
Fuctions
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. Functions are used to perform certain actions, and they are
important for reusing code: Define the code once, and use it many times.
void myFunction()// declaration
{
// the body of the function (definition)
}
www.myanatomy.in 42
Fuctions
For code optimization, it is recommended to separate the declaration and the definition of
the function.
You will often see C programs that have function declaration above main(), and function
definition below main(). This will make the code better organized and easier to read:
Example:
#include<stdio.h>
void myFunction(); // Function declaration
int main() // The main method
{
myFunction(); // call the function
return 0;
}
void myFunction() // Function definition
{
printf(“This is MKP");
} 43
www.myanatomy.in
Fuctions
void func1()
Function Scope: {
A Function scope begins at the {
opening of the function and ends // label in scope even
with the closing of it. Function // though declared later
scope is applicable to labels only. A goto label_exec;
label declared is used as a target to
label_exec:;
go to the statement and both goto
}
and label statement must be in the
same function. // label ignores block scope
goto label_exec;
}
void funct2()
{
// throwserror:
// as label is in func1() not funct2()
goto label_exec;
www.myanatomy.in } 44
Fuctions
Function Scope:
Now various questions may arise with respect to the scope of access of variables:
What if the inner block itself has one variable with the same name?
If an inner block declares a variable with the same name as the variable declared by the
outer block, then the visibility of the outer block variable ends at the point of the declaration
by inner block.
• What about functions and parameters passed to functions?
A function itself is a block. Parameters and other local variables of a function follow the same
block scope rules.
• Can variables of the block be accessed in another subsequent block?
No, a variable declared in a block can only be accessed inside the block and all inner blocks
of this block.
www.myanatomy.in 45
Storage Classes in C
The storage classes define the visibility (scope) and the lifetime of any function/ variable within a
C program. These classes precede the type that they are going to modify.
A variable given in a C program will have two of the properties: storage class and type. Here,
type refers to any given variable’s data type, while the storage class determines that very
variable’s lifetime, visibility, and also its scope.
www.myanatomy.in 46
Storage Classes in C
Summary of Storage Classes in C
www.myanatomy.in 47
Pointers in C
In C, pointers are variables that store the memory addresses of other variables.
If we have a variable var in our program, &var will give us its address in the memory.
The unary operator & is used to access the address of a variable. It is called address
operator or reference operator.
The unary operator * is used for declaring a pointer variable and to access the value
stored in a address. It is called value operator, dereference operator, or indirection
operator.
www.myanatomy.in 48
Pointers in C
Program to demonstrate pointer:
#include <stdio.h>
int main()
{
int x = 10;
int *ptr = &x;
printf("Value of x = %d”, *ptr);
printf("Address of x = %p”, ptr);
*ptr = 20;
printf("After doing *ptr = 20, *ptr is %d”, *ptr);
return 0; Output:
} Value of x = 10
Address of x = 0x7f3f0d919b9c
After doing *ptr = 20, *ptr is 20
www.myanatomy.in 49
Pointers in C
Pointer Assignment:
#include <stdio.h>
int main()
{
int i=25, j=30;
int *p, *q;
p = &i;
q = p;
printf(“%d %d %d %d”, i, j, *p,*q); // 25 30 25 25
*q = 50;
printf(“%d %d %d %d”, i, j, *p, *q); // 50 30 50 50
}
www.myanatomy.in 50
Pointers in C
Passing address of a variable to a function:
#include <stdio.h> #include <stdio.h>
void test(int *); void ma(int *p, int *q)
int main() {
{ p = q;
int j; *p = 5;
test(&j); }
printf(“%d”, j); Output: 25 int i=2, j=1;
} int main()
void test(int *p) {
{ ma(&i, &j);
*p=25; printf(“%d %d”, i,j); Output: 2 5
} }
www.myanatomy.in 51
Pointers in C
Passing address of a variable to a function:
#include <stdio.h> int main()
int x; {
void Q(int z) x = 5;
{ P(&x);
z = z+x; printf(“%d”, x);
printf(“%d”, z); }
}
void P(int *y)
{
int x= *y+2; Output:
Q(x); 12 7 6
*y = x-1;
printf(“%d”, x);
}
www.myanatomy.in 52
Pointers in C
Pointer to Pointer: #include <stdio.h>
int main()
{
Data-type int i=30,j=45;
int i; int int *p, **q;
int *p; int * p=&i; p = &i;
int **q; int ** q= &p; q = &p;
int ***r; int *** r = &q; printf(“%d %d %d”, i, *p, // 30 30 30
**q);
**q=25;
p=&j; // 25 45 45
printf(“%d %d %d”, i, *p,
**q);
}
www.myanatomy.in 53
One Dimensional Arrays
One Dimensional Arrays:
Array in C can be defined as a method of clubbing multiple entities of similar type into a
larger group.
These entities or elements can be of int, float, char, or double data type or can be of user-
defined data types too like structures.
However, in order to be stored together in a single array, all the elements should be of the
same data type.
The elements are stored from left to right with the left-most index being the 0th index and the
rightmost index being the (n-1) index.
www.myanatomy.in 54
One Dimensional Arrays
One Dimensional Arrays: Searching an Element #include<stdio.h>
int main(){
int arr[20], size, key, i, index;
printf("Number of elements in the list: ");
scanf("%d", &size);
printf("Enter elements of the list: ");
for (i = 0; i < size; i++)
The Linear Search algorithm in C sequentially scanf("%d", &arr[i]);
checks each element of the list until the key printf("Enter the element to search ie. key element: ");
element is found or the entire list has been scanf("%d", &key);
traversed. Therefore, it is known as a sequential for (index = 0; index < size; index++) {
search. if (arr[index] == key){
printf("Key element found at index %d\n",
index);
break;
}
}
printf("Key element not found");
return 0; 55
www.myanatomy.in
}
One Dimensional Arrays
Arrays and Memory in C:
• Let us consider the below example for the illustration of arrays and memory.
• In the above example, we have declared an array with three elements 4, 6, and 9.
• The image below is the visualization of an array that we had so far in our previous example.
• Let us assume that an integer occupies four bytes of space, and the first byte of the first
element of the array is stored at memory location 50 as shown in the image below.
www.myanatomy.in 56
One Dimensional Arrays
Arrays and Memory in C:
• From 50 to 54, the first element four will get
stored from 55 to 58, the second element six will
get stored, and from 59 to 62, the third element
nine will get stored.
• The clear visualization of the memory is shown in
the image below.
www.myanatomy.in 57
One Dimensional Arrays
Arrays and Memory in C:
• How will the compiler calculate the address? It is based on the formula given below.
• Address = 50 + 4 * 1.
www.myanatomy.in 58
One Dimensional Arrays
Pointer with Arrays:
int ma[8] = {10, 20, 30, 40, 50, 60, 70, 80};
0 1 2 3 4 5 6 7 Index
ma 100 10 20 30 40 50 60 70 80
int main()
{
int i, *p;
int ma[5]={20, 30, 40, 50, 60};
p=ma; // or p=&ma[0];
for(i=0; i<5; i++)
{
printf(“%d”, p[ i ]);
}
}
www.myanatomy.in
One Dimensional Arrays
Functions and Arrays: Pasing Base Address of an Array to a Function:
#include <stdio.h>
void display(int *p, int n)
{
int i;
for(i=0; i<n; i++){
printf(“%d”, p[i]);
}
}
int main()
{
int i, *p;
int ma[5]={20, 30, 40, 50, 60};
display(ma, 5);
display(ma+2, 3);
printf("Size of Array: %d”, sizeof(ma));
}
www.myanatomy.in
2-D Arrays in C
2-D Array:
www.myanatomy.in 62
2-D Arrays in C
2-D Array Initialization:
www.myanatomy.in 63
2-D Arrays in C
Write a C program to insert 9 integers into a 3X3 2-D array and display them
Output:
#include <iostream> printf(“The array elements are:”); Enter the elements:
using namespace std; for (i = 0; i < 3; i++) 1
int main() { 2
{ for(j=0; j<3; j++) 3
int test[3][3], i, j; { 4
printf(“Enter the elements:”); printf(“%d”, test[i][j]); 5
for (i = 0; i < 3; i++) } 6
{ printf(“\n”); 7
for(j=0; j<3; j++) } 8
{ return 0; 9
scanf(“%d”, &test[i][j]; } The array elements
} are:
} 1 2 3
4 5 6
7 8 9 64
www.myanatomy.in
2-D Arrays in C
Pointers and two dimensional arrays
Example:
char greetings[] = "Hello World!";
printf("%s", msg);
www.myanatomy.in 66
Strings
Access Strings
Since strings are actually arrays in C, you can access a string by referring to its index number
inside square brackets [].
Example
char msg[] = "Hello World!";
printf("%c", msg[0]);
Note: that we have to use the %c format specifier to print a single character.
www.myanatomy.in 67
Strings
Modify Strings Loop Through a String
To change the value of a specific character in a string, You can also loop through the characters of a
refer to the index number, and use single quotes:
string, using a for loop:
Example
Example
#include <stdio.h> #include <stdio.h>
int main()
{ int main()
char greetings[] = "Hello World!"; {
greetings[0] = 'J';
char carName[] = "Volvo";
printf("%s", greetings);
return 0; int i;
} for(i = 0; i < 5; ++i)
{
printf("%c\n", carName[i]);
}
return 0;
www.myanatomy.in } 68
Strings
Strings and Pointers:
Creating a pointer for the string:
The variable name of the string str holds the address of the first element of the array i.e., it
points at the starting memory address.
So, we can create a character pointer ptr and store the address of the string str variable in it.
This way, ptr will point at the string str.
In the following code we are assigning the address of the string str to the pointer ptr.
www.myanatomy.in 69
Strings
Strings and Pointers:
We can represent the character pointer variable ptr as follows.
www.myanatomy.in 71
Strings
String Functions:
• We're often required to modify the strings and perform several operations on them according
to our needs. If we want to get the length of the string, we could run a loop and calculate its
length, but it is not the best way in case of complex problems. Hence, string functions are
used to make our code efficient and straightforward as they are pre-written so we can use
them directly.
• The string handling functions are defined in the header file string.h. This header file must be
included in the C program to use the string handling functions.
www.myanatomy.in 72
Strings
String Functions: The following are the string functions in C:
Function Description
strlen() It returns the string's length.
www.myanatomy.in 74
Recursion in C
Program to demonstrate recursion-1: Calculate factorial using recursion
www.myanatomy.in 75
Recursion in C
Program to demonstrate recursion-2: Prime check using recursion
int main()
#include <stdio.h> {
int checkPrime(int n, int index) int num, b;
{ printf("Enter a positive integer:”);
if(index == 1){ scanf(“%d”,&num);
return 1; b = checkPrime(num, num/2);
} if(b == 1)
else if(n % index == 0){ {
return 0; printf(“%d is a Prime number !”, num);
} }
else else
return checkPrime(n, index-1); {
} printf(“%d is not a Prime number!“, num);
}
return 0;
www.myanatomy.in 76
}
Structures and Unions
Structure is a user-defined datatype in C language which allows us to combine data of
different types together. Structure helps to construct a complex data type which is more
meaningful. It is somewhat similar to an Array, but an array holds data of similar type only.
But structure on the other hand, can store data of any type, which is practical more useful.
For example: If I have to write a program to store Student information, which will have
Student's name, age, branch, permanent address, father's name etc, which included string
values, integer values etc, how can I use arrays for this problem, I will require something
which can hold data of different types together.
www.myanatomy.in 77
Structures and Unions
Defining a structure:
• As you can see in the syntax above, we start with the
struct keyword is used to struct keyword, then it's optional to provide your
define a structure. struct structure a name, we suggest you to give it a name,
defines a new data type which then inside the curly braces, we have to mention all the
is a collection of primary and member variables, which are nothing but normal C
derived data types. language variables of different types like int, float, array
etc.
Syntax: • After the closing curly brace, we can specify one or
struct [structure_tag] more structure variables, again this is optional.
{
//member variable 1 Note: The closing curly brace in the structure type
//member variable 2 declaration must be followed by a semicolon(;).
...
}[structure_variables];
www.myanatomy.in 78
Structures and Unions
Example of Structure:
struct Student
{
char name[25];
int age;
char branch[10];
char gender;
};
Here struct Student declares a structure to hold the details of a student which consists of 4 data
fields, namely name, age, branch and gender. These fields are called structure elements or
members.
Each member can have different datatype, like in this case, name is an array of char type and
age is of int type etc. Student is the name of the structure and is called as the structure tag.
www.myanatomy.in 79
Structures and Unions
Declaring Structure Variables:
• It is possible to declare variables of a structure, either along with structure definition or after
the structure is defined. Structure variable declaration is similar to the declaration of any
normal variable of any other datatype. Structure variables can be declared in following two
ways:
www.myanatomy.in 80
Structures and Unions
Accessing Structure Members: #include<stdio.h>
#include<string.h>
struct Student
Structure members can be
{
accessed and assigned values char name[25];
in a number of ways. Structure int age;
members have no meaning char branch[10];
individually without the char gender;
structure. In order to assign a };
value to any structure member, int main()
{
the member name must be
struct Student s1;
linked with the structure s1.age = 18;
variable using a dot . operator strcpy(s1.name, "Viraaj");
also called period or member printf("Name of Student 1: %s\n", s1.name);
access operator. printf("Age of Student 1: %d\n", s1.age);
return 0;
}
www.myanatomy.in 81
Structures and Unions
Structure Initialization:
• Like a variable of any other datatype, structure variable can also be initialized at compile time.
//initialization
struct Patient //initialization of each member separately
{ struct Patient p1;
float height; p1.height = 180.75;
int weight; p1.weight = 73;
int age; p1.age = 23;
};
www.myanatomy.in 82
Structures and Unions
Array of Structure:
• We can also declare an array of structure variables. in which each element of the array will
represent a structure variable. Example : struct employee emp[5];
• The below program defines an array emp of size 5. Each element of the array emp is of type
Employee.
#include<stdio.h> printf("\nEnter %d Employee record:\n", i+1);
struct Employee printf("\nEmployee name:\t");
{ scanf("%s", emp[i].ename);
printf("\nDisplaying Employee record:\n");
char ename[10]; printf("\nEnter Salary:\t");
for(i = 0; i < 3; i++)
int sal; scanf("%d", &emp[i].sal);
{
}; }
printf("\nEmployee name is %s", emp[i].ename);
struct Employee emp[5]; printf("\nSlary is %d", emp[i].sal);
int i, j; }
void ask() }
{ void main()
for(i = 0; i < 3; i++) {
{ ask();
www.myanatomy.in } 83
Structures and Unions
Unions:
• Unions are conceptually similar to structures in C. The syntax to declare/define a union is
also similar to that of a structure. The only differences is in terms of storage.
• In structure each member has its own storage location, whereas all members of union uses a
single shared memory location which is equal to the size of its largest data member.
• This implies that although a
union may contain many
members of different types, it
cannot handle all the
members at the same
time.This implies that although
a union may contain many
members of different types, it
cannot handle all the
members at the same time.
www.myanatomy.in 84
Structures and Unions
Declaring a Union in C:
A union is declared using the union keyword in C. The syntax is as follows
union tag_name {
member definition; • This declares a variable It1 of type union item. This union contains
member definition; three members each with a different data type. However only one of
... them can be used at a time. This is due to the fact that only one
member definition; location is allocated for all the union variables, irrespective of their size.
} union variable(s); The compiler allocates the storage that is large enough to hold the
largest variable type in the union.
For example,
union item • In the union declared above the member x requires 4 bytes which is
{ largest amongst the members for a 16-bit machine. Other members of
int m; union will share the same memory address.
float x;
char c; • To define variables of a union, we use union keyword as follows:
} It1;
www.myanatomy.in
• union item it2, it3; 85
Structures and Unions
Accessing a Union Member in C:
• We use member access operator (.) to access members of a union in C. It is used between
the union variable name and the union member that we want to access. Syntax for accessing
any union member is similar to accessing structure members.
union test
{
int a;
float b;
char c;
}t;
t.a; //to access members of union t
t.b;
t.c;
• In unions, if we change the value of any one member, the value of other members gets
affected.
www.myanatomy.in 86
File Handling
What is File Handling in C?
File handling refers to the method of storing data in the C program in the form of an output or input that might
have been generated while running a C program in a data file, i.e., a binary file or a text file for future analysis
and reference in that very program.
What is a File in C?
A file refers to a source in which a program stores the information/data in the form of bytes of sequence on a
disk (permanently). The content available on a file isn’t volatile like the compiler memory in C. But the
program can perform various operations, such as creating, opening, reading a file, or even manipulating the
data present inside the file. This process is known as file handling in C.
www.myanatomy.in 87
File Handling
Let us look at a few reasons why file handling makes programming easier for all:
• Reusability: File handling allows us to preserve the information/data generated after we run the program.
• Saves Time: Some programs might require a large amount of input from their users. In such cases, file
handling allows you to easily access a part of a code using individual commands.
• Commendable storage capacity: When storing data in files, you can leave behind the worry of storing all
the info in bulk in any program.
• Portability: The contents available in any file can be transferred to another one without any data loss in
the computer system. This saves a lot of effort and minimizes the risk of flawed coding.
www.myanatomy.in 88
File Handling
Types of Files in a C Program
When referring to file handling, we refer to files in the form of data files. Now, these data files are available in
2 distinct forms in the C language, namely:
• Text Files
• Binary Files
Text Files
• The text files are the most basic/simplest types of files that a user can create in a C program. We create
the text files using an extension .txt with the help of a simple text editor. In general, we can use notepads
for the creation of .txt files. These files store info internally in ASCII character format, but when we open
these files, the content/text opens in a human-readable form.
• Text files are, thus, very easy to access as well as use. But there’s one major disadvantage; it lacks
security. Since a .txt file can be accessed easily, information isn’t very secure in it. Added to this, text files
consume a very large space in storage.
• To solve these problems, we have a different type of file in C programs, known as binary files.
www.myanatomy.in 89
File Handling
Binary Files
• The binary files store info and data in the binary format of 0’s and 1’s (the binary number system). Thus,
the files occupy comparatively lesser space in the storage. In simpler words, the binary files store data
and info the same way a computer holds the info in its memory. Thus, it can be accessed very easily as
compared to a text file.
• The binary files are created with the extension .bin in a program, and it overcomes the drawback of the
text files in a program since humans can’t read it; only machines can. Thus, the information becomes
much more secure. Thus, binary files are safest in terms of storing data files in a C program.
www.myanatomy.in 90
File Handling
• Here’s a list of functions that allow you to do so: Here’s a list of functions that allow you to do so:
Description of Function Function in Use
used to open an existing file or a new file fopen()
www.myanatomy.in 91
File Handling
Operations Done in File Handling
The process of file handling enables a user to update, create, open, read, write, and ultimately
delete the file/content in the file that exists on the C program’s local file system. Here are the
primary operations that you can perform on a file in a C program:
www.myanatomy.in 92
File Handling
Opening a File in the Program – to create and edit data
We open a file with the help of the fopen() function that is defined in the header file- stdio.h.
Here is the syntax that we follow when opening a file:
www.myanatomy.in 93
File Handling
Opening a File in the Program – to create and edit data
• Here, if we suppose that the file – recentprogram.txt doesn’t really exist in the E:\\myprogram
location. Here, we have used the mode “w”. Thus, the first function will create a new file with
the name recentprogram.txt and then open it for writing (since we have used the “w” mode).
• The “w” here refers to writing mode. It allows a programmer to overwrite/edit and create the
contents in a program file.
• Now, let us take a look at the second binary previous program.bin file that is present in the E:\\
myprogram location. Thus, the second function here will open the file (that already exists) for
reading in the “rb” binary mode.
• The “rb” refers to the reading mode. It only allows you to read a file, but not overwrite it. Thus,
it will only read this available file in the program.
www.myanatomy.in 94
File Handling
Let us take a look at a few more opening modes used in the C programs:
r Open a file for reading In case the file doesn’t exist in the location,
the content. then fopen() will return NULL.
rb Open a file for reading In case the file doesn’t exist in the location,
the content in binary then fopen() will return NULL.
mode.
w Open a file for writing the In case the file exists, its contents are
content. overwritten.
In case the file doesn’t exist in the location,
then it will create a new file.
www.myanatomy.in 95
File Handling
How do we close a file?
Once we write/read a file in a program, we need to close it (for both binary and text files). To
close a file, we utilise the fclose() function in a program.
fclose(fptr);
In this case, the fptr refers to the file pointer that is associated with that file that needs to be
closed in a program.
www.myanatomy.in 96
File Handling
Example #1: Writing Data to the Text File in a Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int val;
FILE *fptr;
fptr = fopen (“C:\\currentprogram.txt”,”w”);
if(fptr == NULL)
{
printf(“File type invalid!”);
exit(1);
}
printf(“Please enter the val: “);
scanf(“%d”,&val);
fprintf(fptr,”%d”,val);
fclose(fptr);
return 0;
}
www.myanatomy.in 97
File Handling
Example #2: Reading Information from the Text File in a Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
int val;
FILE *fptr;
if ((fptr = fopen(“C:\\currentprogram.txt”,”r”)) == NULL)
{
printf(“Visible error detected. Cannot open the file!”);
exit(1);
}
fscanf(fptr,”%d”, &val);
printf(“The value of the integer n is=%d”, val);
fclose(fptr);
return 0;
}
www.myanatomy.in 98
Thank You
www.myanatomy.in