Programming With C-language Practical Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

PRACTICAL WORK BOOK

For Academic Session 2013

Programming with C-Language (EE-262)


For
SE (EE)

Name:
Roll Number:
Class:
Batch:
Department :

Department of Electrical Engineering


N.E.D. University of Engineering & Technology, Karachi
Programming with C-Language Contents
NED University of Engineering and Technology Department of Electrical Engineering

CONTENTS

Lab. Title of Experiments Page


Dated Remarks
No. No

1 Introduction to Turbo C++ IDE 01-03

C Building Blocks
2 04-08
I/O and Data Types

C Building Blocks
3 09-13
Operators & Expressions
Looping Constructs
The for loop
4 14-23
The while loop
The do while loop
Decision making
if and if-else structure
5 24-32
The switch case and
conditional operator
6 Functions 33-36
7 Arrays 37-40
8 Strings 41-44
9 Pointers 45-48

10 Hardware Interfacing 49-54


11 Structures 55-59
12 Linked List 60-66
13 Filling 67-71
14 Graphics 72-79
15 Project 80-82

Revised 2012MMAB/MMA
Programming with C-Language Introduction to Turbo C++ IDE
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 01

Introduction to Turbo C++ IDE


OBJECT
To study the components of Turbo C++ development environment and implement a
simple C Program.

THEORY

The Integrated Development System (IDE)


The Turbo C compiler has its own built-in text editor. The files you create with text-
editor are called source files, and for C++ they typically are named with the extension
.CPP, .CP, or .C.

Invoking the IDE


To invoke the IDE from the windows you need to
1) Install the Turbo C in your c-drive directory.
2) Go to Run and provide the following path c:\tc\bin.
3) Alternately make a shortcut of tc.exe on the desktop

This makes you enter the IDE interface, which initially displays only a menu bar
at the top of the screen and a status line below will appear. The menu bar
displays the menu names and the status line tells what various function keys will
do.

1
Programming with C-Language Introduction to Turbo C++ IDE
NED University of Engineering and Technology Department of Electrical Engineering

Opening New Window


To type a program, you need to open an Edit Window. For this Go to menu bar (Use
Alt key or mouse to select), open file menu and click new . A window will appear on
the screen where the program may be typed.

Implementing a Simple C Program


/* Basic C Program */
/*Hello.CPP*/
#include<conio.h>
#include<stdio.h>
void main (void) /* Defining main function*/
{
clrscr(); /* Clears previous contents of screen*/
printf( \n\n Hello World ); /*Prints the string
argument on the screen*/
getch(); /* Hold the output screen until a key is hit*/
}

Saving a Program
By pressing [F2] button or go to the menu bar File select save command. Provide
a proper extension to your file (.c, .cpp or .cp)

Making an Executable File

Now the source file is required to be turned into an executable file. This is called
Making of the .exe file. The steps required to create an executable file are:
1. Compile the source code into a file with the .obj extension.
2. Link your .obj file with any needed libraries to produce an executable program.

2
Programming with C-Language Introduction to Turbo C++ IDE
NED University of Engineering and Technology Department of Electrical Engineering

Compiler Linker
Lab01.obj
.obj .exe Lab01.exe
Lab01.c
+
+ library modules
headerfiles.h

Fig 1.1 Block Diagram

All the above steps can be done by using Compile option from the menu bar or using
key combination Alt+F9 (By this linking & compiling is done in one step).

Executing the Program

Now finally to execute the source code; menu bar Run Run or you can press
Ctrl+F9. The output window will appear on the screen.

Common Programming Errors

Forgetting to terminate a statement with;.


Forgetting to terminate a comment with */.
Using a capital letter where a lowercase letter should be used (for example,
typing Main instead of main)
Forgetting to include header files while working with a .cpp extension.
Forgetting to specify void before main ( ), in case if the function is not
returning any value.

3
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 02

C Building Blocks
(I/O and Data Types)
OBJECT
To study basic building blocks of C-language such as data types and input-output
functions.

THEORY
This Lab is concerned with the basic elements used to construct C elements. These
elements includes the C character set, identifiers, keywords, data types, constants,
variables, expressions statements and escape sequences.

Comments:
Comments statements will not to be compiled. Comments are simply the statements to
improve program readability and to document program properly. Comments begins
with /* and end with */, text is placed in between them.
/* Lab Session 2(a) */

printf() Function:
This function is used to output combination of numerical values, single character and
strings.

Syntax:-
printf ( fomat specifier , variable or constant);
printf( text );

Examples:-
printf( Area of circle is %f sqmm ,3.756);

scanf() Function:
The purpose of scanf() function is to except data from keyboard, and place that data to a
memory location specified in its argument.

Syntax:-
scanf( fomat specifiers , address of variable);

Examples:-
scanf( %d , &r);

Escape Sequences:
These are non printing characters. They are special character set, each with specific
meaning. An escape sequence always begins with a back slash and is followed by one
or more special characters.

4
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering

Table 2.1
Escape Sequences
Escape Sequence Meaning
\n New Line
\t Horizontal Tab
\a Alert(Bell)
\\ Back Slash
\ Quotation Mark
\f Form feed
\r Carriage Return
\0 Null

Variables:
A variable name is a location in memory where a value can be stored for use by a
program. All variables must be defined with a name and a data type in the code before
they can be used in a program.

A variable name in C should be a valid identifier. An identifier is a series of characters


consisting of letters, digits and underscore and does not begin with a digit. C is case
sensitive i.e. area and Area can not be treated as same.

There are certain reserved words called Keywords that have standard, predefined
meanings in C. These keywords can be used only for their intended purpose; they can t
be used as programmer defined identifier.

Data Types:
C supports several different types of data, each of which may be represented differently
within the computer s memory. The basic data types are listed below.

Table 2.2
Data Type and Storage Allocation
Data Type Meaning Bytes
char Character 1
int Integer 2
short Short Integer 2
long Long Integer 4
Unsigned Unsigned Integer 2
Float Floating 4
Double Number(Decimal) 8
Double Precision
Floating Point Number

Format Specifiers:
Format specifier specifies that which type of data has to be print or read into. Following
is a list of different format specifiers.

5
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering

Table 2.3
Format Specifiers
Specifiers Meaning
%c Character
%d Integer
%f Float value
%e Float value in exponential form
%u Unsigned Integer
%x Hexadecimal integer (unsigned)
%o Octal value
%s String

Example:

Now consider a Simple C program.


/* Lab Session 2(a) */
#include<conio.h>
#include<stdio.h>
void main (void) /* Defining main function*/
{
clrscr(); /* Clears previous contents of screen*/
int r; /* Declares a variable of type integer */
float area; /* Declares a variable of type float */
float Pi=3.14; /*Initializing a variable of type float */
printf( \t\t\tEnter the radius of circle: ); /*Output the
string on the screen*/
scanf( %d , &r); /*Stores the value on the address of variable
r*/
area=Pi*r*r; /*Evaluating area and assigning the value to
variable area*/
printf( \n\n\t\t\tArea of Circle is :%0.3f ,area);
getch();
}

Even though this program is simple, it illustrates several important features of C


language.

Output:

6
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering

EXERSISE
2.1) Identify and correct the errors in the following statements.
a) scanf( d ,value);

b)printf( The answer of %d+%d is \n,x,y);

c) scanf( %d%d ,&number1,number2);

