Anda di halaman 1dari 53

‘C’ Language Guide

By

Sambaraju

Sambaraju, ASTRA
‘C’ Language Guide

INDEX
1. Concepts

 Introduction to Language
 History Of C
 C Basics
 Operators
 Control Statements
 Arrays
 Strings
 Structures
 Functions
 Pointers
 Storage Classes
 Files,Command line arguments
 Advance C

2. Interview Question &Answers


3. List of Practice Programs

Sambaraju, ASTRA
‘C’ Language Guide
Introduction to Language

Language:In General Language means “way to communicate”


Def: The set of statements is called Language

Instruction: It is a command given to the computer to perform a task


Program: The set of Instructions is called Program
Programming: It is a process of preparing Instructions
Steps:
 Logic preparation
 Coding
 Compilation/transformation
 Execution

Basically programming Languages are of 2 types


 High level Language
 Low level Language
1. Machine Level(numbers)
2. Assembly level(mnemonics)

Translators/Language Converters: These are used to convert one language


into
Another language.

Source  Destination

 Assembler (Low Level)


 Compiler (High Level)
 Interpreter (High Level)
Assembler:It is for Assembly Programming. It converts assembly into
machine
Compiler: It translates high level into machine level
It executes instruction at single step
Interpreter: It translates high level into machine level
It executes instruction line – by -line

General Problem solving Techniques

 Define an Algorithm
 Draw the flow chart
 Write the code(in any language)
 Debug and run the code

Algorithm:It is a method of representing the step-by-step logical procedure


for solving a problem
Sambaraju, ASTRA
‘C’ Language Guide
Properties/features of Algorithm:-
 Finiteness
 Definitness
 Effectiveness
 Generality
 Input/output

Eg:Write an algorithm to find avg of 3 numbers

Step1: Start
Step2: Read the numbers a,b,c
Step3: Calculate the sum of a,b,c
Step4: Divide the sum by 3
Step5: store the result in d
Step6: Print the value of d
Step7: Stop

Flow Chart:It is graphical representation of an Algorithm


In this logic of program is clearly represented
In this we use different types of symbols

Eg:Avg of 3 numbers

Sambaraju, ASTRA
‘C’ Language Guide
History of C
History Of C :
 First C developed on UNIX operating system and it was coded in low
level language in 1969.(PDP-7 assembly language).
 After that "Martin Richard" developed BCPL language. BCPL is in
assembly language and error prone
 Thereafter B language is developed by "Ken Thomson". B is a high
level language and it has typical functionality
 Thereafter based on B language finally C language is developed in 1973
by "Dennis Ritchie". And C is a middle level language
.
Features Of C :

 Efficient - C language is very efficient due to built functions.


 Fast - Due to conditional statements and control statements.
 Structured - Module Programming
Programming
 Portability - C program written for one computer can run in other
computer (With different Operating systems) with some modifications
Or some modifications.

Characteristics Of C :

 Small size
 Extensive use of function calls
 Loose typing
 Structured programming
 Low level (BitWise) programming readily available
 Top-down Approach
 Pointer implementation - extensive use of pointers for memory, array,
 structures and functions.

Advantages And Disadvantages Of C:


Advantages of C:
In c, Programmers can create and maintain a unique library functions which
can
be used by many different programs. Thus large projects can be managed easily
with minimal duplication of effort.
Disadvantages Of C:
Its main drawback is that it has poor error detection which can make it off
putting to the beginner. However diligence in this matter can pay off
handsomely since having learned the rules of C we can break them. Not many
languages allow this. This if done properly and carefully leads to the
power of C programming.

Sambaraju, ASTRA
‘C’ Language Guide
C Basics
Structure of C Language :
1. Documetation Section [optional]
/*------------*/
2. Link Section
#include<filename>
3. Definition of constants [optional]
#define variable value
4. Global variable declaration [optional]
datatype variable
5. main()
{
declaration;
executable statements;
}
6. Sub functions
Datatypes in C Language :
Datatype:Datatype tells which type of data we are giving as the input.
The following are the datatypes available in c-Language.
* Primary Datatypes
* Derived Datatypes
* User defined Datatypes
Primary Datatypes
Type Size Of Bits Range
char 8[1 byte] -128 to 127
Unsigned char 8[1 byte] -128 to 127
signed char 8[1 byte] -128 to 127
int 16[2 bytes] -32,768 to 32,767
signed int 16[2 bytes] -32,768 to 32,767
short int 16[2 bytes] -32,768 to 32,767
Unsigned short int 8[1byte] 0 to 65,535
signed short int 8[1 byte] 0 to 65,535
-2,147,483,647 to 2,147,483,646
long int 32[4 bytes]
unsigned long int 32[4 bytes] 0 to 4,294,967,295
float 32[4 bytes] 6 digits of precision
double 64[8 bytes] 10 digits of precision
long double 128[16 bytes] 10 digits of precision
Derived Datatypes - Arrays, strings
User defined Datatypes - structures, unions
C Tokens:
C token is an individual word present in the c-language. There are 6 types
 Keywords: keywords are defined by the software with the specified
meaning(In c language 32 keywords are there )
auto Break case char const continue default do
double Else enum extern float For goto If
int Long register return short signed sizeof Static
struct Switch typedf union unsigned Void volatile while
Sambaraju, ASTRA
‘C’ Language Guide
 Identifiers:User defined variable names.
 Constants: The value which is not changed during the execution
 Strings: Group of caharacters enclosed in " "
 Operators: The following are the operators available in c
1. Arthematic Operators: [+,-,*,/,%]
2. Assignment Operators: [=]
3. Relational Operators: [<,<=,>,>=,==,!=]
4. Logical Operators: [and,or,not]
5. increment/decrement Operators:[++,--]
6. Bitwise Operators: [&,|,~,^,>>,<<]
7. Conditional or terinary Operator:[?:]
 Special characters:
, (comma) -to seperate 2 variables
sizeof Operators -returns the size of the variable

Input /Output Functions:


The input and output functions are
printf() output
scanf() input
putchar() output
getchar() input
puts() output
gets() input
printf(): printf() used to display the content on the screen which is written with
in the quotation marks.
* Used to display the output by using conversion specifies/conversion
specifiers
* Returns no. of characters printed on the screen.
Syntax: - printf(“control string”,list of variables);

eg1:prints the simple message eg2:prints sum of 2 nos


#include <stdio.h> #include <stdio.h>
main() main()
{ {
printf("Welcome to c world"); int a=2,b=3,c;
} c=a+b;
printf("c=%d",c);
o/p:Welcome to c world }
o/p:c=5
eg3: prints more than one value eg4: prints no.of characters
#include <stdio.h> #include <stdio.h>
main() main()
{ {
float f1=3.5,f2=2.5,sum,diff; int i;
sum=f1+f2; i=printf("welcome%d",i);
diff=f1-f2; }
printf("%f %f",sum,diff); o/p:7
}
o/p:6.0 1.0
Sambaraju, ASTRA
‘C’ Language Guide

scanf():It is used to read the data from the input device (keyboard).
scanf() Returns no.of inputs taken from the keyboard

Syntax: - scanf(“control string”,&list of variables);

eg1:Program for reading integer data eg2:Reading character data form the
from the keyboard keyboard
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int a,b,c; char surname;
printf("Enter values for a,b"); char name[100];
scanf("%d %d",&a,&b); printf("enter surname");
c=a+b; scanf("%c",&surname);
printf("a+b=%d",c); printf("enter name");
} scanf("%s",name);
Here %d conversion specifier says to printf("%c.%s",surname,name);
scanf() to take integer data and }
& says the address of the varibale in
the memory

