Programming With C-language Practical Manual
Programming With C-language Practical Manual
Programming With C-language Practical Manual
Name:
Roll Number:
Class:
Batch:
Department :
CONTENTS
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
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
THEORY
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
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)
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
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).
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.
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.
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:
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) 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
a) printf( \n*\n**\n***\n****\n***** );
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.
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;
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.
10
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering
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.
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 );
d) num1+num2=ans;
1) 9.0/6.0 +5/2 =
2) 9*3/4 =
3) 14%7 +3%4 =
12
Programming with C-Language C Building Blocks
NED University of Engineering and Technology Department of Electrical Engineering
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 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 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.
15
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering
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 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:
Output:
18
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering
19
Programming with C-Language Looping Constructs
NED University of Engineering and Technology Department of Electrical Engineering
EXERCISE
*
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
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
else
{ statements;
}
True Condition
False
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
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.
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:
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:
An Example
/* Conditional Operator */
Output:
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
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 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.
}
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
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
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
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
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:
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
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*/
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 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.
Each time you use * , the complier distinguishes its meaning by the context.
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
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;
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.
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.
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.
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 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);
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.
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*/
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
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:
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.
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
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*/
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");
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.
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:
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:
75
Programming with C-Language Graphics
NED University of Engineering and Technology Department of Electrical Engineering
#include "graphics.h"
#include "conio.h"
#include "stdlib.h"
void main()
{
int gd,gm;
gd=DETECT;
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();
}
76
Programming with C-Language Graphics
NED University of Engineering and Technology Department of Electrical Engineering
EXERCISE
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
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
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