d) printf( The number is %d /n ,&number1);

2.3) Write a single C statement to accomplish the following tasks.


a) Prompt the user to enter an integer in inverted commas.
Like this Enter an integer:

b) Read an integer from the keyboard and store the value entered in the variable
a.

c) Read two integers from the keyboard and store the value entered in the
variable a & b.

7
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering

2.3) What do these codes print?

a) printf( \n*\n**\n***\n****\n***** );

b) printf( This is\base );

c) printf( \n\t\t\t1\n\t\t2\n\t3\n4\n\t5\n\t\t6\n\t\t\t7 );

8
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 03

C Building Blocks
(Operators and Expression)
OBJECT
To study the different types of arithmetic and logical operators

THEORY
In C, there are various operators, used to form expressions. The data items on which the
operators act upon are called operands. Some operators require two operands while other
act upon only one operand.

They are classified as:


1. Arithmetic Operators (binary type)
2. Unary Operators
3. Relational and Logical Operators
4. Assignment Operator

Arithmetic Operators
In C++, most programs perform arithmetic calculations. Arithmetic calculations can be
performed by using the following arithmetic operators. Table 2.3 summarizes the C++
arithmetic operators. Note the use of various special symbols not used in algebra. The
asterisk (*) indicates multiplication and the percent sign (%) is the modulus or remainder
operator. The arithmetic operators in Table 2.3 are all binary operators, i.e., operators
that take two operands.

Table 2.3
Arithmetic Operators
C++ C++ arithmetic
C++ expression
operation operator
Addition + x+y
Subtraction - x-y
Multiplication * x*y
Division / x/y
Modulus % x%y

Unary Operators:
In addition to the arithmetic assignment operators, C++ also provides two unary
operators that act upon on a single operand to produce a new value, for adding 1 to or
subtracting 1 from the value of a numeric variable. These are the unary increment
operator, ++, and the unary decrement operator, --, which are summarized in the below
table.

9
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering

Table 2.3
Increment and Decrement Operators
Operators Operation Explanation
++a Pre Increment Increment a by 1, then use the new value of a in the
expression in which a resides.
a++ Post Increment Use the current value of a in the expression in which
a resides, then increment a by 1.
--a Pre Decrement Decrement a by 1, then use the new value of a in the
expression in which b resides.
a-- Post Decrement Use the current value of a in the expression in which
a resides, then decrement b by 1.

Assignment Operators:

C++ provides several assignment operators for abbreviating assignment expressions. For
example, the statement

c = c + 3;

can be abbreviated with the addition assignment operator += as

c += 3;

The += operator adds the value of the expression on the right of the operator to the value
of the variable on the left of the operator and stores the result in the variable on the left of
the operator.

Thus the assignment c += 3 adds 3 to c. Following table shows the arithmetic


assignment operators, sample expressions using these operators and explanations.

Arithmetic assignment operators


Assignment operator Sample expression Explanation Assigns
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
Subtraction -= d -= 4 d=d-4 1 to d
Multiplication *= e *= 5 e=e*5 20 to e
Division /= f /= 3 f=f/3 2 to f
Remainder %= g %= 9 g=g%9 3 to g

10
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering

Summary of Operator Precedence and Associativity:

Table adds the logical operators to the operator precedence and associativity chart. The
operators are shown from top to bottom, in decreasing order of precedence.

Operator Precedence and Associativity.


Operators Associativity Type
() left to right parentheses
++ -- left to right unary (postfix)
++ -- + - ! right to left unary (prefix)
* / % left to right multiplicative
+ - left to right additive
<< >> left to right insertion/extraction
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment

Common Programming Errors

It is syntax error to place a calculation on the left side of an assignment operator.


Forgetting one or both of the double quote surrounding the format control string
in a printf() or scanf() statement.
Forgetting to precede a variable name, in scnaf() statement, with an ampersand
& operator.
An attempt to divide by zero is normally undefined on computer system results in
a fatal error.
A syntax error will occur if the two symbols in any of the operator ==, !=, >=
and <= are separated by space.
Confusing the equality operator == with the assignment operator.

11
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering

EXERSISE
3.1) Identify and correct the errors in the following statements.
a) if (c<7);
printf( C is less than 7\n );

b) if (c =>7);
printf( C is equal to or less than 7\n );

c)printf( Remainder of %d divided by %d is \n , x , y , x % y);

d) num1+num2=ans;

3.2) a. Evaluate the following.

1) 9.0/6.0 +5/2 =
2) 9*3/4 =
3) 14%7 +3%4 =

b. Determine the value assigned to the relevant variable.


int a;
float b;
1) b = 5/4 ; b=
2) a = 5/4 ; a=
3) b = 5/2 +3.0; b=

c. Determine the value of int x after each statement. Initially x =5.

I. printf( %d\n , x ); Ans: x =


printf( %d\n , ++x ); Ans: x =
printf( %d\n , x++ ); Ans: x =
printf( %d\n , x ); Ans: x =

12
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering

II. printf( %d\n , x ); Ans: x =


printf( %d\n , --x ); Ans: x =
printf( %d\n , x-- ); Ans: x =
printf( %d\n , x ); Ans: x =

3.3) State the order of evaluation of the operators in each of the following C statements
and show the value of x after each statement is performed.

a) x = 7 + 3 * 6 / 2 1;
b) x = 2 % 2 + 2 * 2 -2 / 2;
c) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) ) ;

Answer:
a)
b)
c)

3.4)Write a program that asks the user to enter two numbers, obtain the two numbers
from the user and print the sum, difference, quotient and remainder of the two.

13
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 04

Looping Constructs
OBJECT
To explore the concept of looping in a programming language, in general, and to study
some looping constructs available in C.

THEORY
The concept of looping provides us a way to execute a set of instructions more than once
until a particular condition is true. In C, loop is constructed by three ways.
1. The for loop
2. The while loop
3. The do while loop

The for Statement


The for loop is appropriate when you know in advanced how many times the loop will be
executed. Here you have a counter variable whose limits are define.

The general form of the for statement is

for ( initialization of counter; loop continuation condition; increment counter )


statements;

The initialization expression initializes the loop's control variable or counter (it is
normally set to 0); loop continuation condition determines whether the loop counter is
within its limits or not and finally the increment statement increments the counter
variable after executing the inner loop statements. The flow chart of the for loop can be
shown as

Set counter

TRUE
Check Loop Increment
Condition Statements Counter

FALSE

14
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering

Source Code:

/* for loop*/
void main(void)
{
clrscr();
int counter; /*Declaring a counter variable*/
int table=2; /*To print the table of */
for(counter =1;counter <=10;counter++)
printf("\n%3d *%3d =%3d",table,counter,table*counter);
getch();
}

Output:

The while Statement:

The while loop is used to carry out looping operations, in which a group of statements is
executed repeatedly, if condition following while is true otherwise control is transferred
to the end of the loop. Here we do not know how many times the loop will be executed.

The general form of the while statement is


while (condition)
{
statement1;
:
statement2;
}

15
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering

The flow chart of the while loop is show below

TRUE
Check Loop
Condition Statements

FALSE

Source Code:

/* while loop*/
void main(void)
{
clrscr();
char guess; /*Declaring a counter variable*/
printf("Enter a character from a to f:");
guess=getche();
while(guess!='e')
{
printf("\nRetry!");
printf("\nEnter a character from a to f:");
guess=getche();
}
printf("\nThats it!");
getch();
}