Short cut keys for compiling C-Program:

F2 - To save the c-program file


Alt+F9 - Compile
Ctrl+F9 - To run the c-program
Ctrl+F7 - Add Watch
Alt+F5 - To View the result.
F7 - Trace
F1 - Help
Alt+F - File
F3 - Load
Alt+X - Quit

Three files will be generated when compiling the C-program

.bak - backup file


.obj - objective file (machine language)
.exe - executable file

Sambaraju, ASTRA
‘C’ Language Guide
Operators
In C, there are some unusual operators used to perform the task of logical
decision making. The following are the operators availble in C.

 Arthematic Operators
 Assignment Operators
 Relational Operators
 Logical Operators
 Equality Operators
 Special Operators
Arithmetic Operators: Arithmetic operations are the basic and common
operations performed using any computer programming. Normally, these
operators are considered as basic operators and known as binary operators as
they require two variables to be evaluated. For example if we want to multiply
any two numbers, one has to enter or feed the multiplicand and the muliplier.
That is why it is considered as a binary operator. In c, the arithimatic operators
used are as follows:

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Ex
main()
{
int a,b,c,d,e,f,g;
a=5,b=2;
c=a+b; /*adds a,b and stores in c */
d=a-b; /*subtracts a,b stores in d*/
e=a*b; /*multiplies a,b stores in e*/
f=a/b; /*divides a,b stores co-efficient value in f*/
g=a%b; /*divides a,b stores the remainder value in g*/
printf("%d/t%d/t%d/t%d/t%d",c,d,e,f,g);
}
The o/p will be: 7 3 10 2 1

Assignment Operators:An assignment operator is used to assign back to a


variable, a modified value of the present holding.

Operator Meaning

Sambaraju, ASTRA
‘C’ Language Guide
= Assign right hand side value to the left hand side
+= Value of LHS variable will be added to the RHS and assign it back
to the varible in LHS
-= Value of LHS variable will be subtracted to the RHS and assign it
back to the varible in LHS
*= Value of LHS variable will be multiplied to the RHS and assign it
back to the varible in LHS
/= Value of LHS variable will be divided to the RHS and assign it
back to the varible in LHS
%= The reminder will be stored back to the LHS after integer
division carried out between the LHS variable and the RHS variable

Relational Operators: For the program flow, the relational operators are
required. Relational operators compare values to see if they are equal or if one
of them is greater than the other so on. Relational operators in C produce only
one or zero result. These are often specified as "true" or "false" respectively.
The following operators are used to perform the relational operations of the two
variables or expressions.

Operator Meaning
< Lessthan
> Greaterthan
<= Lessthan or
equal to
>= Greaterthan or
equal to
The relational operators are represented in the following syntax
exp1 relational_Opertor exp2
The exp1 will be compared with exp2 and depending upon the relation like
greaterthan, greaterthan or equal to and so on. The result will be either
"true" or "false".
Ex:
Expression Result
3>4 false
6<=2 false
10>-32 true

Logical Operators:For the program flow the logical operators are required. The
following are the logical operators
Operator Meaning
&& Logical AND

|| Logical OR

! Not

Sambaraju, ASTRA
‘C’ Language Guide
Logical AND: A compound expression is true when two
conditions(expressions) are true. To write both conditions, the operator && is
used in the following manner
exp1 && exp2
In the two expressions, the conjunction must be integers. The char data are
converted to integer and are thus allowed in the expression.
Logical OR: The logical OR has the following form
exp1 || exp2
and evaluates to true if either exp1 or exp2 is true.
Logical negation operator: A logical expression can be changed from false to
true or from true to false with the negation operator !. And it has the
following form
!(exp)

Equality Operators: The following operators are used to check the equality of
the given expression or a statement. These operators are normally represented
by using the two keys namely "equal to" by the operator "==" and "not equal
to" by the operator !=
The equality operators produce the result either "true" or "false"
ex:
a=4; b=6; c=8;
expression Result
a == b false
's' == 'y' false

Special Operators:In C, there are some special operators to perform particular


type of operation.
Unary Operators: The unary operators require only a single expression to
produce a line. Unary operators usually precede their single operands.
Sometimes some unary operators may be followed by the operands such as
incrementer and decrementer. The most common unary operation is unary
minus
where minus sign precedes a numerical constant, a variable or an expression.
The following are the unary operators in C
(a) Pointer Operator(*) : The pointer operator is used to get the content of the
address operator pointing to a particular memory element or cell.
(b) Address Operator(&) : The address operator & is used to get the address of
the other variable in an indirect manner.
(c) Sizeof Operator : The sizeof operator is used to give the direction to the
C compiler to reserve memory size or block to the particular data type
which is
defined in the strucutre type of data in the linked list.
(d)Incrementer and decrementer: Two special operators are used in C namely
incrementer and decrementer. These operators are used to control the loop
in an
effective manner.

incrementer: The symbol ++ or notation is used for incrementing by 1.


i++ is equal to i=i+1
Sambaraju, ASTRA
‘C’ Language Guide
++i is equal to i=i+1
decrementer: The symbol -- or notation is used for decrementing by 1.
i-- is equal to i=i-1
--i is equal to i=i-1

Ternary Operator: C includes a very special operator called the ternary


or conditional operator. It is called ternary because it uses 3 expressions
The ternary operator acts like a shorthand version of the if-else constructio
syntax: exp1?exp2:exp3;
If exp1 is true then exp2 is evaluated; otherwise exp3 is evaluated. The
Conditional operator is used in place of single if-else to make an assignment
eg:
if(a>b)
max=a;
else
max=b;
This can be written using ternary operator as
max=(a>b)?a:b;

Comma Operator:C uses the comma operator in two ways. The first is to
seperate variables in the declaration.
eg: int a,b,c;
Another use is as an operator in an expression for loop.
eg:for(i=0,j=10; i<=10, J>=1; i++,j--)

Sambaraju, ASTRA
‘C’ Language Guide
Control Statements
Control Statements are mainly divided into three types

Conditional Expressions: The conditional expressions are mainly used for


decision making. The following statements are used to perform the task of the
conditional operations.
 if statement
 if-else statement
 nested if statement
 else-if Ladder
 switch statement

Loop Statements: The loop statements are essential to construct systematic


bllock styled programming. In C, three various ways one may define the
control structures using different types of loop operations. The following are
the loop structures in C.
 while loop
 do-while loop
 for loop

Breaking control statements: For effective handling of the loop statements, C


allows the use of the following 3 types of control break statements.
 Break Statement
 Continue Statement
 goto statement

if statement :The if statement is used to write conditional expressions. If the


given condition is true then it will execute the statements. Otherwise it will
execute optional statements.
syntax:
if<conditon>
{
-----
-----
}
The expression is evaluated and if it is "true",
the statement following the if is executed. In case the
given expression is "false", the statement is skipped and
execution continues with the next statement.
ex:
a=20; b=10;
if(a>b)
printf("Larget value=%d");
If the given condition is satisfied, then it prints the message
"Lagest value=20" and if not, it will simply skip the statement.

Sambaraju, ASTRA
‘C’ Language Guide
if –else statement The if-else statement is used to write conditional
expressions. If the given condition is true then it will execute the statements.
Otherwise it will
execute else block statements.

