C Language Notes
C Language Notes
C - LANGUAGE NOTES
Prepared by
KAMALA KAR VANKALA
M.C.A.,
CHEEPURUPALLI
VIZIANAGARAM(DIST)
E-mail: [email protected]
OUR OTHER MATERIALS: COBOL, FOXPRO,C++,DATASTRUCTURES
Introduction of C language
Generally there are two major types of languages are available are as follows:
The set of commands available in low level is complex and not easy to
understandable. In this category " Assembly " and " machine codes " are
available. Assembly programs are faster than other high-level language
programs.
The set of commands available in high level language is very simple and
easy to understandable.
High level languages are further divided into two major categories.
C language
C++ (Object Oriented)
Java (Objected Oriented)
Smalltalk (Objected Oriented)
Pascal language
HISTORY OF C LANGUAGE
Characteristics of C language
C language was developed by Dennis Richie at AT & T Bell Laboratories in
1972. It is a general purpose, flexible ,powerful and structured programming
languge. C is used for many application. It has many inbuilt functions. It is
simple to use and easy to learn friendly,reliable and compact language. It is
case sensitive language. The variable in upper case & lower case letters have
different meaning. It has many library functions. The user can add new
functions. It is high-level language but it is called middle level language. It has
characteristics of both high-level language & low-level.
CHARACTER SET
The characters that can be used to form words, numbers and expressions
depend upon the computer which the program is run. The characters in C are
grouped into the following categories
4. White spaces
C TOKENS
These are the names of variables, functions & arrays. It consists of letters, digits &
underscore characters (_).
Rules for identifier:-
It must be from the character set.
First character must be a letter.
Special character cannot be used.
Avoid single character identifiers. Use combination of letters, digits &
underscore character.
Length must not be more than 8 characters. Some compilers allow 32
character identifiers.
Keyword cannot be used in user defined identifier.
Eg: si, sum, SUM,a5_4.
CONSTANTS
Constants in C refers to fixed values that do not change during the
execution of a program
1)Numeric Constants
a. Integer Constant
b. Real Constant
a) Integer constants
An integer constant refers to a sequence of digits.
Ex.: 426
+782
-8000
-7605
b) Real constants
Ex.: +325.34
426.0
-32.76
-48.5792
2) character constants
Symbolic contants:
Symbolic constants are the constants which are assigned to an
identifier, the identifier can represents that particular constant in the entire
program. Symbolic names are sometimes called constant identifiers. Since
the symbolic names are constants, they do not appear in the declarations.
Syntax:
#define symbolic-name value of constant
Eg:
#define STRENGTH 100
#define PASS_MARK 50
#define PI 3.14159
The following rules apply to a #define statement which define a symbolic
constant.
Operators
Variable in a C language
A variable is a quantity, which can change during program execution. It is
the name of the location in the memory of computer in which constant can be
stored. These locations can store integer, float or character constant. Variable
must be declare before it can be used in a program. Variable declaration tells the
compiler about the name of the variable and type of data which it can hold. When
a variable is declared, compiler creates space in memory & gives that name to the
space. General form of variable declaration is:
Data type list of variable separated by comma.
The type of data which a variable can store is called its data type. C language
supports following data types
These data types are derived from primary data types. These are also called
structured data types or secondary data types. They can be further divided into
arrays, function and pointers.
a) Array
An array is a collection of related data items, which have similar data type
& have a common name. It is used to represent a group of related data items. The
data items can be integer, float or character. All the data items must have same
data type & storage class.
b) Function
Here *a represents the pointer variable which can be used to store the address of
another variable.
Eg: int i=5; // address of i is 1001
Int *j;
j=&i;
*j=(&i) //Asterisk(*)
=(1001)
=5
The data types which are defined by user is known as user defined data types.
Structure, union & enum are user defined data types.
a) Structures
b) union
Union is a data type. It is similar to structure data type. Like structure, union can
also contain members of different data types. However at a time, union can hold
one member. The difference b/w structure and union is that only one member of
the union can contain a value at a given time. Whereas a structure provide
storage for each member a union provide storage for one member. The space
allotted to a union is dependent on the largest member of union.
Example:
main()
{
auto int i,j;
printf(“%d%d”,i,j);
}
Example:
Main()
{
Increment();
Increment();
Increment();
}
Increment()
{
static int i=1;
Printf(“%d”,i);
I=i+1;
for example:
main()
{
register int i;
for(i=0;i<=10;i++)
printf(“%d”,i);
}
Assignment statement:
Values can be assigned to variables using the assignment operator = as
follows
Syntax: data-type variable=constant;
Eg: int a=1000;
OPERATORS
An operators is a symbol that tells the computer to performed certain
mathematical or logical manipulation.
The various operatore in c are as follow
1. Arithmetic operators
2. Assignment operators
3. increment/ decrement operators
4. Relational operators
Program :-
main()
{
int x=5;
x+=10;
printf(“%d”,x);
getch();
}
5) Logical Operators
These operators are refered to as Boolean operators. These Operators act upon
Operators that are themselves logical expression.
After testing the value of condition it gives result,which is either true or false.
Operators Meaning
&& AND
|| OR
!! NOT
6)Conditional operators
The conditional operators are also called as “Terinary operators”. The
conditional operators are ?,:
It executes value one if the condition is true and executes value two if the
condition is false.
1 :: Left-Right
4 new,delete,size of Right-Left
5 *,%,/ Left-Right
6 +,- Left-Right
8 ==,!= Left-Right
9 & Left-Right
10 ^ Left-Right
11 ! Left-Right
12 !! Left-Right
13 ? ,: Right-Left
Input-output function are used to transfer data b/w peripheral devices and
memory. C language has no provision for reciving data from input device. It
cannot send data to the output devices. So input output operations are done by
using standard input output library functions. These functions are kept in special
library files. When a particular input output function is required in a program, the
FORMATTED FUNCTION
printf()
printf() is built-in function we can display with printf() any message, variable
value on screen/file/printer.
Here control string specifies the field of format in which the data is to be entered
and arg1,arg2,…,argn specifies the name of the variables where the data is
stored. Control string and arguments are separated by commas.
Eg1: printf(“%d%d”,a,b);
Here %d is the control string for printing an integer values. a,b specifies the
locations of the variables a and b respectively.
Here %d is the control string for printing real values. a,b specifies the locations of
the variables a and b respectively.
Eg3: scanf(“%c%c”,a,b);
Here %d is the control string for printing character values. a,b specifies the
locations of the variables a and b respectively.
Escape sequences are special notations through which we can display our data
Variety of ways:
Scanf(“control string”,arg1,arg2…argn);
Here control string specifies the field of format in which the data is to be entered
and arg1,arg2,…,argn specifies the address of the location where the data is
stored. Control string and arguments are separated by commas.
Eg1: scanf(“%d%d”,&a,&b);
Here %d is the control string for reading an integer. &a,&b specifies the address
locations of the variables a and b respectively.
Eg2: scanf(“%f%f”,&a,&b);
Here %f is the control string for reading a real number. &a,&b specifies the
address locations of the variables a and b respectively.
Eg3: scanf(“%c%c”,&a,&b);
Here %c is the control string for reading a character. &a,&b specifies the address
locations of the variables a and b respectively.
1)getch()
It is used to read a single character from keyboard. It is non buffered function.
Data is directly assigned to variable without pressing enter key. It also maintains
the output on screen until we press enter key.
Syntax: C=getch();
Consider the following example program.
Void main()
{
Char ch;
Printf(“enter any character”);
Ch=getch();/*read a character from keyword*/
Printf(“type any charcter”);
Ch=getche();
Printf(“u have entered=”);
Putchar (ch);
Getch();/*to maintain output on screen*/
}
2)getche()
It is used to read a single character from keyword. It is non buffered function.
Data is directly assigned to variable without pressing enter key. when you enter
character from keyword , it will be seen on screen. It is an echoed function. It also
maintains the output on screen until we press enter key.
Syntax:-
C =getche();
}
3)getchar()
syntax: c=getchar();
for e.g:-
main()
{
char ch;
printf(“type any charcter”);
ch=getchar();
printf(“u have entered”);
putchar(ch);
getch();
}
4)putchar() and putch()
Putch() and putchar() print a charcter on screen. They can output only one
charcter at a time.
Syntax:-putch(ch);
For e.g.-
Main()
{
Char ch=’x’;
Syntax:-gets(string);
Puts() is an o\p function. It is used to display a string on screen. It automatically
appends a new line charcter to the o\p.
Syntax:-puts(ch);
For eg.
Main()
{
Char ch[24];
Puts(“enter data”);
Gets(ch);
Puts(“Banglore”);
Puts(ch);
}
STRUCTURE OF C PROGRAM
#include<stdio.h> tells the compiler to read the file stdio.h and include its
contents in this file. stdio.h is one of the header files, contain the information
about input and output functions. stdio.h means Standard Input Output Header
file.
#include<conio.h> tells the compiler to read the file conio.h and include its
contents in this file. stdio.h is one of the header files, contain the information
about clrscr() and getch() functions. conio.h means Consoled Input Output
Header file.
Void main()
The word main followed by a pair of parenthesis(),which indicates that main
is also a function. Left brace ‘{‘ represents the beginning of the program. When
ever we found the right brace ‘}’ that indicates the ending of the program.
Clrscr () tells the compiler to clear the screen and kept the cursor at left side
corner.
Getch() is reads the single character directly from keyboard without printing on
the screen.
Comment lines: comments in the program are optional and may appear at any
where in the program. It indicates the message to the user. The comment lines
can be represented as follows
c)Program Execution
The turbo C environment, the RUN option will do the compilation and
execution of a program. Press Ctrl+F9 for execution of the program.
1. if statement
the if statement is used to control the flow of execution of the statemants.
Syntax: if(condition)
Statement;
Here , if the condition is true then the statement will be executed otherwise
the controller will comes out.
Eg: if(a>b)
Printf(“welcome to C”);
Syntax: if(condition)
{
Statement1;
Statement2;
.
.
}
Here, if the condition is true then all the statements will be executed in the
sequential order.
Consider the following example program to find out the greatest number.
int a,b;
printf(“Enter two values”); // input: 20,10.
scanf(“%d%d”,&a,&b);
if(a>b)
{
Printf(“a is the greatest number”);
}
2) if-else statement:-
It has a condition inside if bracket. If the condition is true, the statement following
if statement is executed. If the condition is false, the statement which following
else, is executed.
Syntax If(condition)
statement1;
else
statement2;
here if the condition is true the statement1 will be executed otherwise te
statement2 will be executed.
Output:
enter marks=35
sorry! u r fail
4) else-if ladder:
It is decision control statement.
Syntax:
If(condition)
Statement;
Else
During the execution of the program, the expression value is checked against each
of the specified alternatives and when a match is occurs, the block of statements
of that first match is executed.
The break statement must be included at the end of each case. Incase, if it
is omitted, the control after executing a block of statements and also proceeds
into the next subsequent case, even though match has already taken place.
output
enter day=1
monday
enter day=8
enter correct day
1. for loop: It is a looping statement which repeat again & again till some
condition is satisfied.It contains three expressions in a single line. First
expression indicates initialization, the second expression indicates
condition and the third expressin indicates
incrementation/Decrementation.
for(exp1;exp2;exp3)
{
Block of statements;
}
The expression1,expression2,expression3 may not present in a loop
For( ; ; )
{
Block of statemens;
}
//Initialize counter the used to initialize the variable. Test counter test the
condition. Increment counter increment the value of the variable.
#include<stdio.h>
#include<conio.h>
Void main()
{
int i;
clrscr();
Nesting loops
Loops can be nested one inside the other.
#include<stdio.h>
#include<conio.h>
Void main()
{
int i,j;
Clrscr();
for(j=1;j<=9;j++)
{
printf(“\n”);
for(i=1;i<=j;i++)
{
printf(“%d\t”,i);
}
}
getch();
}
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
3. Do-while loop:It is an exit control loop. First the statements are executed &
then the condition is checked. The statements are executed once even if the
condition fails at the beginning.
Syntax:
Do
{
Statement1;
Statement2;
}
While(test counter) Do
{ {
Statement; Statement 1;
Statement; Statement 2;
Increment/decrement counter; }
} While(comdition);
Goto statement is used to change the normal sequence of program. It takes the
control to some other part of the program.
syntax:
goto label;
label;
statement;
#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
goto forward;
sum=a+b;
printf(“sum=%d”,sum);
forward:
printf(“enter a,b=”);
scanf(“%d%d”,&a,&b);
getch();
}
Break statement
Break statement is used to exit from a loop. It can be used with while loop,do-
while,if statement & switch statement.
Eg: while(condition)
{
Statement1;
Statement2;
#include<stdio.h>
#include<conio.h>
Void main()
{
int i;
clrscr();
for(i=0;i<=10;i++)
{
printf(“%d\t”,i);
if(i==8)
break;
}
getch();
}
Output
1 2 3 4 5 6 7 8
Continue statement
A Continue statement returns the control to the beginning of the repeating loop.
Eg: while(condition)
{
........;
........;
If(n==0) continue;
. . . . . . . .;
. . . . . . . .;
}
#include<stdio.h>
#include<conio.h>
Void main()
{
int i,j;
clrscr();
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
if(i==j)
continue;
printf(“%d\t%d”,i,j);
}
}
getch();
}
Output
1 2
2 1
Structured Programming:
ARRAYS
An array is a collection of similar data items,which have similar data type and
have a common name is used to represent a group of related data items. The data
items can be integer,float or character. All data items must have same data type
and storage class. The first element in the array is numbered 0 and last element is
one less than the size of array. Array is also known as subscripted variable.
Array are of two types
City is the name of an array. It can stored 100 char data type values.
Array can be initialized by giving initial values. These values must be enclosed in
braces and seprated by a comma.
1 2 3 4 5
Marks[0] Marks[1] Marks[2] Marks[3] Marks[4]
These arrays are used to store the data in the form of row, column format.
#include<stdio.h>
#include<conio.h>
void main()
{
int student[4][2];
#include<stdio.h>
#include<conio.h>
Void main()
{
int marks[6]={10,20,30,40,50,60};
int i;
clrscr();
for(i=0;i<=5;i++)
printf(“%d\t”,marks[i]);
getch();
}
output:10 20 30 40 50 60
STRINGS
A string is nothing but a “group of characters ” or “character
array”. Each character occupies one byte of memory, and the last character is
always ‘\0’(null character). For example, the string SYSTEM would be stored as
or
The scanf() and printf() function used with %s with format specification to read
and print a string.
Example:
Char str[25];
Scanf(“%s”,str);
printf(“%s”,str);
In the case of reading strings, the ampersand(&) is not required before the
string variable name. As mentioned earlier, one of the limitations of the scanf() is
that it is not capable of holding multiword strings, even though it can read them.
To overcome this problem, we can use gets() function in place of scanf() function.
Similarly puts() function can be used in place of printf().
1) Strlen()
2) Strlwr()
3) Strupr()
4) Strrev()
5) Strcpy()
6) Strcat()
7) Strcmp()
8) Stricmp()
Syntax: strlen(string );
Eg: #include<stdio.h>
#include<string.h>
Void main()
{
char s1[25];
printf(“Enter String:”);
gets(s1);
printf(“Total no.of characters are %d ”,strlen(s1));
}
In put: Enter string:Hello World
Out put : Total no.of characters are 11
Syntax: strlwr(string);
Eg: #include<stdio.h>
#include<string.h>
Void main()
{
char s1[25];
printf(“Enter String:”);
gets(s1);
printf(“ %s ”,strlwr(s1));
}
Eg: #include<stdio.h>
#include<string.h>
Void main()
{
char s1[25];
printf(“Enter String:”);
gets(s1);
Printf(“ %s ”,strupr(s1));
}
Syntax: strrev(string);
Eg: #include<stdio.h>
#include<string.h>
Void main()
{
Char s1[24];
Printf(“Enter String:”);
gets(s1);
Printf(“ %s ”,strrev(s1));
}
Eg: #include<stdio.h>
#include<string.h>
Void main()
{
Char s1[25],s2[25];
Printf(“Enter two String:”);
gets(s1,s2);
Printf(“ %s ”,strcat(s1,s2));
}
In put: Enter two strings: Hello World
Welcome to C
6)strcpy(): This function copies the content of one string into another string.
Syntax: strcpy(string1,string2);
Here strcpy() is used to copy the character from string2 to string1. The function
returns the result string string1 the string2 remains unchanged. String2 may be a
character array or a string constant.
Eg: #include<stdio.h>
#include<string.h>
Void main()
{
char s1[25],s2[25];
Printf(“Enter String s1:”);
gets(s1);
Printf(“ The string s2 is : %s ”,strcpy(s2,s1));
}
In put: Enter string s1: Hi this is Kamal
7)strcmp(): This function compares two strings to determine whether the are
same or not. The two strings were compared character by character until there is
a match in string (or) end of the string. If two strings are equal, it returns a value
“0”. Otherwise it returns numeric difference between ASCII value of non matching
characters.
Syntax: strcmp(string1,string2);
In the above syntax, the function returns less than “0” if string1 is less than
string2, and greater than “0” if string1 is greater than string2.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[25],s2[25];
int c;
clrscr()
printf(“Enter String s1:”);
gets(s1);
printf(“Enter String s2:”);
gets(s2);
c=strcmp(s1,s2);
if(c>0)
printf(“string1>string2”);
else if(c<0)
printf(“string1<string2”);
else
printf(“both strings are equal”);
getch();
}
Output:
String1>string2
FUNCTIONS
A function a self contained block of statements that perform a
specific task. Function are also called sub programs.
SYNTAX:-
Return type functionname (datatype arg1,datatype arg2,…………)
{
body of function
………………….
………………….
………………….
return (expression);
}
Features of functions:
a) Function Declaration and prototypes.
b) Calling functions by value or by reference
c) Recursion
Category of functions:
A function, depending on whether arguments are present or not and
whether a value is returned or not, may belong to one of the following categories
1) Functions with no arguments and no return values
2) Functions with arguments and no return values
3) Functions with arguments and return values
#include<stdio.h>
#include<conio.h>
void swap(int, int); Function declaration
void main()
{
int a,b;
clrscr();
printf(“Enter 2 numbers :”);
scanf(“%d%d”,&a,&b);
swap(a,b); Function call
getch();
}
void swap(int x, int y) Called function
{
int z;
z = x;
x = y;
y = z;
printf(“\n After swapping : %d%d”, x,y);
#include<stdio.h>
#include<conio.h>
int big(int, int);
void main()
{
int a,b,max;
clrscr();
Arguments: These are variables, which are passed to the function at the time of
function call.
Parameters: These are the variables, which are present in the first line of function
definition.
2.User defined functions;-A function, which is defined by the user & does some
useful work,is called user-defining function.
For ex:- akhil(); student();etc.
Use of function
Large programs are difficult to understanding so they are divided into
functions.
Function are easy to write,understand & debug.
Different programs can use a single function.
Library function can be attached to the program.
Function can be reused in other programs.
Library functions save time & space.
Function are independent of system.
Program design become easy and program can be executed fast.
Coding becomes compact with the help of functions.
Debugging of program becomes easy.
Memory is efficiently used.
Program complexity is reduced.
Execution speed are increase.
User defining function are more flexible.
Testing becomes easy.
Program reliability is high.
How a function can be declared?
Every function must be declared to the compiler before using it in the program.
<returntype><datatype><fuctionname>(arguments);
#include<stdio.h>
#include<conio.h>
int calsum(int,int);
void main()
{
int a,b,sum;
clrscr();
printf(“enter the a,b=”);
scanf(“%d%d”,&a,&b);
sum=calsum(a,b);
getch();
}
int calsum(x,y);
int x,y;
{
int c;
c=x+y;
return(c);
}
What is the purpose of main() function?
The function main() invoke other functions in it. It is the first function to be called
when the program starts execution. Program execution always starts with the
function of main().
Any changes done to the formal parameters have no effect on the actual
parameters, because they have separate memory locations.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20;
swap v(a,b);
printf(“a=%d b=%d”,a,b);
}
Kamalakar Vankala MCA., Cheepurupalli -9032986572 Page 64
swap v(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
print(“x=%d y=%d”,x,y);
}
output;- x=20 y=10
a=10 b=20
CALL BY REFERENCE
According to this mechanism, the address of each actual parameters can be
copied into corresponding formal parameters. The formal parameters are pointer
variables and they are pointing to same memory location of the corresponding
actual parameters.
Any changes done to the formal parameters have to effect on the actual
parameters, because they have single memory locations
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20;
swap v(&a,&b);
printf(“a=%d b=%d”,a,b);
}
swap v(int *x,int *y);
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
a=20,b=10
FUNCTIONS WITH ARRAYS
Like the values of simple variables, it is also possible to pass the values of an array
to a function. To pass an array to a called function, it is sufficient to list the name
of the array, without any subscripts, and the size of the array as arguments. For
example, the call
largest(a,n);
will pass all the elements contained in the array ‘a’ of size ‘n’. The called function
expecting this call must be appropriately defined. The largest function header
might look like:
int largest(array,size);
int array[];
int5 size;
Example Program for sorting of an array elements
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
int marks[5];
clrscr();
printf(“Enter 5 sub marks:”);
for(i=0;i<=4;i++)
scanf(“%d”,&marks[i]);
printf(“\nMarks before sorting \n”);
for(i=0;i<=4;i++)
printf(“%d”,marks[i]);
sortmarks(marks,5);
printf(“\nMarks after sorting \n”);
for(i=0;i<=4;i++)
printf(“%d”,marks[i]);
getch();
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,fact;
printf(“enter any num=”);
scanf(“%d”,&a);
fact=rec(a);
printf(“factorial=%d”,fact);
}
int rec (int x)
{
int f;
if(x==1)
return(1);
else
f=x*rec(x-1);
return(f);
}
Advantages of Recrsion
• with the help of recrsion, the program code is compact,each to write and
understand.
• Program code is compact.
• It can be used to solve mathematical problem.
• Useful in multiprocessing and multitasking.
• Compilation time of the program is less.
• Can be used to solve problem of data structures.
• It saves memory.
Disadvantage
Local variable:- The variable, which are declared within the body of a function,
they are called local variables of that function. They can be used in that function
only.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum;
Output: sum=30
Global variable:
Local variables are declared within the body of a function, and can only be used
within that function. This is usually no problem, since when another function is
called, all required data is passed to it as arguments. Alternatively, a variable can
be declared globally so it is available to all functions. Modern programming
practice recommends against the excessive use of global variables. They can lead
to poor program structure, and tend to clog up the available name space.
A global variable declaration looks normal, but is located outside any of the
program's functions. This is usually done at the beginning of the program file, but
after preprocessor directives. The variable is not declared again in the body of the
functions which access it.
Example:
#include<stdio.h>
#include<conio.h>
int a,b;
void main()
{
int sum;
clrscr();
a=20;
b=10;
sum=a+b;
printf(“sum=%d”,sum);
getch();
}
For example:
#ionclude<stdio.h>
#include<conio.h>
int x=20; //external variable definition
void main()
{
extern int x; //external variable declaration
clrscr();
print(“%d”,x);
}
struct student
{
char name[10];
Example :
#include<stdio.h>
#include<conio.h>
struct personal
{
Char name[20];
Int day;
Char month[10];
Int year;
Float salary;
}
void main()
{
struct personal person;
clrscr();
printf(“Input values\n”);
Array of structure
We can declared array of structures to declare many structure variable.
Example;
Struct example
{
Int roll no;
Char name[20];
Float marks[10];
};
Struct example student[100];
Example:
struct salary
{
char name[20];
char dept[10];
struct
{
int dearness;
int house_rent;
int city;
}allowance;
}employee;
In the above example , the salary structure contains a member named allowance
which it self is a structure with three members. The members contained in the
inner structure namely dearness, house_ rent, and city can be referred to as
employee.allowance.dearness
employee.allowance.house_rent
employee.allowance.city
Features of a structure
It permits different data types.
We can make an array of structures.
Pointer to a structure can be made.
Structures can be nested.
Self referential structure can be defined.
Union can be a member of structure.
The member of a structure can be accessed and manipulated.
UNIONS
Unions are a concept which is similar to structures, therefore the syntax of the
unions are also same as structures. However, there is a major difference between
them in terms of storage. In structure each member has its own storage location,
where as all the members of a union use the same location. This implies that,
although a union may contain many members of different types , it can handle
only one member at a time. Like structures, a union can be declared using the key
word union as follows:
Eg:
Union item
{
int m;
float x;
char c;
} code;
The union contains three members, each with a different data type.
However, we can use only one of them at a time. This is due to the fact that only
one location is allocated for a union variable, irrespective of its size. The compiler
allocates a piece of storage that is large enough to hold the largest variable type
in the union. In the declaration above the member ‘x’ requires 4 bytes which is
the largest among the members.
Type def:
C provides the “typedef” key word that allows you to specify a new name
for a data type already provided in C programming language. That means, we can
use the type def keyword to specify an identifier for an existing data type.
Syntax:
typedef data-type new name;
Eg:
Typedef int num;
Here the new identifier “num” has been specified for “int” data type.
Size of structures:
We can use structures, unions and arrays to create variables of large sizes.
The actual size of these variables in terms of bytes may change from machine to
machine. We may use the unary operator “sizeof” to tell us the size of structure
(or any variable).
Syntax:
Sizeof(struct structure -name)
(Or)
Sizeof(structure variable)
Eg:
Sizeof(struct x)
(Or)
Sizeof(y)
Here y be the simple structure variable.
POINTER
Pointer is a memory address variable,which points to a location in memory. It
contains memory address of another variable or array element.
Example:
int i=5;
int *j;
j=&i;
here i is a variable which stored value 5 at some location in memory. Let
the address of this memory location is 1001. j which is a pointer variable will store
Example;
Int *ptr;
a[1]=*(b+1);
a[2]=*(b+2);
a[3]=*(b+3);
a[4]=*(b+4);
let us explain this with a program.
void main()
{
int a[6]={5,10,15,20,25,30};
int i,n=6,*b;
clrscr();
b=a;
printf(“array a contain following data\n”);
for(i=0;i<6;i++)
printf(“%d\t”,*(b+1));
printf(“\n data in reserve order is”);
for(i=6;i<6;i--)
printf(“%d”,*(b+1));
getch();
}
OUTPUT: array a contain following data
5 10 15 20 25 30
Data is reserve order is
30 25 20 15 10 5
Many languages permit a programmer to specify an array’s size at run time. The
process of allocating memory at run time is known as dynamic memory
allocation.
Dynamic memory allocation can be done using the following functions.
1. Malloc()
2. Calloc()
3. Free()
4. Realloc()
5. Delete
6. New
The above functions are known as memory management functions.
Malloc()
The malloc() can be used to allocate the block of memory. If the allocation of
memory is done successfully, then starting address of the location returned to a
pointer. If the memory allocation cannot be done, then a “null pointer” will be
returned.
Suppose ‘p’ is a pointer variable, and if it should points to a block of ‘n’
memory locations then the ‘n’ memory locations can be used by the following
syntax
Syntax: ptr=(cast-type*)malloc(byte-size);
E.g: Int *p
p=(int *)malloc(n*size of(int));
If ‘p’ is null then the memory allocation is done, then starting address of
these ‘n’ locations will be returned to a “void pointer”. This void pointer is
converted into an integer pointer by using the concept “type casting”
Calloc()
It is similar to malloc() except that, it requires 2 parameters. The calloc() can be
declared using the following syntax.
Kamalakar Vankala MCA., Cheepurupalli -9032986572 Page 82
Syntax: ptr=(cast-type*)callo(n,elem-size);
E.g: Int *p
p=(int *)calloc(n,size of(int));
the major difference between malloc() and calloc() is the memory allocated
by malloc() contains all garbage values where as memory allocated by calloc()
contains all “zero” values.
Free()
This function is used to release the memory dynamic allocation functions. While
using any of the above functions a header file <alloc.h> must be included.
Syntax: free(ptr);
Eg: free(p);
Where ‘p’ is a pointer variable.
Realloc()
Modifies the size of previously allocated space. If the previously allocated
memory is not sufficient and we need additional space for more elements. It is
also possible that the memory allocated larger than necessary and we want to
reduce it. In both the cases, we can change the memory size already allocated
with help of the function realloc(). This process is called the reallocation of
memory. For example, if the original allocation is done by the statement
Ptr=malloc(size);
Then reallocation of space may be done by the statement
Ptr=realloc(ptr, newsize);
If the reallocation of memory is done successfully, it returns a pointer to the first
byte of the new memory block. Otherwise it returns a NULL pointer and original
block is freed(lost).
Delete
The delete operator is used to release the memory space for reuse. The general
form of declaration is
Syntax: delete pointer-variable;
Eg: delete p;
Where ‘p’ is a pointer variable.
Naming a file
Opening a file
Reading data from a file
Writing data to file, and
Closing a file
fopen() Creates a new file for use, Opens an existing file for
use
fclose() Closes a file which has been open for use
getc() Reads a character to a file
putc() Writes a character to afile
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 file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
FILE *fp;
fp=fopen(“filename”, “mode”);
The first statement declares the variable fp as a “pointer to the data type
FILE”. As stated earlier. File is a structure that is defined in the I/O library.
The second statement opens file named “filename” and assigns an
identifier to the FILE type pointer fp. This pointer contains all the
information about the file is subsequently used as communication link
between the system and the program.
The second statement also specifies the purpose of opening this file.
The mode does this job. Mode can be any one of the following.
Mode Purpose
FILE *p1,*p2;
p1 =fopen(“data”, “r”);
p2 =fopen(“results”, “w”);
CLOSING A FILE:
Syntax:
fclose(file_pointer);
Eg:
……….
……….
FILE *p1,*p2;
p1 = fopen(“INPUT”, “w”);
p1 = fopen(“OUTPUT”, “r”);
………
………
fclose(p1);
fclose(p2);
• getc()
• putc()
• fprintf()
• fscanf()
The simplest file I/O functions are getc() and putc(). These are analoguos to
getchar() and putchar() and handle one character at atime. Assume that a file is
opened with mode ‘w’ and file pointer fp1. Then, the statement
putc(c,fp1);
Writes the character contained in the character variable c to the file associated
with FILE pointer fp1. Similarly, getc is used to read a character from a file that
has been opened in read mode. For example, the statement
C=getc(fp2)
Would read a character from the file whose file pointer is fp2.
The file pointer moves by one character position for every operation getc or
putc. The getc will return an end –of-file marker EOF, when end of the file has
been reached. Therefore, the reading should be terminated when EOF is
encountered.
Example program for writing to and reading from a file
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1;
char c;
clrscr();
printf(“Data Input \n\n”);
f1=fopen(“INPUT”, “w”);
while(c=getchar() != EOF)
putc(c,f1);
fclose(f1);
printf(“\n data output \n\n”);
f1=fopen(“INPUT”, “r”);
while(c=getc(f1) != EOF)
printf(“%c”,c);
fclose(f1);
getch();
fprintf():
The functions fprintf and fscanf perform I/O operations that are identical to
printf and scanf functions, except of course they work with files. The general form
of fprintf is shown below.
Syntax:
fprintf(fp, “control string”, list);
where fp is a file pointer associated with a file that has been opened string. The
control string contains output specifications for the items in the list. The list may
include variables, contains and strings.
Eg:
fprintf(f1, “%s%d%f”, name, age, 7.5);
fscanf():
The general format of fscanf is shown beliow
Syntax:
fscanf(fp, “control string”, list);
Eg:
fscanf(f2, “%s%d”, item, &quantity);
Output:
Enter n value: 8
Factorial is: 40320
#include<stdio.h>
#include<conio.h>
void main ( )
{
int n,rem,rev=0;
clrscr( );
printf(“enter n value”);
scanf(“%d”,&n);
while(n!=o)
{
rem =n%10;
rev=rev*10+rem;
n=n/10;
}
printf(“%d”,rev);
getch();
}
EXAMPLE:-
N rem=N%10 rev=rev*10+rem N=N/10
456 6 =0*10+6 45
= 0+6
=6
45 5 =6*10+5 4
=60+5
=65
4 4 =65*10+4 0
=650+4
=654
PROGRAM:-
#include<stdio.h>
#include<conio.h>
void main ( )
{
int n,rem,rev=0;
clrscr( );
printf(“enter n value”);
scanf(“%d”,&n);
while(n!=o)
{
rem =n%10;
rev=rev*10+rem;
n=n/10;
}
if(rev==n)
printf(“given number is a palendrom”);
else
printf(“given number is not a palendrom”);
getch( );
}
PROGRAM:-
#include<stdio.h>
#include<conio.h>
void main ( )
{
int n,rem,sum=0;
clrscr( );
printf(“enter n value”);
scanf(“%d”,&n);
while(n!=o)
{
rem =n%10;
rev=rev*10+rem;
n=n/10;
}
if(sum==n)
printf(“n is a armstrong number”);
else
printf(“n is not a armstrong number”);
getch( );
}
*
**
***
****
*****
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d“,j);
}
printf(“\n”);
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d“,i);
}
printf(“\n”);
}
getch();
}
Output:
enter how many numbers 5
enter n elements in an array: 10 20 30 40 50
enter an element for searching:30
the search element is found
Flow chart:
Flow chart is a pictorial representation of a program. In this representation
we have to use different types of symbols for both input and output statements.
The symbols are shown below.
Programming in “C-Language”
Int a,b,sum
Read
a,b
sum=a+b
Print sum
stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum;
Flow chart:
start
Int a,b,sub
Read
a,b
sub=a-b
Print sub
stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
Flow chart:
start
Int a,b,mul
Read
a,b
mul=a*b
Print mul
stop
Flow chart:
start
Int a,b,div
Read a,b
div=a/b
Print div
stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,rim;
printf(“Enter Values for a,b”);
scanf(“%d%d”,&a,&b);
rim=a%b;
printf(“The Result is is %d”,rim);
}
Flow chart:
start
Int a,b,rim
Read
a,b
rim=a%b
Print rim
stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(“Enter Values for a,b”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“a is big”);
else
printf(“b is big”);
}
start
Int a,b
Read
a,b
false
If(a>b)
stop
Algorithm:
Step 1: Start
Step 2: Initialize a,b,c.
Step 3:Read a,b,c.
Step 4: check if(a>b).
Step 5: If step 4 is true check if(a>c) .
Step 6:If step 5 is true print “a is big”.
Step 7:If step 4 is false print “b is big”.
Step 8:If step 4 is false check(b>c).
Step 9:If step 8 is true print “b is big”.
Step 10:If step 8 is false print “c is big”.
Step 11: Stop.
if(a>b)
{
if(a>c)
printf(“a is big”);
else
printf(“c is big”);
}
else
If(b>c)
Printf(“b is big”);
else
Printf(“c is big”);
}
start
Int a,b
Read a,b
If(a>b)
false
true
If(b>c)
false
false
If(a>c)
true
Print c is big
true
Print c is big Print b big
Print a big
stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int N,sum=0,i=1;
printf (“Enter Number of Values to add”);
scanf (“%d”,&N);
while(i<=N)
{
Sum=sum+i;
i++;
}
Printf(“The sum is %d”,&sum);
}
Int N,sum=0,i=1
Read N
While(i<=N) false
true
sum=sum+i
i=i+1
Print sum
stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int N,i=1;
printf (“Enter Number of Values to print”);
scanf (“%d”,&N);
while(i<=N)
{
Printf(“%d”,i)
i++;
}
}
Int N,i=1
Read N
While(i<=N) false
true
Print i;
i=i+1
stop
KAMALAKAR VANKALA
M.C.A.,
Cheepurupalli,
Vizianagaram(Dist).
E-mail: [email protected]
Mobile: +91 9032986572
Kamalakar Vankala MCA., Cheepurupalli -9032986572 Page 117