Output

16
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering

The do while Statement

The do while repetition statement is similar to the while statement. In the while
statement, the loop-continuation condition test occurs at the beginning of the loop before
the body of the loop executes. The do while statement tests the loop-continuation
condition after the loop body executes; therefore, the loop body always executes at least
once.

do
{
Statement;
}
while (condition );

This loop must be executed at least once because the condition is checked at the end. If
the condition is following while is true the control is transferred to the beginning of the
loop statement otherwise control is transferred to the statement following while
statement.

Loop
Statements

TRUE
Check
Condition

FALSE

17
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering

Source Code:

/*do while loop*/


/*Nested Loop*/
void main(void)
{
clrcsr();
char guess; /*Declaring a counter variable*/
int cnt,num;
do
{
printf("\nEnter a number to print its table");
scanf( %d ,&num);
for(cnt=1;cnt<=10;cnt++)
printf( \n%3d*%3d =%3d ,num,cnt,num*cnt);
printf( Press r to repeat );
guess=getch();
}
while(guess =='r');
printf("\n Program terminated");
getch();
}

Output:

18
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering

Common Programming Errors

Using commas instead of semicolon in a for header is a syntax error.


Placing a semicolon immediately to the right of the header makes the body of
that for statement an empty statement.
Forgetting one or both of the braces that delimit a compound statement.
Placing a semicolon after the condition in a while statement.
If a counter or total is not initialized, the result of your program will probably be
incorrect. This is an example of a logical error.
Do not compare floating point numbers.
Attempting to use the increment or decrement operator on an expression other
than a simple variable name is a syntax error, e.g. writing --(y+3);

19
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering

EXERCISE

4.1) Write a program to display the following patterns.

*
1
**
121
***
12321
****
1234321
*****
123454321
******

20
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering

21
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering

22
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering

4.2) Using for loop implement a program that generates all the possible combinations of
4 bit binary numbers. (0000 0001 0010 0011 0100 1111)

23
Programming with C-Language Decision Making
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 05(A)

Decision Making
OBJECT
To study programming control constructions used for decision making in C.

THEORY
In C, a program may require a logical test on the basis of which the program statement
will execute. This decision is based on the truth or falsity of a statement called as
Condition.
There are three major decision making structures the if statement, if-else statement and
switch case. In continuation of these structures, we shall also see a decision making
operator called as conditional operator (? :).

The if Statement:
The if statement enables you to test for a condition (such as whether two variables are equal)
and branch to different parts of your code, depending on the result or the conditions with
relational and logical operators.
The simplest form of if statement is:

if (expression)
statement;

In this form, the statement will be executed only if the expression is evaluated to a non
zero value (i.e. if the expression is true).

Condition
True

False
Statement

24
Programming with C-Language Decision Making
NED University of Engineering and Technology Department of Electrical Engineering

An Example:

Source Code:

/* Calculator*/
#include<conio.h>
#include<stdio.h>
void main (void) /* Defining main function*/
{
clrscr(); /* Clears previous contents of screen*/
int a,b;
char op;
printf( \t\t\t\tSimple Calculator\n );
printf( \nEnter a number: );
scanf( %d ,&a);
printf( \nSelect an operator form the list * , / , +, -
: );
op=getche();
printf( \n\nEnter another number: );
scanf( %d ,&b);
if ( op == / )
printf("\n%d / %d = %d",a,b,a/b);
if ( op == * )
printf("\n%d * %d = %d",a,b,a*b);
if ( op == + )
printf("\n%d + %d = %d",a,b,a+b);
if ( op == - )
printf("\n%d - %d = %d",a,b,a-b);
printf( \n\nThanks! Press any key to terminate );
getch();
}

Output:

25
Programming with C-Language Decision Making
NED University of Engineering and Technology Department of Electrical Engineering

The if-else Statement:


The if single-selection statement performs an indicated action only when the condition is
true; otherwise the action is skipped. The if-else double-selection statement allows the
programmer to specify an action to perform when the condition is true and a different
action to perform when the condition is false.
The simplest form of if-else statement is:
if (expression)
{ statements;
}

else
{ statements;
}

True Condition
False

if Statement else Statement

An Example:

/* if-else */
void main (void) /* Defining main function*/
{
clrscr(); /* Clears previous contents of screen*/
int grade;
printf( Enter your grade );
scanf( %d ,&grade);
if ( grade >= 60 )
printf("Passed");
else
printf("Failed");
getch();
}

Output:

26
Programming with C-Language Decision Making
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 05(B)

Decision Making
OBJECT:
To study switch-case and conditional operator.

THEORY:
In previous Lab Session 4(a), we have seen if and if- else statement, but it is sometimes
required to execute a particular portion of code, only if a certain condition out of other
available conditions is true and than transfer the control to the outer part of the program,
skipping the other cases. In this lab we shall learn how to solve such situations.

The switch Statement


Occasionally, an algorithm will contain a series of decision in which a variable or
expression is tested separately for each of the constant integral value it may assume, and
different actions are taken. This is called multiple-selection. C provides the switch
multiple-selection statement to handle such decision.

When the switch statement is executed, the expression is evaluated and the control is
transferred directly to the group of statements whose case-label matches the value of the
expression. If none of the case-label matches the value of the expression, then none of
the groups within the switch statement will be selected. In this case, the control is
transferred to the statement that follows the switch statement.

If the default case is present and none of the case labels matches the original expression,
the statement of default group will be executed.
The general form of the switch statement is:

switch (identifier variable)


{
case identifier_One: statement; break;

case identifier_Two: statement; break;


....
case identifier_N: statement; break;

default: statement;

27
Programming with C-Language Decision Making
NED University of Engineering and Technology Department of Electrical Engineering

An Example:

/*Switch case */
void main(void)
{
clrscr();
char grade;
printf("\nEnter your grade: ");
scanf("%c",&grade);
switch (grade)
{
case 'A':
case 'a':
printf("Your percentage is in between 90 - 100 \n");
break;
case 'B':
case 'b':
printf("Your percentage is in between 80 - 89 \n");
break;
case 'C':
case 'c':
printf("Your percentage is in between 70 - 79 \n");
break;
case 'D':
case 'd':
printf("Your percentage is in between 60 - 69 \n");
break;
default:
printf("Your percentage is below 60 \n");
}
getch();
}

Output:

28
Programming with C-Language Decision Making
NED University of Engineering and Technology Department of Electrical Engineering

Conditional Operator:
The conditional operator (? :) in C is a ternary operator; that is, it is the only operator to
take three terms.
The conditional operator takes three expressions and returns a value:

Variable = (expression1) ? (expression2) : (expression3)

When evaluating a conditional expression, expression1 is evaluated first. If expression1


is true then the expression2 is evaluated and this becomes the value of the conditional
expression. However if expression1 is false then expression3 is evaluated and this
becomes the value of the conditional expression variable.

An Example

/* Conditional Operator */

void main (void) /* Defining main function*/


{
clrscr();
int per;
printf("\nEnter your percenatge\n");
scanf("%d",&per);
printf("You are ");
printf ("%s\n", per >= 60 ? "Passed": "Failed");
getch();
}

Output:

Common Programming Errors:

Placing semicolon after if statement.


Placing a variable as a case identifier.
Forgetting a break statement when it is necessary in switch statement is a logical
error.
Non integer Case identifier.
Placing a relational expression in switch statement.

29
Programming with C-Language Decision Making
NED University of Engineering and Technology Department of Electrical Engineering

EXERSISE

5.1) Write a program that determines weather a number supplied by the user is prime or
not.