syntax:
if<conditon>
{
-----
-----
}
else
{
-----
-----
}
The expression is evaluated and if it is "true", the statement
following the if is executed. In case the given expression is "false", the
statement . under else block will be executed.
ex:
if(a>b)
printf("Largest value=%d",a);
else
printf("Largest value=%d",b)

nested if statement The if statement within if statement is nested if.

syntax:
if(condition-1)
{
if(condition-2)
{
statement-1
}
}
else
statement-2

if the condition-1 is satisfied, then only it checks the condition-2.


Otherwise
else block will be executed.
ex:
#include <stdio.h>
main()
{
int a;
printf("enter value for a");
scanf("%d", &a);
if(a>0)
Sambaraju, ASTRA
‘C’ Language Guide
{
if(a==5)
{
printf("Your input is corretct");
}
}
else
printf("Your input is not correct");
}

Else- if ladder
Syntax:
if (condition-1)
statement-1
else if(condition-2)
statement-1
else
statement-2

ex:big no among three numbers


#include <stdio.h>
main()
{
int a,b,c;
printf("enter values for a,b,c");
scanf("%d%d%d",&a,&b,&c);
if (a>b && a>c)
printf("%d is big",a);
else if(b>c)
printf("%d is big",b);
else
printf ("%d is big",c);

Switch statements The switch statement is a multiway decision maker that tests
whether an expression matches one of the number of constant values, and
braces accordingly.

syntax: switch(expression)
{
case constant1: statement; break;
case constant2: statement; break;
.
case constantn: statement; break;
default: statement;
}

Sambaraju, ASTRA
‘C’ Language Guide
 The expression whose value is being compared, may be any valid
expression including the value of the variable, an arithimatic
expression, logical comparision, a bitwise expression or the return
value from a function call, but not the floating point expression.
 The constants in each of the case statements must obiviously be of the
same
type
 The expression value is checked against each of the specified cases and
when a match occurs, the statement following that is executed. Again
to maintain generality, the statement can be either a simple or a
compound statment.
 The value that follows the keyword case may only be constants they
can't be expressions. They may be integers or characters, but not
floating point
numbers or character strings.
 The last case of this statement which is called the default case is optional
and should be used according to the program's specific requirement
 Execution or the switch constant in C follows this logic. No statements
are
executed until a case has been matched or the default case has been
encountered

while Loop: The while loop is used when we are not certain that the loop will
be executed.After checking whether the initial condition is true or false and
finding it to be true, only then the while loop will enter into the loop
operations.
syntax:
For single condition
while<condition> For a block of statements
statement; while<condition>
For a block of statements {
while<condition> statement-1;
{ statement-2;
statement-1; ......
statement-2; }
......
}

 The condition cab be any valid expression including the value of a


variable
a unary or binary expression, or the value returned by a function. The
statement can be a single or compound statement. The condition is
actually
test condition.

 The while loop does not explicitly contain the initilization /


incrementation parts of the loop. These two statements are normally
provided by the programmers.

Sambaraju, ASTRA
‘C’ Language Guide
initial condition
while(test condition)
{
statement-1
statement-2
change of initial condition
}

Do-while Loop: The do-while loop is used whenever one is certain about a test
condition, then the do-while loop can be used. As it enters into the loop atleast
once and then checks whether the given condition is true or false. As long as
the test condition is true, the loop operations or statements
will be repeated again and
again.
Syntax:
do
{
statement-1
statement-2
----------
}while(condition);

for Loop: The for loop is most commonly used in C. This loop
consists of three
expressions. The first expression is used to initialize the index value, the
second to check whether or not the loop is to be continued again and the third
to change the index value for further iteration.
Sometimes the operations carried out by the while loop can also be done by
using the for loop. Depending on the situation programmer can decide the loop.

Syntax:
for(exp1;exp2;exp3)
statement;

Where expression-1 is the initialization of the expression


or condition;
expression-2 is the condition checked as long as the
given expression
is true.
expression-3 is the incrementer or decrementer to
change the index value
of the for loop variable.

Break: The break statement is used to terminate the


control from the loop statements of the case-structure. The
break statement is normally used in the switch-case loop
and in each case condition, the break statement must be
used. If not, the control will be transfered to the subsequent case condition.
syntax:
Sambaraju, ASTRA
‘C’ Language Guide
break;
break statement in while loop
The break statement used in while loop. The following example shows how
break
statement will be used in the while loop.
main()
{
int value,i;
i=0;
while(i<=10)
{
printf("enter number:");
scanf("%d",&value);
if(value<=0)
{
printf("Zero or -ve value found");
break;
}
i++;
}
}

The above program segment will process only the +ve integers. Whenever a
zero
or non -ve value is encountered, the computer will display the message "zero
or negative value found" as an error and exit from the while loop.

Continue: The continue statement is used to repeat the same operations once
again even if it checks the error.
syntax:
continue;
The continue statement is used for the inverse operation of the break statement.
example:
main()
{
int value,i;
i=0;
while(i<=10)
{
printf("enter number:");
scanf("%d",&value);
if(value<=0)
{
printf("Zero or -ve value found");
continue;
}
i++;
}
}
Sambaraju, ASTRA
‘C’ Language Guide

This program segment process only +ve integers. Whenever a zero or -ve value
is encountered, the computer will display the message "zero or -ve value
found"
as an error and it continues the same loop as long as the given condition is
satisfied.

goto: The goto statement is used to alter the program execution sequence by
transfering the control to some other part of the program.
syntax:
goto label;

Here, label is the valid C identifier. There are 2 ways of goto statements
* Conditional goto * Unconditional goto
UnConditional goto:The unconditional goto statement is just used to transfer
the control from one part of the program to other part without checking any
condition.
ex:
main()
{
start: printf("Welcome ");
goto start;
}
Conditional goto: The conditional goto is used to transfer the control of the
execution from one part of the program to the other in certain conditional cases.
Ex:
main()
{
int value,i;
i=0;
while(i<=10)
{
printf("enter number:");
scanf("%d",&value);
if(value<=0)
{
printf("Zero or -ve value found");
goto error;
}
i++;
}
error: printf("Input data error");
}

Sambaraju, ASTRA
‘C’ Language Guide
Arrays
An array is a collection of identical data objects which are stored in
consecutive memory locations under a common heading or a variable name.
(or)
An array is a group or a table of values referred to by the same variable
name.
(or)
Arrays are set of values of the same type, which have a single name followed
by an index.

The individual values in an array are called elements. Array elements are
also variables. Square brackets appear arround the index right after the name,
with the first element referred to by the number. Whenever an array name with
an index appears in an expression, the C compiler assumes that element to be
of an array type.

Array Declaration :Declaring the name and type of an array and setting the
number of elements in the array is known as dimensioning the array. Before
linear or multidimensional array used in the program we must provide the
compiler the following information.
* Type of the array (i.e. integer, floating point, char type etc.)
* Name of the array
* Number of subscripts in the array (i.e., whether the array is 1D or 2D)
* Total number of memory locations to be allocated.

syntax for 1D array


storage_class data_type array_name[index];

where, storage_class refers to the scope of the array variable such as


external, static, or an automatic.
data_type used to declare the nature of the data elements stored in the
array like character type, integer or floating type.
array_name is the name of the array.
index is used to declare the size of the memory locations required
for further processing by the program. index should be integer value
and it starts from 0 and ends with n-1.

Array in the memory:


0 1 2 3 ....................n-1

ex:
int marks[300];
char name[100];
float avg[20];

Array Initilization:
storage_class data_type array_name[index]={ele-1,ele-2......ele-n};

Sambaraju, ASTRA
‘C’ Language Guide
where, storage_class refers to the scope of the array variable such as
external, static, or an automatic.
data_type used to declare the nature of the data elements stored in the
array like character type, integer or floating
array_name is the name of the array.
index is used to declare the size of the memory locations required
for further processing by the program. Index should be integer value and
it starts from 0 to n-1.
the elements are placed one after another within the braces and finally
ends with the semicolon
ex:
int value[5]={10,20,30,40,50};
char sex[2]={'M','F'};
The above array is represented in the memory as follows
value[0]=10;
value[0]=20;
value[0]=30;
value[0]=40;
value[0]=50;
sex[0]='M';
sex[1]='F';

Array Processing : Address of integer array elements in the array:


eg: int a[5]; let us say it starts with 658000 initially
Array in the memory with the addresses is
0 1 2 3 4

&a[0]=658000; &a[1]=658002; &a[2]=658004; &a[3]=658006;


&a[4]=658008;

Note:total memory occupied for an array is depends on the datatype of the


array
for example:
* If we declare integer array of size 10 elements, the total memory occupied
by the array is 10*2=20 bytes.(because for 1 integer 2 bytes memory is
required)
* If we declare character array of size 10, it requires 10*1=10 bytes memory
* If we declare float array of size 10, it requires 10*4=40 bytes memory.

defining an array:
main()
{
int a[5]={8,9,0,1,3};
int i;
/*displaying array elements on the screen*/
for(i=0;i<=4;i++) /* i is the looping variable
{ and index from 0 to 4*/
printf("%3d",a[i]);
}
Sambaraju, ASTRA
‘C’ Language Guide
}

