C Programming
C Programming
Language
4. Speed-
Uses of C :
UNIX Operating System was Developed by Using “C” Language
Developing database Systems
Graphics Packages
Spread Sheets
Word Processors
Office automation
Scientific/Engineering Applications
CAD/CAM Applications
Programming Methodologies:
1. Analysis the problem
2. Identify the variable needed
3.Design the solution
4.Writing the Code or program
5.Testing the program(checking the errors)
6.Correcting the errors
7.Execute or run
Example:
Step1: Start
Step2: Input / Read the value a, b , c
Step3: c = a+b
Step4:Print / Display c
Step5: Stop
FlowChart :
Flowchart is a graphical representation of an algorithm.
Terminal Start
Start
and Stop
Sum= Process
a+b
Display sum
Display Sum
Stop
Character Set :
Combination of Alphabets, Digits and Special characters
used to makes a information.
Alphabets : Uppercase Letters – A,B,C….. Z
Lowercase Letters - a,b,c……
z
Digits: 0,1,2, 3, 4, 5, 6 ,7, 8, 9.
Special characters: + Plus Sign - Minus Sign , Comma
* Asterisk / Slash
= Equal to
@ At Symbol < Less Than
: Colon
; Semicolon
C tokens
Keywords
Identifiers
Variable
Constants
Operators
Special symbols
Strings
Keywords
sumOfRoots1and2
_XYZ
maxThrowsPerTurn
TURNS_PER_GAME
R2D2
Examplesofinvalididentifiers:
2hotToHandel//doesnotstartwtihaeltter
NetPay//contan
i saspace
ALPHA;BETA//contan i sann i vad
ilcharacter;
Variable
Types
Examples: #include<stdio.h>
#include<conio.h>
Stdio -> Standard Input/Output
Conio -> Console Input/Output
Void -> Keyword. It Means Returns Nothing.
main() -> It is a function name which can be used to
indicate the beginning of the program
execution
Irrespective of the number of functions in a
program, the operating system always passes
control to main () when a C program is executed.
Syntax :
#include<headerfilename.h>
Examples:
#include<stdio.h>
#include<conio.h>
Stdio -> Standard Input/Output
Conio -> Console Input/Output
Void -> Keyword. It Means Returns Nothing.
main() -> It is a function name which can be used to
indicate the beginning of the program
execution
CONSOLE INPUT OUTPUT OPERATIONS
OUTPUT INPUT
PRINTF SCANF
printf(“control
string”,variable1,variable2…..);
scanf(“control string”, &variable1, &variable2…..);
Operators
- Subtraction
X-y -> 5
* Multiplication
X*y -> 50
/ Division
x/y -> 2
% Modulo Division
Relational Operators
Relational operators are used to test the relationship
between two variables or constant
Operator Meaning Example
Result value
Assignment
operator
Shorthand of Assignment Operator
Syntax:
Variablename <arithmetic Operator>=Expression;
Simple Assignment Operators Equivalent Shorthand Assignment
Operators
x=x+1 x += 1
y=y-1 y-=1
z=z*(x+y) z *= (x+y)
Y=y/(x+y) Y /= (x+y)
X=x%z X %= z
Conditional Operators (?:)
Simple conditional operations can be carried out with the
conditional operator(?:)
Syntax:
Expression1 ? Expression 2:expression 3
Condition True Part False Part
#include<stdio.h>
void main() OUTPUT
{ The Result
int a=10,b=5,c; is 10
C=(a>b)?a:b;
printf(“The Result is %d",c);
}
BitWise Operators
Used in applications which require
manipulation of individual bits within a
word of memory
Operators Meaning
~ One’s Complement
| Bitwise OR
^ Bitwise X-OR
Special Operators
Operators Meaning Example
FUCTION OPERATION
getchar() Reads a character from the Keyboard, waits for carriage return
getche() Reads a character with echo; does not wait for carriage return not
defined by ANSI, but a common extension.
getch() Reads a character without echo, does not wait for carriage
return, not defined by ANSI, but a common extension.
For example,
Reading decimal ,octal and hexadecimal numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("\n Enter No in decimal");
scanf("%d",&a);
printf("\n u Entered %d\n",a);
Sequence
Selection
Iteration
Sequential Control Structure :
It is also called Linear programming. In this method, the
program will have statements that are placed sequentially and
there is no decision involved in the process.
Syntax :
if ( condition )
{
program statements;
}
/* Illustration to find the biggest of two number */
#include<stdio.h>
#include<conio.h>
main()
{
int value1, value2, big;
clrscr();
printf(“\n Enter the number values : ”);
scanf(“%d%d”,&value1,&value2);
big=value1;
if(value1<value2)
big=value2;
printf(“\n The bigger number is %d”, big);
getch();
}
if-else statement :
The if-else statement directs the computer to select a
sequence of one or more instructions based on the result of
comparison. When two groups of statements are given and it is
desired that one them be executed if some condition is true and
the other group be executed if that condition is not true.
Syntax :
if (expression)
{
program statements;
}
else
{
program statements;
}
/* Illustration to display whether the number is even or odd */
#include<stdio.h>
#include<conio.h>
main()
{
int number;
clrscr();
printf(“\n Enter the number : ”);
scanf(“%d”,&number);
if(number % 2 = = 0)
printf(“\n The number is Even”);
else
printf(“\n The number is Odd”);
getch();
}
if-else-if statement :
This construction is called if-else-chain. Each condition is evaluated in
order and if any condition is true, the corresponding statement is executed and
the remainder of the chain is terminated.
Syntax :
if (condition1)
Statment1;
else if(conditon2)
Statement2;
else
Statement3;
/* Illustration to find the status of an individual : */
#include<stdio.h>
#include<conio.h>
main()
{
int age;
clrscr();
printf(“\n Enter the age :”);
scanf(“%d”,&age);
if(age>=1 && age<18)
printf(“\n The individual is a minor”);
else if(age>=18 && age<40)
printf(“\n The individual is a major”);
else if(age>=40 && age<120)
printf(“\n The individual is a adult”);
else
printf(“\nInvalid age entered”);
getch();
}
Switch case statements
It is an alternative to the if-else chain. It compares to each of switch
cases and when the match is found, execution begins with the statement
immediately following the match.
Syntax :
switch(expression)
{
case value_1:
statment1;
break;
case value_2:
statement2;
break;
…
…
default:
statement n;
break;
}
/* Illustration to switch statement */
#include<stdio.h>
#include<conio.h>
main()
{
char choice;
clrscr();
printf(“\n Enter a character :”);
scanf(“%c”,&choice);
switch(choice)
{
case ‘a’:
printf(“\n The character is ovel”);
break;
case ‘e’:
printf(“\n The character is ovel”);
break;
case ‘i’:
printf(“\n The character is ovel”);
break;
case ‘o’:
printf(“\n The character is ovel”);
break;
case ‘u’:
printf(“\n The character is ovel”);
break;
default :
printf(“\n Invalid character”);
break;
}
getch();
}
Iterative Control Structure :
The ‘C’ language has the ability to repeat the same calculation on
sequence of instruction again & again.
Syntax :
while(expression)
{
statement;
}
/* Illustration to print the numbers from 1 to 10 */
#include<stdio.h>
#include<conio.h>
main()
{
int n=1;
clrscr();
while(n<=10)
{
printf(“\n%d”,n);
n++;
}
getch();
}
The Do While Construct :
In this construct the statements in the loop are executed &
the testing is done at the end of the loop.
Syntax :
Do
{
Statements;
} while(expression);
/* Illustration to print the numbers from 10 to 1 */
#include<stdio.h>
#include<conio.h>
main()
{
int n=10;
clrscr();
do
{
printf(“\n%d”,n);
n--;
}while(n>=1);
getch();
}
for Loop Construct :
It is also a looping statement which include all the expressions in the
same line i.e., initialization, condition, increment/decrement.
Syntax :
#include<stdio.h>
#include<conio.h>
main()
{
int n,i;
clrscr();
printf(“\n Enter a number :”);
scanf(“%d”,&n);
for(i=1;i<=10;i++)
{
printf(“\n %d”,n*i);
}
getch();
}
Break Statement :
The break statement transfers the control to the end of the construct.
It is used to terminate the inner most loop.
/* Illustration to break the loop */
#include<stdio.h>
#include<conio.h>
main()
{
int k;
clrscr();
for(k=1;k<=10;k++)
{
printf(“\n %d”,k);
if(k==5)
{
printf(“\n Break….”);
break;
}
}
getch();
}
Continue Statement
It works almost opposite way of the ‘break’ statement. It forces the
next iteration of the loop to take place.
/* Illustration to continue the loop */
#include<stdio.h>
#include<conio.h>
main()
{
int k;
clrscr();
for(k=1;k<=10;k++)
{
printf(“\n %d”,k);
if(k==5)
{
printf(“\n Continue….”);
continue;
}
}
getch();
}
The goto Statement
Datatype arrayname[subscript];
int a [];
Output -
Single or One Dimensional
Arrays
Arrays whose elements are specified by one subscript
are called One dimensional array or linear array.
Syntax :
datatype arrayname[size];
For Example :
Note :
By default array index should starts with zero (0)
Write a program for entering data Array Initialization
into an array & Reading data from
an array
#include<stdio.h>
#include<stdio.h>
void main() #include<conio.h>
{ void main()
int arr[10],I,n; {
printf("\n ENter N Elements"); int a[5]={10,20,30,40,50};
scanf("%d",&n); int i;
for(i=0;i<n;i++) clrscr();
{ for(i=0;i<5;i++)
printf("enter arr[%d]=",i);
{
scanf("%d",&arr[i]);
} printf("%d\n",a[i]);
for(i=0;i<n;i++) }
{ getch();
printf("%d\n",arr[i]); }
}
}
10
Enter N Elements : 2 20
3
5 30
Enter arr[0] : 2
3 40
Enter arr[1] : 5
50
Enter arr[2] : 3
Write a “C” program to sort the given number is in
ascending order using one dimensional array
#include<stdio.h>
void main()
{
int i,j,n, a[10],temp;
printf("\n size of vector=");
scanf("%d",&n);
printf("vector elements:");
for (i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
printf("\n\nElements in asending order is=\n");
for(i=0;i<n;i++)
printf("%8.2d",a[i]);
printf("\n\nElements in descending order is=\n");
for(i=n-1;i>=0;i--)
printf("%8.2d",a[i]);
getch();
}
Two Dimensional Arrays
A Arrays whose elements are specified by two subscript
such as row and column are called two dimensional array or
linear array.
Row means horizontally
Column means vertically
#include<stdio.h>
void add(); void add()
void main() {
{ int a,b,c;
add(); printf("Enter two numbers\n");
printf("Prg ends"); scanf("%d%d",&a,&b);
add(); c=a+b;
} printf("The sum is %d\n",c);
}
/* To perform Addition of two numbers */
/* WITH ARGUMENT BUT NO RETURN VALUES*/
#include<stdio.h>
void add(int,int);
void main()
{
int x,y;
printf("Enter two number");
scanf("\t\t%d %d",&x,&y);
add(x,y); /* Actual Arguments */
}
void add(int a,int b) /* Formal Arguments */
{
int c=a+b;
printf("\t\tThe C Value is %d",c);
}
/* To perform Addition of two numbers
Without Argument and With Return values */
#include<stdio.h>
#include<conio.h>
int add(); //declaration
void main()
{
int c;
c=add(); /* Return Variable - c */
printf("The sum of two numbers is %d",c);
}
int add()
{
int a,b,c;
printf("Enter two Numbers=");
scanf("%d %d",&a,&b);
c=a+b;
return(c);
}
/* To perform Addition of two numbers
With Argument and With Return values */
#include<stdio.h>
int add(int,int); //Function prototype declaration
void main()
{
int c;
printf("Enter two Numbers=");
scanf("%d %d",&a,&b);
c=add(a,b); /* Actual Arguments */
printf("The sum of two numbers is %d",c);
}
int add(int x,int y) /* Formal arguments */
{
int c;
c=x+y;
return(c);
}
PASSING PARAMETERS
Passing Value to a function
Functions communicate with each other by passing
arguments.
It can be passed in Two Ways
1. Call By Value
2. Call by Reference
Passing
Parameter
s
Call by
Call by
value
reference
CALL BY VALUE
3000
int* ptr;
2000
ptr = &x; ptr
PRADEEP
Assigning data to the pointer variable
syntax :
pointervariablename=&variablename;
to another
To manipulate arrays more easily by moving pointers to
them, Instead of moving the arrays themselves
To allocate memory and access it (Dynamic Memory
Allocation)
To create complex data structures such as Linked List, Where
one data structure must contain references to other data
structures
Advantages:
Pointers reduce the length and complexity of a program.
They increase the execution speed.
The use of a pointer array to character strings results in saving of
variable directly
#include<stdio.h>
#include<conio.h>
void main()
{
int n=10;
int *ptr;
ptr=&n;
printf("Value of n is %d",n);
printf("\nAddress of n is %x",&n);
printf("\nAddres of pointer is %x",ptr);
printf("\nvalue stored in pointer is %d",*ptr);
getch();
}
Example 2
#include<stdio.h>
#include<stdlib.h>
#define size 10
void main()
{
char name[size];
char *i;
printf("\n Enter your name ");
gets(name);
i=name;
printf("\n Now printing your name
is :");
while(*i != '\0')
{
printf("%c",*i);
i++;
}
}
Explain how the variable can be accessed by
pointer
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
float a,*b;
clrscr();
printf("\n Enter the radius of the circle");
scanf("%d",&r);
a=3.14*r*r;
b=&a;
printf("\n The value of a=%f",a);
printf("\n The value of a=%u",&a);
printf("\n The value of b=%u",b);
printf("\n The value of a=%f",*b);
getch();
}
Pointer Arithmetic
Addition and subtraction are the only operations that can be
performed on pointers.
Then ptr_var has the value 1000 stored in it. Since integers are 4
bytes long, after the expression “ptr_var++;” ptr_var will have the
value as 1004 and not 1001.
Pointer Increment process example
#include<stdio.h>
#include<conio.h>
void main()
{
int *ptr; //static memory allocation
clrscr();
ptr=(int *) malloc(sizeof(int));
*ptr=100;
printf("\n%u\n",ptr); //address of ptr
printf("\n%d\n",*ptr);
ptr++; // increment 2 bytes
*ptr=101;
printf("\n%d\n",*ptr);
free(ptr);
getch();
}
* It is the complement of
&. It returns the value
contained in the memory
location pointed to by the
pointer variable’s value
Write a C program to find the length of the string Using Pointer
#include<stdio.h>
#include<string.h>
void main()
{
char *text[20],*pt;
int len;
pt=*text;
printf("Enter the string");
scanf("%s",*text);
while(*pt!='\0')
{
putchar(*pt++);
}
len=pt -*text;
printf("\nLength of the string is %d",len);
}
/*Add Two Numbers using pointers*/
#include<stdio.h>
void main()
{
int a,b,*c=&a,*d=&b;
printf(“Enter two numbers to be summed");
scanf("%d %d",&a,&b);
printf(“The sum of two numbers=%d",c + d);
getch();
}
Pointers With
Arrays
The address of an array element can be expressed in two
ways :
By writing the actual array element preceded by the
ambersand (&) sign.
By writing an expression in which the subscript is added to the
array name.
Array Using Pointers
#include<stdio.h>
#include<conio.h>
void main()
{
int b[100],*iptr;
iptr=&b;
clrscr();
printf("The initial value of iptr is %u\n",iptr);
iptr++;
printf("Incremented value of iptr is %u\n",iptr);
getch();
}
POINTERS IN ARRAYS
Example 2
#include<stdio.h>
#include<conio.h>
void main()
{ 10
int arr[]={10,20,30,40};
int *ptr,i; 20
clrscr();
30
ptr=arr; // same as &arr[0];
printf("\n The Result of the array is 40
");
for(i=0;i<4;i++)
{
printf("%d\n",*ptr);
ptr++;
}
getch();
}
Pointers as Function Arguments
When pointers are passed to a function :
The address of the data item is passed and thus the function can
freely access the contents of that address from within the function
String Function
strcpy() strlwr()
strcat() strcmp()
strlen() strcmpi() String.h
Strupr() strrev()
Strcpy() function :
It copies the contents of one string into another string.
Syntax : strcpy(string1,string2); string1 is destination
string, string2 is source string.
#include<stdio.h>
#include<string.h>
void main()
{
char str[25],cpy[25];
printf("\n Enter a String");
gets(str);
Strcpy(cpy,str);
printf("\n The source string is %s",str);
printf("\n The copied string is %s",cpy);
}
Enter a String : PRATHAP
The Source string is : PRATHAP
OUTPUT
The Copied string is : PRATHAP
Strcat() function :
it concatenates the source string at the end of the target
string
Syntax : strcat(string1,string2);string1 target string, string2
source string
#include<stdio.h>
#include<string.h>
void main()
{
char str[25],str1[25];
printf("\n Enter a String");
gets(str);
printf("\n Enter another String");
gets(str1);
printf("\n The concatenated string is %s",strcat(str,str1));
} Enter a String : GOOD
OUTPUT Enter another String : MORNING
The Concatenated string is : GOOD
MORNING
Strcmp() function :
It compares two strings to find whether the strings are equal or not.
Syntax : strcmp(string1,string2);
#include<stdio.h>
#include<string.h> Return values
void main()
0 Equal
{
char str[25],str1[25]; 1
int x; string1>string2
printf("\n Enter a String"); -1
gets(str); string1<string2
printf("\n Enter another String");
gets(str1);
x=strcmp(str,str1);
If(x==0)
printf(“\n Strings are equal”);
else if(x>0)
printf("\n The string1 %s is greater than string2 %s”,str,str1);
else
printf("\n The string2 %s is greater than string1 %s”,str1,str);
}
Enter a String : JAIKUMAR
OUTPUT Enter another String : SASIKUMAR
The string2 SASIKUMAR is greater than string1
Strcmpi() function :
It compares two strings without regard to case to find whether the strings are
equal or not. ( i ignorecase)
Syntax : strcmpi(string1,string2);
#include<stdio.h>
#include<string.h>
void main()
{
char str[25],str1[25];
int x;
printf("\n Enter a String");
gets(str);
printf("\n Enter another String");
gets(str1);
X=strcmpi(str,str1);
if(x==0)
printf(“\n The two Strings are equal”);
else if(x>0)
printf("\n The string1 %s is greater than string2 %s”,str,str1);
else
printf("\n The string2 %s is greater than string1 %s”,str1,str);
}
Enter a String : COMPUTER
OUTPUT Enter another String : computer
the Two strings are equal
strrev() function :
used to reverse a string. It takes only one argument.
Syntax : strrev(string);
#include<stdio.h>
#include<string.h>
void main()
{
char str[25];
printf("\n Enter a String");
gets(str);
printf("\n The Reversed string is %s",strrev(str));
}
OUTPUT Enter a String : TAMMU
The reversed string is : UMMAT
strupr() function :
used to convert a string to uppercase. It takes only one
argument.
Syntax : strupr(string);
#include<stdio.h>
#include<string.h>
void main()
{
char str[25];
printf("\n Enter a String");
gets(str);
printf("\n The case changed string is %s",strupr(str));
}
Syntax : strlwr(string);
#include<stdio.h>
#include<string.h>
void main()
{
char str[25];
printf("\n Enter a String");
gets(str);
printf("\n The case changed string is %s",strlwr(str));
}
#include<stdio.h>
#include<string.h>
void main()
{
char str[25];
printf("\n Enter a String");
gets(str);
printf("\n The length of the string is %d",strlen(str));
}
Strings can also be read a character by character using the functions scanf() and getchar()
etc.,
The strcat() concatenates the second argument with the content of first argument
strcmp() compares two strings to find whether the strings are equal or not.
BASED ON
Keyword
Where it is
Declared
Storage Area
Default Initial
value
Lifetime of a
variable
1. Local or Auto or Internal variable
2. External or Global variable
3. Static variable
4. Register Variable
LOCAL VARIABLE
LOCAL VARIABLE
Auto variable are always declared within a function and they are
local to the function in which they are declared. Hence they are
also named as local variables
Keyword : auto
Declaration : Inside the function
Storage Area : Stack
Initial Value : Garbage value (At the time of compilation compiler
assigns any value)
Lifetime : Upto that function only
Example : void function1()
{
auto int x; (or) int x;
int m=10;
#include<stdio.h> printf("%d\n",m);
void function1();
void function2(); }
}
GLOBAL VARIABLE
GLOBAL VARIABLE
Keyword : extern
Declaration : Outside of the main() function
Storage Area : CPU–memory
Initial Value : zero
Lifetime : Upto the entire program
Example : void function1() {
k=k+10;
int x; (or) printf("%d\n",k); }
main() void function2()
{
main() k=k+1000;
{ { extern int printf("%d\n",k);
}
x; void function3()
} } {
k=k+10;
printf("%d\n",k); }
#include<stdio.h>
int k; //global variable
void function1();
void function2();
void function3();
void main()
{
k=20;
function1();
function2();
function3();
Static Variable
Static Variable
void main()
{
int i;
for(i=1;i<=5;i++) 0
stat(); //calling 1
} 2
3
4
/* Example 2 */
#include<stdio.h>
#include<conio.h>
void incre(); /* Function
prototype declaration */
void main()
{
clrscr(); OUTPUT
incre();
incre();
incre();
getch(); The character Stored in
} x is A
The character Stored in
void incre() x is B
{
The character Stored in
static char x=65;
x is C
printf("\n The character
stored in x is %c",x++);
}
Register
Variable
Register Variable
These variables are stored in CPU registers and hence they can be
accessed faster than the one which is stored in memory.
Keyword : register
Declaration : Inside the function
Storage Area : CPU - Register
Initial Value : Garbage value(At the time of compilation compiler
assigns any value)
Lifetime : Upto that function only
Example : register int x;
Note :
register double x; register float y;
Registers are usually a 16bit therefore it
cannot hold a float or double data type value which require 32 & 64 bytes
respectively for storing a value. But the compiler would treat as automatic
variables
void swap(int *e,int *f)
{
int *temp;
*temp=*e;
*e=*f;
*f=*temp;
printf("\n The swapped values are %d %d",*e,*f);
}
Syntax :
struct structurename variable1, variable2, ..... variable n;
Example
Struct book b1; /* b1 is a structure variable name */
Syntax :
Stru_variablename.membername;
Example
B1.pages=400;
B1.price=450.00;
Write a Program the create the Account Details using Structure?
#include<stdio.h>
struct amount
{
int ac_no;
char name[10];
int balance;
};
void main()
{
struct amount v;
printf("\nEnter the account Details");
scanf("%d%s%d",&v.ac_no,&v.name, &v.balance);
printf("The values are %d%s%d",v.ac_no,
v.name, v.balance);
printf("%d",sizeof(struct amount));
}
Initializing Structures
Like variables and arrays, structure variables can be initialized at the
beginning of the program.
The variable emp1 and emp2 of the type employee can be initialized
when it is declared as
For Example,
struct employee
{
int empno;
char
empname[20];
char
deptname[10];
float salary;
}emp[5];
Passing Structures as Arguments
A structure variable can be passed as an argument to another
function
Example
Struct date
{
int month;
int day;
int year;
};
struct account
{
int acc_no;
char name[40];
char acc_type;
float balance;
struct date dob;
} customer;
/* NESTED STRUCTURES
A structure within another
scanf("%d",&s.sno);
structure */
printf("enter the sname\n");
#include<stdio.h>
scanf("%s",s.sname);
struct dob {
printf("enter the dob\n");
int date;
scanf("%d%d%d %c",&s.sdob.date,
int month;
&s.sdob.month,&s.sdob.year,&s.sex);
int year; };
printf("%d\t %s\t %d %d %d \t %c",
struct stud{
s.sno, s.sname, s.sdob.date,
int sno;
s.sdob.month, s.sdob.year, s.sex);
char sname[10];
getch();
struct dob sdob;
}
char sex; };
void main()
{
struct stud s;
clrscr();
printf("enter the sno\n");
Session Summary
The structure definition create a new data type that can be used to
declare variables.
#include<stdio.h>
union amount
{
int acct_no;
int acct_type;
char name[10];
char street[50];
char city_state[20];
int balance;
}a;
void main()
{
printf("Enter the account Details:\n");
scanf("%d%d%s%s%d“ ,
&a.acct_no,&a.acct_type,&a.name,&a.city_state,&a.balance);
printf("The values are %d\n%d\n%s\n%s\n%d\n", a.acct_no,
a.acct_type, a.name, a.city_state, a.balance);*/
printf("%d\n",sizeof(union amount));
}
Structure Arrays
It is an single entity representing a It is an single entity representing a Collection of
Collection of variables of different data variables of same data types
types
Individual entries in a structure are called Individual entries in a array are called array
Members elements
The members of a structure are not stored The members of a array are stored in sequence of
in sequence of memory locations memory locations
All the members of a structure can be Only the first member of an array can be
initialized initialized
Individual structure elements are referred Individual array elements are accessed by its
through the use of .(dot or membership) name followed by the square braces[] within
operator which the index is placed
Initialization of elements can be done only Initialization of elements can be done during array
during structure definition declaration
Structure definition reserve enough Array declaration reserve enough memory space
memory space for its members for its elements
The keyword ‘struct’ tells us what we are There is no keyword to represent arrays
dealing with structure
Structure Union
Keyword : struct Keyword : union
Each member in a structure occupies and All the members of a union use the same memory
uses its own memory space space
More memory space is required since each Less memory space is required since all member
member is stored in a separate memory is stored in the same memory locations
locations
All the members of a structure can be Only any one member of an union can be
initialized initialized
The variables that make up the structure The variables that make up the union are called
are called Structure variable union variable
Individual structure elements are referred Individual union elements are referred through
through the use of .(dot or membership) the use of .(dot or membership ) operator
operator
The union is another compound data type may hold the variables of
different types and sizes with the compiler keeping track of the size.
The memory space reserved for a union members is large enough to store
its largest member
The keyword “union” begins the union declaration followed by the tag
(i.e., union name)
malloc()
calloc()
alloc.h
realloc()
free()
Used to allocate a contiguous block of
memory in bytes.
Note :
If the memory allocation is success it returns the
starting address else if returns NULL
Used to free (release or deallocate) the block of
unused or already used memory
free(pointer_variable);
Example 1:
ptr=(int*)malloc(4*sizeof(int));
free(ptr);
/* malloc() Function Example */
#include<stdio.h>
#include<alloc.h>
#include<process.h>
void main()
{
char *str;
if((str=(char *)malloc(10))==NULL){
printf("Not enough memory to allocate buffer\n");
exit(1);}
strcpy(str,"Helloworld");
printf("String is %s\n",str);
free(str);
}
String is
HelloWorld
malloc() Example 2
#include<stdio.h>
#include<conio.h>
void main()
{
int *ptr; //static memory allocation
clrscr();
ptr=(int *) malloc(sizeof(int));
*ptr=100;
printf("\n%u\n",ptr); //address of ptr
printf("\n%d\n",*ptr);
free(ptr);
getch();
}
*sptr=300;
Allocating Memory
The following example uses a two-dimensional array to record
marks of 5 students for 10 subjects.
It uses pointers and malloc() function, to assign memory.
Pointer Increment process
*ptr=300;
but malloc allocates memory
ptr++; // increment 2 bytes
only for 4 bytes
printf("\n ptr 4= %d\n",*ptr);
#include<stdio.h>
free(ptr);
#include<conio.h>
getch();
void main()
}
{
int *ptr; //static memory allocation
clrscr();
ptr=(int *) malloc(sizeof(int)*2);
//allocate 4 bytes
*ptr=100;
ptr++; // increment 2 bytes
printf("\n ptr 1= %d\n",*ptr);
*ptr=150;
ptr++;
printf("\n ptr 2= %d\n",*ptr);
*ptr=200;
ptr++;
printf("\n ptr 3= %d\n",*ptr);
calloc() used to allocate multiple blocks of
contiguous memory in bytes. All the blocks are of
same size.
Example 1:
ptr=(int*)calloc(5,sizeof(int));
On execution of this function 5 memory blocks of size 4 bytes
are allocated and the starting address of the first byte is assigned to the
pointer ptr of type int
/* Calloc() Function example */
#include<stdio.h>
#include<string.h>
#include<alloc.h>
void main()
{
char *str=NULL;
str=(char *)calloc(20,sizeof(char));
strcpy(str,"Welcome to world");
printf("String is %s\n",str);
free(str);
}
String is Welcome to
World
This function used to increase or decrease
the size of memory already allocated by using
malloc() or calloc() function
Here,
pointer − The pointer which is pointing the previously
allocated memory block by malloc or calloc.
size − The new size of memory block.
Here is an example of realloc() in C language,
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
printf("\nError! memory not
allocated.");
exit(0);
}
printf("\nEnter elements of array :
");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
p = (int*) realloc(p, 6);
printf("\nEnter elements of array :
");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
//REALLOC() FUNCTION EXAMPLE
#include<stdio.h>
#include<string.h>
#include<alloc.h>
void main()
{
char *str;
str=(char *)malloc(5);
strcpy(str,"Kalai");
printf("String is %s\n Address is %u\n",str,str);
str=(char *)realloc(str,5);
strcpy(str,"Sangeetha");
printf("String is %s\n New Address is %u\n",str,str);
free(str);
}
Like all variables a pointer must be declared before they are used
The indirection (or) the deferencing operator is used to access the value
of an address in a pointer
The three values that can be used to initialize a pointer are zero, null
and address
All files are automatically closed when the program, using them,
terminates, normally by main() returning to the operating system
or by a call to exit().
Types of Files:
1. Text File (or) Sequential File
2. Binary File (or) Random File
Text File :
It is a Sequence of characters. It can be organised into lines terminated by a
newline character.
Binary File :
It is a Sequence of Bytes with one-to-one correspondence to those in the
external device, that is there are no character translations.
Also the number of bytes written (or read) is the same as the number on
the external device.
It do not have any flags to indicate the end of the file. It can be
determined by the size of the file.
Basic file operations
Naming a file
Opening a file
Reading data from a file
Writing data to a file
Closing a file
Function Operation
Name
fopen() Creates a new file
Opens an existing file
fclose() Closes a file which has been opened
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads an integer from a file
putw() Writes an integer to a file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file(bytes)
rewind() Set the position to the begining of the file
It is a pointer to a structure which contains
the information about the file
FILE *file
pointername;
FILE *fp;
fp=fopen(“emp.dat”,
”w”);
Mode Name Meaning
w Open a text file for Writing
r Open a text file for Reading
a Append to a text file
rb Open a binary(random) file for reading
wb Create a binary(random) file for Writing
ab Append to a binary(random) file
r+ Open a text file for Read/Write
w+ Create a text file for Read/Write
a+ Append or create a text file for Read/Write
r+b Open a binary(random) file for read/write
w+b Create a binary(random) file for read/write
a+b Append a binary(random) file for read/write
fclose(filepointer
name);
fclose(fp);
Writing a character
The function used for writing characters to a file, that was
previously opened using fopen(), is fputc().
Syntax :
Reading a character
The fgetc() function is used for reading characters from a file
opened in read mode, using fopen().
Syntax :
String Input / Output
fputs() and fgets(), which write and read character strings to
and from disk file.
Syntax
# if # elif
# ifdef # include
# indef # define
# else # undef
# define
The # define directive contains two parts : an identifier and a
string that is to be substituted for the identifier, each time the
identifier is encountered in the source file.
#ifdef NF hai
#ifndef FORMAT
6
#define NNN N,printf("new"),N
#endif 16
#endif Compi~1.c | Feb 16 2008 | Line
#include <stdio.h> Number : 29
void main() hai
{ new
The const Keyword
It can be used to achieve almost the same effect as #define
when creating constants.
Function fscanf() & fprintf() are used to perform I/O operations in file
Function fgetc() & fputc() are used to perform Character I/O operations
in file
Function fgets() & fputs() are used to perform String I/O operations in
file