30
Programming with C-Language Decision Making
NED University of Engineering and Technology Department of Electrical Engineering

5.2) Implement this if statement using switch-case.

if( a = = 0 || a = = 1 || a = = 2 || a = = 3)
printf( How is it possible? );
else
printf( That s right! );
read the value of integer type variable a before applying checks.

31
Programming with C-Language Decision Making
NED University of Engineering and Technology Department of Electrical Engineering

5.3) Write a program to find out the sum of the digits present in an integer.
Example: Enter an integer: 777
Sum of digits = 21

32
Programming with C-Language Functions
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 06

Functions
OBJECT
To study the implementation and operation of functions in C.

THEORY
The best way to develop and maintain a large program is to construct it from smaller
pieces or modules each of which is more manageable than the original program.
Modules in C are called functions, which are used to perform specific tasks.
Packaging code as a function, allows the code to be executed from several locations in
a program simply by calling the function. You can use as many functions in a
program, and any function can call any of the other functions.

An Example of C-Function
Each program we have presented has contained a function called main() that called
standard library functions to accomplish its tasks. We now consider how programmers
write their own customized functions.

Consider a program that uses a function square to calculate the squares of the integers
(1 to 5).

Source Code:

/* Calculator*/
#include<conio.h>
#include<stdio.h>
int square(int);
void main (void) /* Defining main function*/
{
clrscr(); /* Clears previous contents of screen*/
int x;
for(x=1;x<=5;x++)
printf( Square of %d is %d\n ,x,square(x));
getch();
}
int square(int y)
{
return y*y;
}

33
Programming with C-Language Functions
NED University of Engineering and Technology Department of Electrical Engineering

Output

Function Prototype: [ int square (int);]


It tells the complier
The name of the function [int square (int);]
The data type of the information which the function returns to the calling
function [int square (int);]. In case of main function, the return type
void tells the compiler that a function does not return a value and
The data type of the function s argument [int square (int);] i.e. the type
of information which is transferred by the calling function.

Function Call: [printf( Square of %d is %d\ n , x , square(x)) ;]


Function square is invoked or called by the main() with in the printf statement.

Function Definition:
It contains all the statements or the operations to be performed by the function and is
defined outside the main( ).
The int y , in the parentheses informs the compiler that square expects to receive an
integer value from the caller and it will store that value in its local variable y.

Common Programming Errors


Forgetting the semicolon at the end of the prototype is a syntax error

return_type fun_name (parameter_type);


Defining a function inside another function is a syntax error.
Defining a function parameter again as a local variable with in the function
is a syntax error.
int square (int y)
{
int y=5;

}
Omitting the return-value-type in a function definition is a syntax error if the
function prototype specifies a return type other than int.
A function prototype placed outside any function definition applies to all
calls to the function appearing after the function prototype.

34
Programming with C-Language Functions
NED University of Engineering and Technology Department of Electrical Engineering

EXERCISE
6.1) Implement a UDF that takes coefficients of quadratic equation a, b, c)
a x2 + b x + c = 0 .
and specify whether the equation has real or complex roots. Also it should specify
whether the roots are identical or different.

35
Programming with C-Language Functions
NED University of Engineering and Technology Department of Electrical Engineering

6.2) Implement user defined function;


long pow( int base, int exponent).

pow(2,3) = 23 = 2*2*2.

36
Programming with C-Language Arrays
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 07

Arrays
OBJECT
To understand how to define an array, initialize an array and refer to individual
element of an array.

THEORY
In C we define an array (also termed as subscripted variable) as a collection of
variables of certain data type, placed contiguously in memory. Let s examine this
definition more closely.
Like any other variable in C, an array must be defined
int EE[15];
This statement declares an array variable, named EE, capable of holding 15 integer
type data elements. The brackets [] tell the compiler that we are dealing with an array.
Array Example
The following example presents how to define arrays, how to initialize arrays and
how to perform many common array manipulations.

Source Code

/* Arrays*/
void main(void)
{
int arr1[4]; /*Declaring 4-element array of
integer type*/
int arr2[4]={1,2,3,4,5};
for(int i=0;i<4;i++) /*Accessing arr1*/
{
printf( \nEnter an integer value: );
scanf( %d ,&arr[i]);
}
printf( \t\t\tarr1 );
for(i=0;i<4;i++) /*Accessing arr1 to print stored
values*/
printf( \nElement No %d of arr1 is d , i+1, arr1[i]);
printf( \t\t\tarr2 );
for(i=0;i<5;i++) /*Accessing arr2*/
printf( \nElement No %d of arr1 is d , i+1, arr2[i]);
getch();
}
NOTE: All the array elements are numbered. The first element in an array is
numbered 0, so the last element is one less than the size of the array.

37
Programming with C-Language Arrays
NED University of Engineering and Technology Department of Electrical Engineering

Output

Common Programming Errors

Forgetting to initialize the number of elements of an array whose elements are


not initialized.
int arr[];

Using a variable to specify number of elements of an array.


int var;
int arr[var];

Providing more initializers in an array initializer list than the elements in the
array is a syntax error.
int arr[3] = {1,2,3,4};

The array subscript should not go below 0, and is always less than the total
number of elements in the array.

38
Programming with C-Language Arrays
NED University of Engineering and Technology Department of Electrical Engineering

EXERCISE:

7.1) Write a program to convert a decimal number into its binary equivalent.

39
Programming with C-Language Arrays
NED University of Engineering and Technology Department of Electrical Engineering

7.2) Read in 20 numbers, each of which is in between 10 and 100. As each number is
read, print it only if it is not a duplicate of number already read.

40
Programming with C-Language Strings
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 08

Strings
OBJECT
To study how to manipulate strings and become familiar with some of the library
function available for strings in C.

THEORY
A string is an especial type of array of type char. Strings are the form of data used in
programming languages for storing and manipulating text.
A string is a one dimensional array of characters. Following are some examples of string
initializations

char str1[]={ N , E , D , \0 };
char str2[]={ NED };
char str3[]= NED ;

Each character in the string occupies one byte of memory and the last character is always
a NULL i.e. \0 , which indicates that the string has terminated. Note that in the second
and third statements of initialization \0 is not necessary. C inserts the NULL character
automatically.

An example

Let us consider an example in which a user provides a string (character by character) and
then the stored string is displayed on the screen.
Source Code:

/* Strings*/
void main(void)
{
clrscr();
char str[20];
char ch;
int i=0;
printf( \nEnter a string (20-characters max): );
while((ch=getche())!= \r ) /*Input characters until
return key is hit*/
{
str[i]=ch;
i++;
}
str[i] = \0 ;
printf( \nThe stored string is %s ,str);
getch();
}

41
Programming with C-Language Strings
NED University of Engineering and Technology Department of Electrical Engineering

NOTE: It is necessary to provide \0 character in the end. For instance if you make
that statement a comment, you will observe erroneous results on the screen.

Output

Library Functions for Strings


There are many library functions for string handling in C. Some of the most common are
listed below. In order to use these library functions you have to include header file
named string.h.