Array in the memory


0 1 2 3 4 5
8 9 0 1 3 and each called with index of the element like
a[0]=8; a[1]=9; a[2]=0; a[3]=1; a[4]=3;

Two Dimensional Arrays : Two dimensional array will be in the form of rows
and columns format.
Syntax:
storage_class datatype arrayname[rows][cols];

where storage_class refers to scope of the array variable such as external,


static, automatic or register.
datatype refers to the nature of the data elements in the array such as
character type, integer type, or float etc.,
array name refers to multidimensional array.
rows refers to the number of rows of the array.
cols refers to the number of columns of the array.

Two Dimensional Array in the memory


0 1 2
0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2
Address of each element in 2-D integer Array:
eg: int a[3][3];let us say it starts with 658000 initially
Array in the memory with the addresses is
&a[0][0]=658000 &a[0][1]=658002 &a[0][2]=658004
&a[1][0]=658006 &a[1][1]=658008 &a[1][2]=658010
&a[2][0]=65812 &a[2][1]=658014 &a[2][2]=658016
Note: Elements in the 2-D array depends on the size of the array. In the a[3][3]
integer array, there will be 3*3=9 elements

Char Array : Character array mainly used to declare alpha numeric characters.
The general syntax for defining character array is
storage_class char_data_type array_name[exp];

The storage class is optional and it may be either one of the scope of the
variable such as automatic, external, static or register.
array_name is the any valid C identifier.
exp is a +ve integer constant.
Ex
char name[50];
char address[100];
Character array in the memory
S I V A \0
Each element of the array is placed in a definite memory space and each
element
can be accesssed seperately. The array element should end with the null
character as a reference for the termination of the character array.
Sambaraju, ASTRA
‘C’ Language Guide
Initializing the character array:
char name[5]="Siva";
The elements would be assigned to each of the character array position in the
following way
name[0]='S'; name[1]='i'; name[2]='v'; name[3]='a';
The character array always terminate with the null character, that is a back
-slash followed by a letter zero. And the computer will treat them as a single
character. The null character will be added automatically by the C compiler
provided there is enough space to accommodate character.
example:
char line[]="this is a test program";
Here, the square brackets are empty. The array size would have been specified
as part of the array definition.

To find out ith element in the array When a[0] is given


&a[i]= &a[0]+((i-1)*scalefactor)
scale factor is the size of the datatype
ex:
Let us take the following integer Array
0 1 2 3 4 5
&650800 &650802 &650804 &650806 &650808 &650810
To find out the address of 4th element in the array
&a[6]=&a[0]+((4-1)*scalefactor)
&a[6]=650800+(3*2) /*for integer 2 bytes memory, so here
=650800+6 scalefactor will be 2*/
=650806

Sambaraju, ASTRA
‘C’ Language Guide
Strings
Sequence of characters enclosed in double quotes is called a string. A
character array is also called as a string. And every string ends with a null
character '\0'.
Initializing a string :

char name[]={'s','i','v','a'};
char name[5]={'s','i','v','a','\0'};
char name[6]="siva";

Reading string from the keyboard:


main()
{
char site[10];
printf("Enter string:");
scanf("%s",name);
}

Writing string to the screen:


main()
{
char site[10];
printf("Enter string:");
scanf("%s",name);
printf("Given string:%s",name);
}

getchar() :getchar() is used to read a single character from the keyboard.


Ex: to read a single character using getchar()
main()
{
char s;
printf("\nEnter any character:");
s=getchar();
printf("\nEntered character:%c",s);
}

putchar() :putchar() is used to print the single character on the screen.


Ex: to write a single character on the screen using putchar()
main()
{
char s;
printf("\nEnter any character:");
s=getchar();
printf("\nEntered character:");
putchar(s);
}

getchar() :gets() is used to read a string from the keyboard.


Sambaraju, ASTRA
‘C’ Language Guide
Ex: to read a string using gets()
main()
{
char s[20];
printf("\nEnter any string:");
gets(s);
printf("\nEntered string:%s",s);
}

puts() :puts() is used to print the string on the screen.


Ex: to write a string on the screen using puts()
main()
{
char s[20];
printf("\nEnter any string:");
gets(s);
printf("\nEntered string:");
puts(s);
}

String Handling Functions (String.h):


o Strlen() - To Find the length of the string
o Strrev() - To reverse the string
o Strcpy() - To Copy one string to another
o Strcat() - To Adding the strings
o Strcmp() - To compare the strings
o Strupr() - To change into upper
o Strlwr() - To change into lower
strlen() :strlen() function is used to find out the length of the given string. It
takes the string as a parameter and returns the integer value.
syntax:strlen(str);
ex:strlen("siva");
example code on strlen()
main()
{
char s[100];
static int i,len;
clrscr();
printf("/nEnter the string:");
gets(s);
len=strlen(s);
printf("/nlength=%d",len);
getch();
}
o/p:
Enter the string:Siva
length=4

Sambaraju, ASTRA
‘C’ Language Guide
strrev() :strrev() function is used to reverse the given string. It takes the string
as
the parameter.
syntax:strrev(str);
ex:
strrev("siva");
example code on strrev()
main()
{
char s[100];
clrscr();
printf("/nEnter the string:");
gets(s);
printf("/nreverse string is : %s",strrev(s));
getch();
}
o/p:
Enter the string:siva
reverse string is : avis

strcpy() :strcpy() function is used to copy the one string into another. It takes
two string parameters. First string is destination string and another one is
source string.
syntax:strcpy(str1,str2); /*copies str2 into str1*/
ex:
strcpy(str,"siva"); /* copies "siva" to str*/
example code on strcpy()
main()
{
char s[100],str[100];
clrscr();
printf("/nEnter the string:");
gets(s);
strcpy(str,s);
printf("/nOriginal string is:",puts(s));
printf("/nCopied string is:",puts(str));
getch();
}
o/p:
Enter the string:this is c programming
original string: this is c programming
copied string: this is c programming