Functions Use
strlen Finds length of the string
strlwr Converts a string to lowercase
strupr Converts a string to uppercase
strcpy Copies a string into another
strcmp Compares two strings
strrev Reverses string
gets Input string from keyboard
puts Output string on the screen

Study all the above mentioned functions.

An Example:
A palindrome is a string that is spelled the same way forward and backwards. Some
examples of palindromes are: radar , mom and dad . Let s implement a program
that that determines whether the string passed to is palindrome or not.

42
Programming with C-Language Strings
NED University of Engineering and Technology Department of Electrical Engineering

Source Code
/* Get familiar with Library functions */
#include<conio.h>
#include<stdio.h>
#include<string.h> /* Header file for string library
function*/
void main(void)
{
clrscr();
char str1[20];
char str2[20];
printf("\nEnter a string (20-characters max):");
gets(str1); /*Input string*/
strcpy(str2,str1); /*Equating the two strings*/
strrev(str2); /*Reverses str2*/
if(strcmp(str1,str2)==0) /*Making decision*/
printf("\nIt is a palindrome");
else
printf("\nIt is not a palindrome");
getch();
}

Output:

Common Programming Errors

Not allocating sufficient space in a string to store the NULL character that
terminates the string is a syntax error.
Printing a string that does not contain a terminating NULL character is an
error.
Passing a character as an argument to a function when a string is expected is a
syntax error and vice versa
Forgetting to include header files.
Trying to use relation logical operators on strings. (==, !=)
Assuming that strcmp return 1 when there arguments are equal is a logical
error.

43
Programming with C-Language Strings
NED University of Engineering and Technology Department of Electrical Engineering

EXERSISE
8.1) Carefully observe the output generated by a program. You are required to write the
source code for the program.
Please, enter your password: ******
Please Re-Enter your password: ****
Sorry, try again

Please Re-Enter your password: ******


You may proceed now.

44
Programming with C-Language Pointers
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 09

Pointers
OBJECT:
To study the concept of pointers in C and their applications.

THEORY:
Pointers are variables whose values are memory addresses. Normally, a variable directly
contains a specific value. A pointer, on the other hand contains, an address of a variable
that contains a specific value.
Pointers are used in situations when passing actual value is difficult or undesirable; like,
returning more than one value from a function. The concept of pointers also provides an
easy way to manipulate arrays and to pass an array or a string from one function to
another.

An example
Let s explore how we declare and initialize a pointer variable, using the following
example.
/* Pointers*/

void main(void) /*Defining main()*/


{
int x = 3;
int *ptx; /*Declaring a pointer type variable, which will
point to an integer variable*/
ptx=&x; /* Initializing the value of ptx*/
printf( Address of variable x: %p ,ptx);
/*prints the value stored in ptx*/
printf( Value stored in x :%d ,*ptx);
/*Referencing variable x using its pointer*/
getch();
}

Output

45
Programming with C-Language Pointers
NED University of Engineering and Technology Department of Electrical Engineering

Address on your screen would be different, as they it is allocated when the program
executes.

The Indirection Operator: *

The indirection unary operator * , is used to access the contents of the memory location
pointed to. The name indirection Operator stems from the fact that the data is accessed
indirectly . The same operator is some times called as dereference operator.

Hence, * has several different uses


Multiply Operator (binary)
Indirection Operator (Unary)
Used in declaration of a Pointer.

Each time you use * , the complier distinguishes its meaning by the context.

Pointers and Arrays

There is an inherent relationship between arrays and pointers; in fact, the compiler
translates array notations into pointer notations when compiling the code, since the
internal architecture of the microprocessor does not understand arrays.

An array name can be thought of as a constant pointer. Pointer can be used to do any
operation involving array subscript. Let us look at a simple example.

An example:
/*Pointers and Arrays*/
void main(void)
{
int arr[4]={1,2,3,4}; /*Initializing 4-element
integer type array*/
for(int indx=0;indx<4;indx++)
printf( \n%d ,arr[indx]);
for(int indx=0;indx<4;indx++)
printf( \n\t%d ,*(arr+indx));/*arr is a constant pointer
referring to 1st element*/
int *ptr=arr; /*ptr is a pointer variable, storing
base address of array*/
for(int i=0;i<4;i++)
printf( \n\t\t%d ,*ptr++);/*ptr will be incremented(by 2-
byte) on the bases of its type*/
getch();
}

46
Programming with C-Language Pointers
NED University of Engineering and Technology Department of Electrical Engineering

Output

Common Programming Errors

The asterisk notation used to declare pointer variables does not distribute to all
variable names in a declaration. Each pointer must be declared with the * prefix
to the name.

int *ptx,*pty;

Initialize pointers to prevent unexpected results.


If you try to store an address in a pointer of wrong type, then your program will
not compile.
Attempting to modify an array name with pointer arithmetic is a syntax error.

47
Programming with C-Language Pointers
NED University of Engineering and Technology Department of Electrical Engineering

EXERSISE

9.1) Write a program to sort 10-element array in an ascending order, access the array
using a pointer variable.

48
Programming with C-Language Hardware Interfacing
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 10

Hardware Interfacing
OBJECT:
To study a method of hardware interfacing using C .

THEORY:
This lab will help you to control the hardware using the parallel port. Here we shall send
signals to the parallel port to control the device connected to it.

Parallel Port Description:


Parallel port interfacing is a simple and inexpensive tool for building computer
controlled devices and projects. The simplicity and ease of programming makes parallel
port popular in electronics hobbyist world.

You can see the parallel port connector in the rear panel of your PC. It is a 25 pin female
(DB25) connector (to which printer is connected). On almost all the PCs only one
parallel port is present, but you can add more by buying and inserting ISA/PCI parallel
port cards.

In computers, ports are used mainly for two reasons: Device control and communication.
We can program PC's Parallel ports for both purposes. In PC there is always a D-25 type
of female connector having 25 pins, the function of each pins are listed below.

Parallel ports are easy to program and faster


compared to the serial ports. But main
disadvantage is it needs more number of
transmission lines. Because of this reason
parallel ports are not used in long distance
communications.
D25- Pin
Function
Number
1 Strobe
2 to 9 Data Lines
10 Acknowledgement
11 Busy
12 Out of Paper
13 Select
14 Auto feed
15 Error
16 Init
17 Select In
Figure 1
18 to 25 GND
- N/C
Table 10.1 Pin numbers and their functions
25-way Female D-Type Connector

49
Programming with C-Language Hardware Interfacing
NED University of Engineering and Technology Department of Electrical Engineering

The Pins having a bar over them means that the signal is inverted by the parallel port's
hardware. If a 1 were to appear on the 11 pin [S7], the PC would see a 0.

Only the Data Port will be covered in this Lab.

Sending Commands to the Data Port


Sending commands involves only the data pins [D0 to D7].Though it is possible to use
the some other pins as input, we'll stick to the basics.

Please remember that the Data pins are from pin 2 to pin 9 and not from pin 1.
The word "Parallel" denotes sending an entire set of 8 bits at once [That's why Parallel
Port term]. However we can use the individual pins of the port ; sending either a 1 or a 0
to a peripheral like a motor or LED.

Example:

Now consider a Simple C program.


/* Lab Session */
#include <stdio.h>
#include <conio.h>
#include <dos.h>
void main(void)
{
outportb(0x378,0xFF);
}

Now take an LED and put one terminal at pin2 and the other to pin 18,it
would glow.[Use a 2K resistor in series with the LED, otherwise you'll end
up ruining your LED, or source too much current from the port pin]

To switch it off
Use this command
outportb(0x378,0x00);
Instead of the line
outportb(0x378,0xFF);

Explaination of outportb(0x378,0x00) & outportb(0x378,0xFF) cmmands:

0x378 is the parallel port address.

50
Programming with C-Language Hardware Interfacing
NED University of Engineering and Technology Department of Electrical Engineering

For a typical PC, the base address of LPT1 is 0x378 and of LPT2 is 0x278. The data
register resides at this base address , status register at base address + 1 and the control
register is at base address + 2. So once we have the base address , we can calculate the
address of each registers in this manner. The table below shows the register addresses of
LPT1 and LPT2.

Register LPT1 LPT2


data registar(baseaddress + 0) 0x378 0x278
status register (baseaddress + 1) 0x379 0x279
control register (baseaddress + 2) 0x37a 0x27a

0x00 is the command appearing at the output pins. The Format is in Hexadecimal
So if u want to make pin no 2 high, that's the first data pin, send 0x01 to the parallel port.

0x01 which would mean 0000 0001 for the data port.
Similarly for other pins.

Note:
This sample program will not work on Windows NT/2000 or XP if you run the program
on these operating systems, it will show an error. Use new Inpout32.dll on NT/2000/XP
OS.

Paste the " inpout32.DLL " in the system files (C:\WINDOWS\system32 and in the
folder C:\WINDOWS\system).

This finishes your basics so that you can run your own hardware (e.g. DC motor) using
parallel port.

51
Programming with C-Language Hardware Interfacing
NED University of Engineering and Technology Department of Electrical Engineering

EXERCISE
10.1) Construct an interfacing circuit to control the direction of DC motor using the
parallel port.

Components List:

Circuit Diagram:

52
Programming with C-Language Hardware Interfacing
NED University of Engineering and Technology Department of Electrical Engineering

Source Code:

53
Programming with C-Language Hardware Interfacing
NED University of Engineering and Technology Department of Electrical Engineering

54
Programming with C-Language Structures
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 11

Structures
OBJECT
To study the implementation and applications of Structures in C.

THEORY
Structures are basically derived data types means they are constructed using other data
types. So far we have studied that how variables of different data types hold particular
type of data depending on their nature and how arrays stored number of similar data
types but in some situation these approaches become too unwieldy when we deal, for
instance, with different type of information related to a single entity. The concept of
structures provides a solution in which we can construct our own data type.

An example
Consider a situation in which we have to develop a system that maintains a record of
different students. Now a particular student has a name, roll number, batch number and
so on. Let us explore this new concept in constructing a record, restricting ourselves to
these three fields only i.e. student s name, roll number and his batch.

/* Structures */
/* Declaring a structures*/
struct student /* struct is a keyword whereas student is
the structure tag*/
{
char name[20]; /*name is a string type member*/
int rolno; /*rolno is an integer type
member*/
int batch; /*batch is an integer type
member*/
}; /*Terminating declaration*/
struct student std1; /* declaring a variable std1 of
data type student*/

void main(void) /*Defining main()*/

{ /* Assigning values to the members of variable std1


of type struct student*/
strcpy(std1.name, Raheel ); /*include string.h*/
std1.rolno=53;
std1.batch=2007;
printf( The name of student is %s\n ,std1.name);
printf( Roll number %d\nBatch is %d ,std1.rolno,
std1.batch);
getch();
} /*Ending main()*/

55
Programming with C-Language Structures
NED University of Engineering and Technology Department of Electrical Engineering

Output

Arrays of structures
Since arrays can hold number of elements of same data type. Using array of structures
we can modify the above program so that data of a group of students can be processed.
/* Array of Structures */
/* Declaring a structures*/
struct student /* struct is a keyword whereas student
is the structure tag*/
{
char name[20]; /*name is a string type member*/
int rolno; /*rolno is an integer type
member*/
int batch; /*batch is an integer type
member*/
}; /*Terminating declaration*/
struct student std[10]; /* declaring a 10-element array of
data type student*/
void main(void)
{
for(int i=0;i<2;i++) /*Accessing 2- element of
array only*/
{
printf( Enter name: );
gets(std[i].name);
printf( Enter Roll#: ,);
scanf( %d ,&std[i].rolno);
printf( Enter Batch );
scanf( %d%*c ,&std[i].batch);
} /*Now complete the rest of the program to
retrieve stored data*/

56
Programming with C-Language Structures
NED University of Engineering and Technology Department of Electrical Engineering

Output

Common Programming Errors

Comparing structures is a syntax error.


Assigning a structure of one type to the structure of a different type is a
compilation error.
Attempting to refer to member of a structure by using the member s name is a
syntax error.
Avoid using the same name of members of structures of different types. This is
allowed, but it may cause confusion.

57
Programming with C-Language Structures
NED University of Engineering and Technology Department of Electrical Engineering

EXERCISE

11.1) Create a structure to specify data of customers in a bank. The data to be stored is:
Account Number, Name, and Balance in account. Assume maximum of 200 customers
in a bank. Write a function to print the account numbers and name of each costumer
with balance below 500Rs.

58
Programming with C-Language Structures
NED University of Engineering and Technology Department of Electrical Engineering

59
Programming with C-Language Linked List
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 12

Linked List

OBJECT
To study the method of implementing Dynamic data structures

THEORY
Form the term dynamic memory allocation, we mean that, the size of memory allocated
for holding data can grow as well as shrink, on the time of execution. This will
effectively help in managing memory since a predefined memory chunk can either be too
large or insufficient.
Linked list is one of the way of obtaining dynamic data structures in which collection of
data items (structures) are lined up in a row and the insertion and deletion can be made
any where in the list. Each member of the linked list (node) is connected to another by a
pointer which holds the address of the next node. The pointer of the last node points to
NULL, which means end of list. With the help of linked list we can implement a
complex data base system.
Before discussing linked list approach, we have to become familiar with some important
building blocks and functions used in dynamic memory allocation
malloc( )
It takes as an argument the number of bytes to be allocated and on call, returns a pointer
of type void to the allocated memory. This pointer can be assigned to a variable of any
pointer type. It is normally used with sizeof operator.
ptr = malloc ( sizeof( struct node));
The sizeof() operator determines the size in byte of the structure element node. If no
memory is available malloc( ) returns NULL.
free( )
The function free() deallocates memory. It takes as an argument the pointer to the
allocated memory which has to be freed.
free(ptr);
Let s explore some of the basic features of linked list from the following example. Here
we have implemented a small record holding program. It asks from the user about the
employee s name and his identification number. For that we have declared a stricture
emp capable of holding above mentioned fields along with the address of next node. The
program has two user defined functions creat() and lstal() to perform the functions of
growing nodes and listing the data of all nodes respectively.

60
Programming with C-Language Linked List
NED University of Engineering and Technology Department of Electrical Engineering

Example:

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<alloc.h>
#include<dos.h>
struct emp
{
int perno;
char name[20];
struct emp *ptnxt;
};
struct emp *ptcrt,*ptfst,*ptlst; // declaring pointer to current, first and last nodes
void creat(void); // Creates a node
void lstal(void); // List the all data
void main(void)
{
clrscr();
ptfst=(struct emp*)NULL; // Initializing 1st pointer in the beginning
char ch;
while(1)
{
printf("\ n\ nEnter Option\ nc to creat \ nd to display all entries\ nt to terminate");
printf("\ n\ t\ t\ t Your Option:");
ch=getche();
switch(ch)
{
case 'c':
creat();
break;
case 'd':
lstal();
break;
case 't':
printf("\ n\ nThanks");
getch();
exit(0);
}
}
}
void creat(void)
{
struct emp *pttemp;
pttemp=(struct emp*)malloc(sizeof(struct emp));// Generating a node
char temp[20];
if(ptfst == (struct emp*)NULL)
{
ptfst = pttemp;
ptlst = pttemp;
}
ptlst->ptnxt=pttemp;
fflush(stdin);
printf("\ n\ nENTER NAME:");
gets(pttemp->name);

61
Programming with C-Language Linked List
NED University of Engineering and Technology Department of Electrical Engineering

fflush(stdin);
printf("ID NO:");
gets(temp);
pttemp->perno=atoi(temp);
pttemp->ptnxt=(struct emp*)NULL;
ptlst=pttemp;
}
void lstal(void)
{
ptcrt=ptfst; // Starting from the first node
while(ptcrt!=(struct emp*)NULL)
{
printf("\ n\ n%s",ptcrt->name);
printf("'s id is %d",ptcrt->perno);
ptcrt=ptcrt->ptnxt; // Updating the address for next node
}
}

Output:

Note:
The significance of using a pointer to last node is to avoid searching for it every time.

62
Programming with C-Language Linked List
NED University of Engineering and Technology Department of Electrical Engineering

EXERCISE
12.1) Write a program that could delete any node form the linked list. Also make use of
free( ) function.