strcat():strcat() function is used to combine two given strings. It takes two


string parameters.

syntax:strcat(str1,str2);
ex:strcat("siva","ram");
example code on strcat()
Sambaraju, ASTRA
‘C’ Language Guide
main()
{
char s[100],c[100];
clrscr();
printf("/nEnter first string:");
gets(s);
printf("/nEnter second string:");
gets(c);
printf("/nAfter concatenation: %s",strcat(s,c));
getch();
}
o/p:
Enter first string:siva
Enter second string:ram
After concatenation: sivaram

strcmp():strcmp() function is used to compare two given stirngs. It takes two


string parameters. The strcmp() returns 0 if two strings are alphabetically equal.
The strcmp() returns +ve value if first string is alphabetically greater than
the second string. The strcmp() returns the -ve value if first string is
alphabetically lessthan the second string.

syntax:strcmp(str1,str2);
example:
strcmp("abc","abc");
example code on strmp()
main()
{
char s[100],c[100];
clrscr();
printf("/nEnter first string:");
gets(s);
printf("/nEnter second string:");
gets(c);
if(strcmp(s,c)==0)
printf("strings are equal");
else if(strcmp(s,c)>0)
printf("/n first string is biggerthan second");
else
printf("/nsecond string is biggerthan first");
getch();
}

strupr() :strupr() function is used to convert the given string into uppercase. It
takes the string as parameter.
syntax:
strupr(str);
example:
strupr("siva");
Sambaraju, ASTRA
‘C’ Language Guide
example code on strupr()
main()
{
char s[100];
clrscr();
printf("/nEnter string:");
gets(s);
printf("/nstring in uppercase:%s",strupr(s));
getch();
}
o/p:
Enter string:siva
string in uppercase:SIVA

strlwr() :strlwr() function is used to convert the given string into lowrcase. It
takes
the string as parameter.
syntax:
strlwr(str);
example:
strlwr("siva");
example code on strlwr()
main()
{
char s[100];
clrscr();
printf("/nEnter string:");
gets(s);
printf("/nstring in lowercase:%s",strlwr(s));
getch();
}
o/p:
Enter string:SIVA
string in lowercase:siva

Array of strings