63
Programming with C-Language Linked List
NED University of Engineering and Technology Department of Electrical Engineering

64
Programming with C-Language Linked List
NED University of Engineering and Technology Department of Electrical Engineering

12.2) Write a program to sort all the entries, in alphabetical order, of the linked list

65
Programming with C-Language Linked List
NED University of Engineering and Technology Department of Electrical Engineering

66
Programming with C-Language Filling
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 13

Filling

OBJECT
To perform Disk I/O using C.

THEORY
Storage of data in arrays and structure members is temporary, all such data are lost when
a program terminates. Files are used for permanent retention of large data.

The smallest data item in a computer can assume the value of 0 or the value of 1. Such a
data item is called a bit. Programmer prefers to work with data in the form of decimal
digits, letters and special symbols. These are referred as characters. Since computers can
only process 1s and 0s, every character is represented as a pattern of 1s and 0s called
byte (group of 8 bits). Just as characters are composed of bits, fields are composed of
charters. A field is a group of character that conveys meaning. A record is composed of
several related fields. A file is a group of related records. A group of related files is
sometimes called as database. A collection of programs designed to create and manage
database is called as a database management system.

Let s explore some of the basic functions and features of Standard I/O (a type of disk
I/O) with the help of following program

Source Code:

/*This Program writes characters on a File*/


#include <stdio.h>
#include <conio.h>
void main(void)
{
FILE *ptf; /*Generate pointer to structure FILE*/
char ch;
ptf=fopen( c:\\tc\\bin\\ali.txt , w );/*Opens a
file*/
while((ch=getche())!= \r )
putc(ch,ptf);
fclose(ptf);/*Closes all the communication to
this file*/
}

In the first line of main(), we have generated a pointer of type FILE. FILE is a structure
that leads indirectly to the operating system s file control block. It is declared in the
header file stdio.h . The FILE pointer name ptf shall be used latter to refer to a file.
Each file must have a separate pointer.

We then make use of the function fopen to establish a line of communication with the
file. The file pointer ptf is assigned a value corresponding to the file name ali.txt.

67
Programming with C-Language Filling
NED University of Engineering and Technology Department of Electrical Engineering

Function fopen takes two arguments: a file name with path (optional) and a file opening
mode. The file open mode w indicates that the file is to be opened for writing. If a file
does not exist, it will be created and opened.

Next two lines take characters form user and write it on the file using putc() function.
The last statement closes the file. This will free the communication areas used by the file.
The areas include FILE structure and the buffer.

Different Modes of fopen()


r Opens for reading. The file must already exist
w Opens for writing. If the file already exists new contents will be written over it
a Open for append. Material will be added to the end of the file.
r+ Open an existing file for both reading and writing
w+ Open for both reading and writing
a+ Open for reading and appending.

Now let s read the file

/*This Program reads characters from a File*/


#include <stdio.h>
#include <conio.h>
void main(void)
{
FILE *ptf; /*Generate pointer to structure FILE*/
int ch;
ptf=fopen( c:\\tc\\bin\\ali.txt , r );/*Opens a
file*/
while((ch=getc(ptf))!=EOF)
printf( %c ,ch);
fclose(ptf);/*Closes all the communication to
this file*/
}

The main difference in this program is that the reading program has to search the last
character of the file. It does this by looking for the EOF (end of file) signal from the
operating system.

68
Programming with C-Language Filling
NED University of Engineering and Technology Department of Electrical Engineering

EXAMPLE OF FORMATTED I/O

/*This Program writes data on a File*/


#include<stdio.h>
#include<conio.h>
void read(void);
void write(void);
void main(void)
{
write();
read();
getch();
}
void write()
{
FILE *Wptr;
int id;
char name[20];
float sal;
Wptr=fopen("new1.dat","w");
printf("Press control+z to terminate\nId, Name, Salary:");
scanf("%d%s%f",&id,name,&sal);
while(!feof(stdin))
{
fprintf(Wptr,"%d %s %f ",id,name,sal);
printf("\nId, Name, Salary:");
scanf("%d%s%f",&id,name,&sal);
}
fclose(Wptr);
}
void read(void)
{
FILE *Rptr;
Rptr=fopen("new1.dat","r");
int id;
float sal;
char name[20];
while(fscanf(Rptr,"%d%s%f",&id,name,&sal)!=EOF)
printf("%s's id is %d and salary is
%f\n",name,id,sal);
fclose(Rptr);
}

Output:

69
Programming with C-Language Filling
NED University of Engineering and Technology Department of Electrical Engineering

EXERCISE

13.1) Write a program to store marks of students in a file. The program should take
following inputs form the user: name, class roll number and marks. At the end of the
entries, list of marks should be produced. The program should ask to append, replace or
read the existing data.

70
Programming with C-Language Filling
NED University of Engineering and Technology Department of Electrical Engineering

71
Programming with C-Language Graphics
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 14

Graphics
OBJECT
To explore some of the basic graphic functions in C.

THEORY
In C, graphics is one of the most interested & powerful future of C programming. All
video games, animations & multimedia predominantly work using computer graphics.
The aim of this lab is to introduce the basic graphics library functions.

/*shapes.cpp*/

#include<graphics.h> //header file for graphic library


functions
#include<conio.h>