Array of strings can be declared as two dimensional array. The following is the
syntax for array of strings.
char_datatype array_name[No.of strings][size of each string];
example:
char name[3][20];
Initializing array of strings
char name[3][20]={"c,"for","beginers"};
Code for reading three strings
main()
{
char s[3][100];
static int i;
Sambaraju, ASTRA
‘C’ Language Guide
clrscr();
for(i=0;i<3;i++)
{
printf("/nEnter %d string:",i+1);
gets(s[i]);
}
for(i=0;i<3;i++)
{
printf("/n%d sting: ",i+1);
puts(s[i]);
}
getch();
}

Sambaraju, ASTRA
‘C’ Language Guide
Structures
Structure is a collection of hetrogeneous datatypes grouped together.
When this is done, the entire collection can be refered to by a structure name.
The individual components are called fields or members. And these fields or
members are accessed or processed seperately.
A structure definition is specified by the keyword struct. This is followed
by user defined name surrounded by braces, which describes the members of
the structure. A member of a strucutre is a single unit.

Structure format :
storage_class struct user_defined_name
{
data_type mem1;
data_type mem2;
data_type mem3;
.
.
.
data_type mem n;
};
The storage_class is optional, whereas the keyword struct and the braces are
essential The user_defined_name is usually used. The datatype and members
are any valid C data objects such as int, float and char.

ex:
struct date`s
{
int day;
int month;
int year;
};
Each member of a structure is specified by a variable name with a period and
the member name. The period is a structure member operator which we can be
refered simply as the period operator.

Structures Initialization

A structure can be initialized in two ways. Consider the following student


particulars.
struct school
{
int rollno,age;
char sex;
float height,weight;
};
First method:static struct school student= {1010,24,'M',167.9,56.7};
The compiler assigns the following values to each of the fields.
rollno = 1010
Sambaraju, ASTRA
‘C’ Language Guide
age = 24
sex = 'M'
height = 167.9
weight = 56.7
Second Method:
student s;
s.rollno=1010;
s.age=24;
s.sex='M';
s.height=167.9;
s.weight=56.7;

Array of Structures:An array is a group of identical data which are stored in


consecutive memory locations in a common heading or a variable. A similar
type of structure is placed in a common heading or a common variable name is
called arrays of structures.
Ex:If one would process the student's particulars for the entire school(more
than one or two students) then array of structures are needed.
ex:
struct school
{
int rollno,age;
char sex;
float height,weight;
};
school student[300];The student[300] is a structure variable. It may
accomodate the structure of a student upto 300. Each record may be accessed
and processed seperately like individual elements of an array.
Initialization of Array of Structures : The strucutre can be initialized in the
following way.
struct school
{
int rollno,age;
char sex;
float height,weight;
};
school student[2]={
{5001,24,'M',67.9,56.7},
{5002,25,'M',67.9,56.7}
};
The C compiler will assign the values to the individual elements of the
particular structure in the following way
For the first record
student[0].rollno=5001;
student[0].age=24;
student[0].sex='M';
student[0].height=67.9;
student[0].weight=56.7;
For the second record
Sambaraju, ASTRA
‘C’ Language Guide
student[1].rollno=5002;
student[1].age=25;
student[1].sex='M';
student[1].height=67.9;
student[1].weight=56.7;

Arrays within Structures :A member of a structure can be an array datatype


also. i.e., we can declare array as member in structure.
ex:
struct school
{
char name[20],sex;
int rollno,age;
float height,weight;
};
The C compiler initialize the members in the following way.
school student[2]= {
{"Siva",'M',5001,24,156.6,56.7},
{"hasini",'F',5002,25,156.6,56.7}
};
The C compiler asigns the values to its members of a structure as
student[0].name[]="Siva";
student[0].sex='M';
student[0].rollno=5001;
student[0].age=24;
student[0].height=156.6;
student[0].weight=56.7;
and so on. In case if some of the members are not initialized explicitly, the
compiler will treat them as zero.

Nested Structures:In C, we can use a structure as a member of another


structure. When a structure is declared as member of another structure, it is
called a nested structure or structure within a structure.
ex:
struct date
{
int day,month,year;
};
struct student
{
char name[20],sex;
int rollno;
struct date dob;
};

To process the individual elements in a nested structure, first we have to


declare the structure variable of the date structure(dob) and then its
individual fields.

Sambaraju, ASTRA
‘C’ Language Guide
Functions
A complex program may be decomposed into a small or easily manageable
parts or modules called functions. Functions are very useful to read, write,
debug and
modify complex programs. They can also be incorporated in the main program.
In
C, the main() itselff is a function that means the main function is invoking
the other functions to perform various tasks.

Advantages of using functions:


 easy to write a correct small functions.
 easy to read, write and debug a function.
 easier to maintain or modify such a function
 small functions tend to be self documenting and highly readable.
 it can be called any number of times in any place with different
parameters.

Defining Functions

Defining the function has the following syntax.


functiontype functionname(datatype argument1, datatype
argument2......)
{
body of function
--------------
--------------
return (statement);
}
Declaring the type of a function: The function refers to the type of value it
would return to the calling portion of the program. Any of the basic
datatypes
such as int, float, char etc. may appear in the function declaration.
ex:
int functionname(....);
float functionname(....);
char functionname(....);
Function Name: Normally a function name is made relevant to the function
operation, as it will be easy to keep a track of it, whenever a transfer of
similar functions is used in the main program.
example:dec
counter();
square();

Formal arguments:
example:
void square(int a,int b)
/*a and b are formal arguments*/
{
Sambaraju, ASTRA
‘C’ Language Guide
----
}
Function body:After declaring the type of a function, function name and
formal
arguments, a statement or block of statemnts are enclosed between open and
close braces is a function body.

Actual and formal arguments


The arguments may be classified under two groups actual and formal
arguments.
Actual Arguments: An actual argument is a variable or an expression
contained
in a function call that replaces the formal parameter which is a part of the
function declaration.
Sometimes, a function may be called by a portion of a program with some
parameters and these parameters are konwn as the actual arguments.
Ex:
main()
{
int x,y;
void sum(int x,int y);
------
------
sum(x,y); /*x and y are actual arguments*/
}
Formal Arguments: Formal arguments are the parameters present in a
function
definition which may also be called as dummy arguments or the parametric
variables. When the function is invoked, the formal parameters are replaced
by the actual parameters.
ex:
main()
{
int x,y;
void sum(int x,int y);
------
------
sum(x,y); /*x and y are actual arguments*/
}
sum(int a,int b) /* a and b are formal or dummy parameters*/
{
-----
}

Local and Global variables

The variables in general may be classified as local or global variables.


Local Variables: The variables which are define inside a function block or a
compound statement is known as local variables.
Sambaraju, ASTRA
‘C’ Language Guide
Ex:
sum(int a,int b)
{
int x,y;/*local variables*/
----
----
}

Global Variables: Global variables are variables defined outside the main
function block. These variables are refered by the same data type and by the
same name through out the program in both the calling portion of a program
and
in the function block.
ex:
int a,b=5; /*global variables*/
main()
{
int sum();
a=10;
------
------
sum();
}
sum()
{
int s;
s=a+b;
return s;
}

Return Statement:The keyword return is used to terminate function and


return a value to its caller. The return statement may also be used to exit a
function without returning a value. The return statement may or maynot
include an expression.
syntax:
return;
return (exp);
ex:
return;
return(345);
return(a+b);
return(++i);
The return statement terminates the execution of the function and pass
on the Control back to the calling environment.

Function Types :
The functions are mainly divided into two types.
* Library Functions.
* User defined Functions.
Sambaraju, ASTRA
‘C’ Language Guide
Library Functions: The following are the standard library functions in C.
<assert.h>
<ctype.h>
<errno.h>
<float.h>
<limits.h>
<locale.h>
<math.h>
<setjmp.h>
<signal.h>
<stdarg.h>
<stddef.h>
<stdio.h>
<stdlib.h>
<string.h>
<time.h>
User defined Functions:The user defined functions are classified in 3 ways
based on the formal arguments passed and the usage of the return statement.
 Functions with no arguments and no return types
 Functions with arguments and no returntypes
 Functions with arguments and returntypes

Passing Arrays to Functions :The entire array can be passed on to a function


in C. An array name can be used as an argument for the function
declaration. No subscripts are required to invoke a function using arrays.
Ex:
main()
{
int sumarray(int a[],int n);
int a[10],sum;
--------------
--------------
sum(a,n); /*passing array to Function*/
}

Passing structures to Functions:A structure can be passed to a function as a


single variable. The scope of a structure declaration should be an external
storage class whenever a function in the main program is using a structure
data types. The field or member data should be same throughout the
program either in the main or in a function.
Ex:
struct sample
{
int x;
float y;
};
sample first;
main()
{
Sambaraju, ASTRA
‘C’ Language Guide
display(struct sample one); /*Function declaration*/
--------------
--------------
display(one); /*Function calling*/
}

Recursive Functions :A function which calls itself directly or indirectly


again and again is known as the recursive function. Recursive functions are
very useful while constructing the data structures like linked lists, double
linked lists and trees.
There is a dintinct difference between normal and recursive functions. A
normal function will be invoked by the main function whenever the
function name is used. whereas the recursive function will be invoked by
itself directly or indirectly as long as the given condition is satisfied.
ex:
recursive function for factorial is n*fact(n-1)
It works in the following way. Let us assume n=5
5*fact(5-1)->5*fact(4)
4*fact(4-1)->4*fact(3)
3*fact(3-1)->3*fact(2)
2*fact(2-1)->2*fact(1)
1*fact(1-1)->1*fact(0)
syntax:
main()
{
function(); /*calling function*/
--------
--------
}
function()
{
--------
--------
function();/*function call recursively*/
}

Sambaraju, ASTRA
‘C’ Language Guide
Pointers
A pointer is a variable which contains the address of memory location
of
another variable. A pointer provides an indirect way of accessing the value
of a data item.

Uses of pointers:
* pointers are used to communicate information about memory.
* pointers are used to saving memory.
* With the pointers data manipulation is done with the address, so the
execution time is faster.
* pointers are used to return more than one value from a function.
* To pass arrays and strings more conveniently from one function to
another.
* pointers are used to allocate memory and access it [dynamic memory
allocation].
* pointers are used to create complex datastructures like linked lists.

Pointer Operators : A pointer contains a memory address. Most commonly,


this address is the location of another variable where it has been stored in
memory. If one variable contains the address of another variable, then the
first variable is said to point to the second.
In C, pointers are distinct such as integer pointers, floating point
number pointer, character pointer etc., A pointer variable consists of two
parts.
(a) the pointer operator (b) the address operator

Pointer Operator:
A pointer operator can be represented by a combination of *(asterisk) with a
variable.

syntax: datatype *pointer_variable;

where, datatype is a type of pointor variable such as integer, char and float..
pointer_variable is the any valid C identifier.
ex: int *iptr;
Here, iptr is a pointer variable which holds the address of an integer
datatype.

Address Operator:An address operator can be represented by a combination


of &(ampersend) with a pointor variable. The & is a unary operator that
returns the memory address of its operand. A unary operator requires only
one operand.
ex:
m=&iptr;
Here, the m recieves the address of iptr.

Sambaraju, ASTRA
‘C’ Language Guide
Pointer Operators:We can perform the following arthimatic operators on
pointers
+ addition eg: *c=*a+*b;
- subtraction eg: *c=*a-*b;
* multiplication eg: *c=*a**b;
/ division eg: *c=*a/*b;
% modulus eg: *c=*a%*b;
++ increment and
-- decremant

Note:++operator causes the pointor to be incremented, but not by 1.


--operator causes the pointor to be decremented, but not by 1.

ex:
int value, *ptr;
value=120;
ptr=&value;
ptr++;
printf("%u\n",ptr);
The pointor ptr is originally assigned the value 2000. The incrementation,
ptr++ increments the number of bytes according to the datatype.

And also we can compare two pointor varibales by using following


comparision
operators
> greater than
< less than
>= greater than or equals to
<= less than or equal to
== equals to
!= not equal to.

Pointer And 1D Arrays:

ex: int value[20];


int *ptr;
Here, the pointer variable holds the address of first element in the value
array i.e address of value[0].means ptr=&value[0] (or) ptr=&value[]
we can use the pointers in the following way
ptr++==value[1];
*ptr==&value[0];
*ptr==value[];
*(ptr+6)==value[6];
ptr++==&vale[1];

/*example for reading and writing one dimensional array*/


main()
{
static int a[10],i,n=5;
Sambaraju, ASTRA
‘C’ Language Guide
int *temp;
printf("/nenter elements");
for(i=0;i<=n-1;i++)
scanf("%d",&a[i]);
temp=&a[0]; /*Address of 0th element*/
for(i=0;i<=n-1;i++)
printf("/n%d",*(temp+i)); /*Address of ith element*/
}

Note:The above program will be executed in the following way also


main()
{
static int a[4]={11,12,13,14};
int i,n,temp;
clrscr();
for(i=0;i<=3;i++)
{
temp=*((a)+(i));
printf("/n%d",temp);
}
}

Pointer And 2D Arrays A pointer to an array contains the address of the first
element. In one dimensional array, the first element is &a[0] but in the two
dimensional array the first element is &a[0][0]
ex:
int a[][];
int *ptr;
ptr=a; /*the address of 0throw and the 0th
row of the 2d array a is assigned to the ptr.
/*example for reading and writing two dimensional array*/
main()
{
static int a[10][10];
int i,j,n=2,m=2;
clrscr();
printf("/nenter elements");
for(i=0;i<=n-1;i++)
for(j=0;j<=m-1;j++)
scanf("%d",&a[i][j]);
for(i=0;i<=n-1;i++)
for(j=0;j<=m-1;j++)
printf("/n%d",*(*(a+i)+j));
getch();
}

Pointer And Functions: Pointers are very much used in a function declaration.
Sometimes only with a pointer a complex function can be easily represented

Sambaraju, ASTRA
‘C’ Language Guide
and accessed. The use of pointers in a function definition may be classified
into two groups.
 Call by value
 Call by reference

Call by value :Whenever a function is called, the control will be transfered


from the main to the called function and value of the actual argument is copied
to the function.Within the function, the actual value copied from the calling
portion of the program may be altered or changed. When the control is
transfered back from the called function to the calling protion of the program,
the altered values are
not transfered back. This type of passing formal arguments to a function is
technically known as call by value.

ex:/*Swapping of two variables*/


main()
{
int a=10,b=20;
printf("/nBefore swaping a=%d b=%d",a,b);
swap(a,b);
printf("/nAfter swaping a=%d b=%d",a,b);
}
swap(int a,int b)
{
a=a+b;
b=a-b;
a=a-b;
}

o/p:

Before swaping a=10 b=20


After swaping a=10 b=20

Explanation:In the above example, the values won't be changed. Why because
when
we declare a and b in the calling function, some memory will be allocated to a
and b. And for a and b in the called function some other memory will be
allocated and those are temporary varibles. according to the definition of
swap() function the values will be changed in the temporary varibales but not
in the actual variables.

Call by Reference :When a function is called by a portion of a program, the


address of the actual arguments are copied onto the formal arguments, though
they may be refered by different variable names. The content of the variables
that are altered within the function block are returned to the calling portion of a
program in the altered itself, as the formal and the actual arguments are
referencing the same
memory location or address. This is technically known as call by reference
Sambaraju, ASTRA
‘C’ Language Guide
or call by address or call by location.
/*swapping of two varibales*/
main()
{
int *a=10,*b=20;
printf("/nBefore swaping a=%d b=%d",a,b);
swap(&a,&b);
printf("/nAfter swaping a=%d b=%d",a,b);
}
swap(int *a,int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}

o/p:
Before swaping a=10 b=20
After swaping a=20 b=10

Explanation:Here we are passing the reference of the variblaes(address) but not


the direct value so, the values will be interchanged in the original memory
location. so, the values will be interchanged.

Pointors And Structures :A pointor can be used to hold the address of the
structure variable too. The pointor variable is very much used to construct
complex data structures such as linked lists, double linked lists and binary trees
etc.,
ex:
struct sample
{
int x;
char y;
};
struct sample *ptr;
Where ptr is a pointor variable holding the address of the structure sample and
is having three members such as int x,char y;
The pointor structure variable can be accessed and processed in one of the
following ways:
1. (*structure_name).field_name=variable;
2. structure_name -> field_name=variable;
example:
struct sample
{
int x;
char y;
};
struct sample *ptr;
(*ptr).x=10; (or) ptr->x=10;
Sambaraju, ASTRA
‘C’ Language Guide
(*ptr).y='y'; ptr->y='y';

Pointers To Pointers :The pointor to a pointor is a form of multiple of


indirections or a class of pointors. In the case of a pointor to a pointor, the firs
pointor contains the address of the second pointor, which points to the variable
that contain the
values desired.
ex:
int **ptr2;
where ptr2 is a pointer which holds the address of the another pointer

Sambaraju, ASTRA
‘C’ Language Guide
Storage classes

C language supports 4 types of storage classes to store the variables. A


variable storage class tells us:
 where the variable would be stored
 what will be the initial value of the variable (i.e. default value)
 what is the scope of the variable i.e. in which functions the value of the
Variable would be available
 what is the life of the variable; i.e. how long would be the variable
Exist.

The 4 storage classes are


1. Auto
2. Extern
3. Static
4. Register

Auto :automatic variables are nothing but local variables.


syntax: auto datatype var;
* automatic variables are stored in memory
* Default value is garbage value
* scope is local to the block in which the variable is defined.
* lifetime is till the control remains within the block in which the variable
is defined
eg:
main()
{
auto int x=20;
printf("x=%d",x);
{
auto int y=2;
auto int x=35;
printf("/nx=%d /t y=%d",x,y);
}
printf("/nx=%d",x);
}
o/p:
x=20
x=35 y=2
x=20

Extern
external variables are global variables.
syntax:extern datatype var;

Sambaraju, ASTRA
‘C’ Language Guide
* extern varibales are stored in memory
* default value is zero
* scope is throughout the function where it is defined
* the extent of external variable is alive upto the termination of program.
ex:
extern int p=4;
main()
{
printf("%d",p);
p=29;
printf("%d",p);
}
o/p:
p=4
p=29

Static
static variables are permanent variables within their own
functions.
syntax: static datatype var;
* static variables are stored in memory
* default value is zero
* scope is local to the block in which the variable
is defined.
* lifetime is throughout the block.

example:
void increment();
void main()
{
increment();
increment();
increment();
}
void increment()
{
static int i=1;
printf("/n%d",i);
i=i+1;
}

o/p:
1
2
3

Register:when operands are brought into processor, they stored up high speed
storage.Those are called registers. Each register can store one word of data i.e
16
Sambaraju, ASTRA
‘C’ Language Guide
bits.
* stored in registers
* default value is garbage value
* scope is local to the block in which the variable defined.
* lifetime is till the control remains within the block in which the variable
is defined.

Files
File: A file is collection of records.
Record: collection of fields.
Field: Individual thing or entry.

File Pointer: A file pointer is a pointer to structure which contains


information about the file including its name, current position of the file.
declaration: FILE *fp;

Basic Operations on file:


-> fopen(): This is used to open a file.
syntax: fopen("filename",mode);
There are several modes available
r: opens a text file for reading.
w: opens a text file for writing.
a: append to a text file.
rb: open a binary file for reading.
wb: create a binary file for writing.
ab: append to a binary file.
rw: opena text file for read/write.
wr: create a text file for read/write.
r+b: open a binary file for read/write.
w+b: create a binary file for read/write.
a+b: append a binary file for read/write.
ex: FILE *fp;
fp=fopen("xyz","w");
-> fclose(): To close a file.
syntax: fclose(pointor);
eg: fclose(fp);

-> fputc(): Writes a character to a file.


eg: int fputc(int ch,FILE *fp);

Files
Sambaraju, ASTRA
‘C’ Language Guide

-> fgettc(): Reads a character from the file.


eg: int fgetc(FILE *FP);
do
{
ch=fgetc(fp);
}while(ch!=EOF);

-> fgets(): It reads the entire string from the specified


stream.
eg: char *fgets(char *str,int length, FILE *fp);

-> fputs(): It writes the entire string to the specified file.


eg: int fputs(const char *str,FILE *fp);

-> feof(): end of file.


eg: while(feof(fp))
ch=fgetc(fp);

-> fputc(): Writes a character to a file.


eg: int fputc(int ch,FILE *fp);

-> fprintf(): To write the data into file.


eg: fprintf(fp,"content");

-> fscanf(): It reads the data from the file.


eg: fscanf(fp,"content");

Example On Files

main()
{
int no,m1,m2,m3,ch,tot;
FILE *fp;
clrscr();
do
{
printf("/n1.Read Data");
printf("/n2.Get Data");
printf("/n3.Exit");
printf("/nEnter choice:");
scanf("%d",&ch);
if(ch==1)
{
printf("/nEnter student details:");
scanf("%d%d%d%d",&no,&m1,&m2,&m3);
fp=fopen("pqr.dat","a");
fprintf(fp,"%d%d%d%d/n",no,m1,m2,m3);
fclose(fp);
Sambaraju, ASTRA
‘C’ Language Guide
}
if(ch==2)
{
fp=fopen("pqr.dat","r");
while(!feof(fp))
{
fscanf(fp,"%d%d%d%d/n",&no,&m1,&m2,&m3);
tot=m1+m2+m3;
printf("no=%d m1=%d m2=%d m3=%d
tot=%d/n",no,m1,m2,m3,tot);
}
fclose(fp);
}
if(ch==3)
exit(0);
}while(ch!=3);
getch();
}

Sambaraju, ASTRA
‘C’ Language Guide
List Of Practical Programs

Write a program to print “Hello”

Write a program to print / Hai Friends /

Write a program to print the address

Write a program to read an integer value

Write a program to print a real value

Write a program to print the characters

Write a program to read and print the integer values

Write a program to read and print the real values

Write a program to perform addition of 2 integer values

Write a program to perform Subtraction of 2 integer values

Write a program to perform Multiplication of 2 integer values

Write a program to perform Division of 2 integer values

Write a program to find area, perimeter of square

Write a program to find area, perimeter of Rectangle

Write a program to find area, perimeter of Circle

Write a program to calculate Simple Interest

Write a program swapping of two numbers(with & without using 3rd
variable)

Write a program to calculate Compound Interest

Write a program to convert Celsius into Fahrenheit

Write a program to convert Fahrenheit into Celsius

Write a program to find square of a given number

Write a program to find cube of a given number

Write a program to find square root of a given number

Write a program to find xy

Write a program to find logarithmic value

Write a program to find trigonometric values

Write a program ASCII character for a given number

Write a program to illustrate Arithmetic operators

Sambaraju, ASTRA
‘C’ Language Guide

Write a program to illustrate Relational operators

Write a program to illustrate assignment operators

Write a program to illustrate increment/Decrement operators

Write a program to illustrate Conditional operators

Write a program to illustrate Bitwise operators

Write a program to illustrate Size of operator

Write a program to check the given number is Even or Odd

Write a program to check whether the given year is leap or not

Write a program to check the person is eligible for vote or not

Write a program compare 2 numbers

Write a program to check valid triangle or not

Write a program to find largest of three numbers

Write a program to find the nature & roots of a Quadratic Equation

Write a program to convert lowercase charcter into uppercase and vice
versa

Write a program to calculate total,avg,result,class of 3 subjects of a student

Write a program to calculate Electricty Bill

Write a program to Calculate Employee Net Salary

Write a Menu Driven program on Arithmetic operators

Write a program to print a weekday using Switch

Write a program to print a month using Switch

Write a program to display color using Switch

Write a program to check the given charcter is vowel or consonant

Write a program to print 1 to 100 numbers (while,for,do-while)

Write a program to print 100 to 1 numbers (while,for,do-while)

Write a program print even numbers between 1 to 100

Write a program to print odd numbers between 1 to 100

Write a program to print A to Z

Write a program to print a to z

Write a program to print all alphabets and their equivalent ASCII values

Write a program to calculate of sum of n natural numbers
Sambaraju, ASTRA
‘C’ Language Guide

Write a program to calculate of average of n natural numbers

Write a program to calculate 1+x/1+x2/2+x3/3+………

Write a program to calculate Even sum and Odd sum between of n natural
numbers

Write a program to print square and cube of n numbers in following format

1 1 1
2 4 8
3 9 27
. . .
. . .

Write a program to print the following format

*
* *
* * *
* * * *
* * * * *

Write a program to calculate Sum of Digits of a given number

Write a program to Reverse the given number

Write a program to print multiplication table of given number

Write a program to find LCM of given number

Write a program to find GCD of given number

Write a program to find the factorial of a given number

Write a program to check the given number is prime or nor

Write a program to prime numbers between m to n range

Write a program to check the given number is palindrome or not

Write a program to calculate sum of factors of given number

Write a program to check given number is perfect or not

Write a program to check the given number is Armstrong or not

Write a program to print Armstrong numbers between 1 to 1000

Write a program to print Fibonacci Series(f(n)=f(n-1)+f(n-2))

Write a programs to print the following format

Sambaraju, ASTRA
‘C’ Language Guide

Write a program to print Pascal triangle

Write a program to read and print 1-D array

Write a program to read and print 2-D array

Write a program to calculate sum and avg of n array elements

Write a program to calculate even and odd sum of n array elements

Write a program to print max number in array

Write a program sorting of array

Write a program to search an element in array

Write a program addition of two matrices

Write a program subtraction of two matrices

Write a program Multiplication of two matrices

Write a program to find trace of given matrix

Write a program to find transpose of a given matrix

Write a program to print the mxn identity matrix

Write a program to calculate row sum and column sum of given matrix

Write a program to illustrate on string and character array

Write a program to find the length of string(with and without using string
functions)

Write a program reverse of string(with and without using string functions)

Write a program to check the given string is palindrome or not

Write a program to convert lowercase into uppercase

Write a program to convert uppercase into lowercase

Write a program to copy one string to another

Write a program to cancating the strings

Write a program compare the two strings

Write a program to find no. of words in a string

Write a program to find no. of vowels in a string

Write a program sort the strings

Write a program illustrate the storage classes

Write a program illustrate Enumerated datatype

Write a program to create student Records using Structures
Sambaraju, ASTRA
‘C’ Language Guide

Write a program to create Employee Records using Structures

Write a program to create Books Records using Structures

Write a program to display system time and date using structers

Write a program illustrate unions

Write a program to illustrate macros(#define)

Write a program to find power using functions

Write a program to find square using functions

Write a program to find sum using functions

Write a program to find factorial using recursion

Write a program to find fibnocci using recursion

Write a program illustrate pointers

Write a program illustrate pointers with arrays

Write a program to calculate array sum using pointers

Write a program illustrate pointers with structures

Write a program illustrate pointers on pointers

Write a program illustrate call by value

Write a program illustrate call by reference

Write a program illustrate file operations

Write a program illustrate command line arguments

Write a program to store the student records in a file

Write a program to store the Employee records in a file

Write a program to print output as source program

Write a program illustrate on graphics functions

Sambaraju, ASTRA