void main()
{
int gd=DETECT, gm;
int poly[12]={350,450, 350,410, 430,400, 350,350,
300,430, 350,450 };
initgraph(&gd,&gm,"c:\\tc\\bgi"); /* initialization of
graphic mode*/

circle(100,100,50);
outtextxy(75,170, "Circle");
rectangle(200,50,350,150);
outtextxy(240, 170, "Rectangle");
ellipse(500, 100,0,360, 100,50);
outtextxy(480, 170, "Ellipse");
line(100,250,540,250);
outtextxy(300,260,"Line");

sector(150, 400, 30, 300, 100,50);


outtextxy(120, 460, "Sector");
drawpoly(6, poly);
outtextxy(340, 460, "Polygon");
getch();
closegraph(); /* Restore orignal screen mode */
}
/* End of program */

To run this program, you need graphics.h header file, graphics.lib library file and
Graphics driver (BGI file) in the compiler package for C. In graphics mode, all the
screen co-ordinates are mentioned in terms of pixels. Number of pixels in the screen

72
Programming with C-Language Graphics
NED University of Engineering and Technology Department of Electrical Engineering

decides resolution of the screen. In the example, circle is drawn with x-coordinate of the
center 100, y-coordinate 100 and radius 50 pixels. All the coordinates are mentioned
with respect to top-left corner of the screen.

LIBRARY FUNCTIONS

initgraph():
This fuction
initializes the graphics system by loading a graphics driver from disk (or
validating a registered driver) then putting the system into graphics mode.
initgraph also resets all graphics settings (color, palette, current position,
viewport, etc.) to their defaults, then resets graphresult to 0.

Declaration:
void far initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);

Arguments:
*graphdriver: Integer that specifies the graphics driver to be used.

*graphmode : Integer that specifies the initial graphics mode (unless *graphdriver =
DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest
resolution available for the detected driver.
pathtodriver : Specifies the directory path where initgraph looks for graphics drivers

*pathtodriver. Full pathname of directory, where the driver files reside. If the driver is
not found in the specified path, the function will search the current directory for the .BGI
files.

closegraph():
This function switches back the screen from graphcs mode to text mode. It clears the
screen also. A graphics program should have a closegraph function at the end of
graphics. Otherwise DOS screen will not go to text mode after running the program.
Here, closegraph() is called after getch() since screen should not clear until user hits a
key.

outtextxy():
Function outtextxy() displays a string in graphical mode. You can use different fonts,
text sizes, alignments, colors and directions of the text. Parameters passed are x and y
coordinates of the position on the screen where text is to be displayed.

Declaration:
void far outtextxy(int x, int y, char *text);

circle():
circle() function takes x & y coordinates of the center of the circle with respect to left top
of the screen and radius of the circle in terms of pixels as arguments.

Declaration:
void far circle(int x, int y, int radius);

73
Programming with C-Language Graphics
NED University of Engineering and Technology Department of Electrical Engineering

Arguments:
(x,y): Center point circle.
radius: Radius of circle.

rectangle() & drawpoly():


To draw a border, rectangle and square use rectangle() in the current drawing color, line
style and thickness.

To draw polygon with n sides specifying n+1 points, the first and the last point being the
same.

Declaration:
void far rectangle(int left, int top, int right, int bottom);
void far drawpoly(int numpoints, int far *polypoints);

Arguments:

(left,top) is the upper left corner of the rectangle, and (right,bottom) is its lower
right corner.
numpoints: Specifies number of points
*polypoints: Points to a sequence of (numpoints x 2) integers. Each pair of
integers gives the x and y coordinates of a point on the polygon.

To draw a closed polygon with N points, numpoints should be N+1 and the array
polypoints[] should contain 2(N+1) integers with first 2 integers equal to last 2 integers.
Output:

74
Programming with C-Language Graphics
NED University of Engineering and Technology Department of Electrical Engineering

Setting Colors:

There are 16 colors declared in graphics.h as listed bellow.


BLACK: 0 DARKGRAY: 8
BLUE: 1 LIGHTBLUE: 9
GREEN: 2 LIGHTGREEN: 10
CYAN: 3 LIGHTCYAN: 11
RED: 4 LIGHTRED: 12
MAGENTA: 5 LIGHTMAGENTA: 13
BROWN: 6 YELLOW: 14
LIGHTGRAY: 7 WHITE: 15

To use these colors, use functions setcolor(), setbkcolor() and setfillstyle().

setcolor() function sets the current drawing color. If we use setcolor(RED); and
draw any shape, line or text after that, the drawing will be in red color. You can
either use color as defined above or number like setcolor(4)
setbkcolor() sets background color for drawing.
setfillstyle() sets fill pattern and fill colors. After calling setfillstyle, if we use
functions like floodfill, fillpoly, bar etc, shapes will be filled with fill color and
pattern set using setfillstyle. The parameter pattern in setfillstyle is as follows:

Names Value Means Fill With...


EMPTY_FILL 0 Background color
SOLID_FILL 1 Solid fill
LINE_FILL 2 ---
LTSLASH_FILL 3 ///
SLASH_FILL 4 ///, thick lines
BKSLASH_FILL 5 \\\, thick lines
LTBKSLASH_FILL 6 \\\
HATCH_FILL 7 Light hatch
XHATCH_FILL 8 Heavy crosshatch
INTERLEAVE_FILL 9 Interleaving lines
WIDE_DOT_FILL 10 Widely spaced dots
CLOSE_DOT_FILL 11 Closely spaced dots
USER_FILL 12 User-defined fill pattern

75
Programming with C-Language Graphics
NED University of Engineering and Technology Department of Electrical Engineering

Here is an example program with colors, pixels, bar, cleardevice etc

/*random.csome graphics effects using random


numbers*/

#include "graphics.h"
#include "conio.h"
#include "stdlib.h"

void main()
{
int gd,gm;
gd=DETECT;

initgraph(&gd, &gm, "");


setcolor(3);
setfillstyle(SOLID_FILL,RED);
bar(50, 50, 590, 430);

setfillstyle(1, 14);
bar(100, 100, 540, 380);

while(!kbhit())
{
putpixel(random(439)+101,
random(279)+101,random(16));
setcolor(random(16));
circle(320,240,random(100));
}
getch();
closegraph();
}

random(no), defined in stdlib.h returns a random number between 0 an no. The


effect is by drawing random radius, random color circles with same center and
random pixels.
kbhit(), defined in conio.h returns a nonzero value when a key is pressed in the
keyboard. So, the loop will continue until a key is pressed.

76
Programming with C-Language Graphics
NED University of Engineering and Technology Department of Electrical Engineering

EXERCISE

14.1) Use the graphics functions to construct the following output.

Task 1:

Background
Green Color

Yellow Color

77
Programming with C-Language Graphics
NED University of Engineering and Technology Department of Electrical Engineering

Task 2:

Automatically
Red Color

Fill With Pixels

78
Programming with C-Language Graphics
NED University of Engineering and Technology Department of Electrical Engineering

79
Programming with C-Language Project
NED University of Engineering and Technology Department of Electrical Engineering

LAB SESSION 15

Project

OBJECT
Select a project based on the following areas

1) Hardware interfacing(e.g. controlling of home appliances, stepper


motor control, virtual instrumentation etc)
2) Database management system (e.g. Hospital management system,
Payroll system etc)
3) Graphical interface(e.g. Scientific calculator, Snake game, Brick
game etc)

Also prepare a report on your project.

80
Programming with C-Language Project
NED University of Engineering and Technology Department of Electrical Engineering

81
Programming with C-Language Project
NED University of Engineering and Technology Department of Electrical Engineering

82

You might also like