Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
21 views49 pages

Complete Manual

Uploaded by

elctech2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views49 pages

Complete Manual

Uploaded by

elctech2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

C Programming

King Khalid University


111CCE-1 College of Computer Science
Department of Computer Engineering

LABORATORY MANUAL
C Programming

111CCE-1
C Programming Lab

Student Information
Name: ___________________________________________________________________________________

ID Number: ________________________ Serial Number: _____ Group Number: ___________

Marks

1443 1st Semester


Syllabus and Course Outline
Course Outline:

Week Experiment Date


Name of the experiment
Number Number (2021)
1 Start of classes and Manual Registration
2 Experiment 1 Introduction to Lab.
3 Experiment 2 Programs using I/O statements , data types,
4 Experiment 3 Programs with operators, expressions
5 Experiment 4 Programs using decision-making constructs if, if-else
Programs using decision-making constructs nested if,
6 Experiment 5
switch
7 Experiment 6 Programs using loops – while, do-while, for
8 Experiment 7 Programs with Array – One dimensional array
9 Experiment 8 Programs with Array – Two dimensional array
10 Experiment 9 Programs using functions
11 Experiment 10 Programs with String functions
12 Experiment 11 Programs with pointers
13 Experiment 12 Programs with structures and unions
14 Experiment 13 Programs with file processing
15 Final Practical Examination

Grades:
 Lab Activity 25% marks
 Lab Report/Exam/Quiz 10% marks
 Homework/Project 15% marks
 Final Exam 50% marks

Lab Policy:
 Attendance is Mandatory.
 Copies in labs will get a grade of ZERO.
 Elearning 10% i.e 3 Lectures of 50minutes each.

© Computer Engineering Dept. Page 2


Academic Calendar Year 1443 H
First Semester

© Computer Engineering Dept. Page 3


Computer Engineering Lab Rules and Policies
GENERAL LABORATORY SAFETY POLICY
The University of King Khalid University (KKU) is committed to providing a safe
learning and working environment for its students, staff and faculty.
The University of King Khalid University (KKU) and College of Computer Science
require all students, visitors, staff and faculty to obey all Laboratory Safety Rules when
present in all Computer Engineering laboratories at all times.

GENERAL LABORATORY SAFETY RULES


Food, drinks (water, coffee, tea,….), substances and related utensils shall not be brought
into, stored or consumed in any laboratory.
Smoking is prohibited in all laboratories at all times.
Avoid all horseplay in the laboratory.
Do not reboot, turn off, or move any workstation or PC.
Do not load any software on any lab computer. Only lab operators and technical support
personnel are authorized to carry out these tasks.
Do not reconfigure the cabling/equipment without prior permission.
Do not leave a workstation or a login unattended.
Do not leave processes in the background without prior approval from the Systems
Manager.
Unauthorized users are not permitted in the computer labs. The departmental computer
resources are to be used to support the instructional and research activities of the
Computer Engineering (CE) Department. Abuse of these resources or conduct not in
accord with University policy shall not be tolerated.
Games may not be played on Computer lab systems or servers or cell phone,……. Etc.
Footwear shall be serviceable, provide full coverage of the feet and have non-skid soles;
All occupants shall be familiar with the locations and operation of safety and emergency
equipment, including but not limited to, fire extinguishers, first aid kits, emergency
eyewash stations and emergency showers, emergency power off system, fire alarm pull
stations, emergency telephones, and emergency exits and egress plans.
Learn and know what to do in an emergency.
Unauthorized person(s) shall not be allowed in a laboratory for any reason.
"Authorized" means having an official university business in the laboratory with the
permission of the College of Engineering. Anyone under the age of eighteen must be
under the immediate and direct supervision of a qualified authorized person at all times.
Laboratories shall be secured when unoccupied.
Never open (remove cover) of any equipment in the laboratories. Never "jump,"
disable, bypass or otherwise disengage any safety device or feature of any equipment in
the laboratories.

© Computer Engineering Dept. Page 4


All safety instructions, warnings, posted signs, verbal orders shall be complied with by
all personnel.
Report all problems and potential hazards in the Laboratories and Technical Support
Unit (LTS U) room 13 /3/A -Computer Science Bldg-A.
In case of emergency, dial 998.

Electrical Safety Guidelines


Be familiar with the electrical hazards associated with your workplace.
You may enter the laboratory, only when authorized to do so and only during authorized
hours of operation.
Be as careful for the safety of others as for yourself. Think before you act. Be tidy and
systematic.
Remove metal bracelets, rings or watch straps when working in the laboratories.
Food, drinks (water, coffee, tea,….), and other substances are strictly prohibited in the
laboratory at all times. Avoid working with wet hands and clothing.
Use extension cords (wires) only when necessary and only on a temporary basis.
Request new outlets if your work requires equipment in an area without an outlet.
Discard damaged cords(wires), cords that become hot, or cords with exposed wiring.
Before equipment is energized ensure, (1) circuit connections and layout have been
checked by a Teaching Assistant (TA) or Lecturer and all colleagues in your group give
their assent.
Know the correct handling, storage and disposal procedures for batteries, cells,
capacitors, inductors and other high energy-storage devices.
Experiments left unattended should be isolated from the power supplies. If for a special
reason, it must be left on, a barrier and a warning notice are required.
Equipment found to be faulty in any way should be reported to the LTSU immediately
and taken out of service until inspected and declared safe.
Voltages above 50V RMS AC and 120V DC are always dangerous. Extra precautions
should be considered as voltage levels are increased.
Never make any changes to circuits or mechanical layout without first isolating the
circuit by switching off and removing connections to power supplies.
Every lab is equipped with and Emergency Power Off System. This consists of a large
switch on the wall labeled 'Emergency Power Off'. When this switch is
depressed, electrical power to the lab will shut off, except for the lights. Only authorized
personnel are permitted to reset power once the Emergency Power Off system has been
engaged.

© Computer Engineering Dept. Page 5


Electrical Emergency Response
The following instructions provide guidelines for handling two types of electrical emergencies:
1. Electric Shock:
When someone suffers a serious electrical shock, he or she may be knocked unconscious. If the
victim is still in contact with the electrical current, immediately turn off the electrical power
source. If you cannot disconnect the power source, depress the Emergency Power Off switch.
IMPORTANT:
Do not touch a victim that is still in contact with a live power source; you could be electrocuted.
Have someone call for emergency medical assistance immediately. Administer first-aid, as
appropriate.
2. Electrical Fire:
If an electrical fire occurs, try to disconnect the electrical power source, if possible. If the fire is
small and you are not in immediate danger; and you have been properly trained in fighting fires,
use the correct type of fire extinguisher to extinguish the fire. When in doubt, push in the
Emergency Power Off button.
DANGER: NEVER use water to extinguish an electrical fire.
The above general laboratory safety rules are designed to safeguard you and your co-workers, fellow
students and colleagues and are a minimum requirement for individuals working in laboratories at The
KKU. Specialized training and rules may apply depending type and scope of activities involved.

-------------------------------------------------------------------------------------------------------------------------------------
I have read and understand these rules and procedures, I agree to abide by these rules
and procedures at all times while using these facilities, I understand that failure to
follow these rules will result in disciplinary action may be taken.

Student Name: -------------------------------------------------------------------------- Student ID: --------------------------

Lab #: - -------------------- Date: - ------------------------------ Signature: - ------------------------------------------

© Computer Engineering Dept. Page 6


CONTENTS

S. No. Experiment Name Page No

1. Introduction to Lab 08

2. Programs using I/O statements , data types 13

3. Programs with operators, expressions 17

4. Programs using decision-making constructs if, if-else 21

5. Programs using decision-making constructs nested if, switch 24

6. Programs using loops – while, do-while, for 27

7. Programs with Array – One dimensional array 30

8. Programs with Array – Two dimensional array 33

9. Programs using functions 36

10. Programs with String functions 40

11. Programs with pointers 43

12. Programs with structures and unions 47

13. Programs with file processing 50

© Computer Engineering Dept. Page 7


Experiment #1
Introduction to Lab
Aim: Introduction to C Programming Lab.
Objectives:
1. Introduction to Lab.
2. C Programming Software and Operating System.

Hardware Requirement: Desktop Computer / labtop computer


Software Requirement: Linux Operating System with GCC/ TURBOC IN WINDOWS OS
INTRODUCTION TO C LANGUAGE
C is a general-purpose high level language that was originally developed by Dennis Ritchie
for the Unix operating system. It was first implemented on the Digital Equipment Corporation PDP-
11 computer in 1972. The Unix operating system and virtually all Unix applications are written in the
C language. C has now become a widely used professional language for various reasons.
 Easy to learn
 Structured language
 It produces efficient programs.
 It can handle low-level activities.
 It can be compiled on a variety of computers.

Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around 1970
 The language was formalized in 1988 by the American National Standard Institue (ANSI).
 By 1973 UNIX OS almost totally written in C.
 Today C is the most widely used System Programming Language.
 Most of the state of the art software have been implemented using C

Why to use C?
C was initially used for system development work, in particular the programs that make-up the
operating system. C was adoped as a system development language because it produces code that runs
nearly as fast as code written in assembly language. Some examples of the use of C might be:
 Operating Systems  Language Compilers  Assemblers
 Text Editors  Print Spoolers  Network Drivers
 Modern Programs  Data Bases  Language Interpreters
 Utilities

© Computer Engineering Dept. Page 8


BASIC STRUCTURE OF C PROGRAMMING

1. Documentation section: The documentation section consists of a set of comment lines giving the
name of the program, the author and other details, which the programmer would like to use later.
2. Link section: The link section provides instructions to the compiler to link functions from the
system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such using the #define
directive.
4. Global declaration section: There are some variables that are used in more than one function. Such
variables are called global variables and are declared in the global declaration section that is outside
of all the functions. This section also declares all the user-defined functions.
5. main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the executable part.
2. Executable part: There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces. The program execution begins
at the opening brace and ends at the closing brace. The closing brace of the main function is the
logical end of the program. All statements in the declaration and executable part end with a
semicolon.
6. Subprogram section: If the program is a multi-function program then the subprogram section
contains all the user-defined functions that are called in the main () function. User-defined functions
are generally placed immediately after the main () function, although they may appear in any order.

© Computer Engineering Dept. Page 9


PROCESS OF COMPILING AND RUNNING C PROGRAM
We will briefly highlight key features of the C Compilation model here.

The C Compilation Model


The Preprocessor
The Preprocessor accepts source code as input and is responsible for
 removing comments
 Interpreting special preprocessor directives denoted by #.
For example
 #include -- includes contents of a named file. Files usually called header files. e.g
o #include -- standard library maths file.
o #include -- standard library I/O file
 #define -- defines a symbolic name or constant. Macro substitution.
o #define MAX_ARRAY_SIZE 100
C Compiler
The C compiler translates source to assembly code. The source code is received from the
preprocessor.
Assembler
The assembler creates object code. On a UNIX system you may see files with a .o suffix (.OBJ on
MSDOS) to indicate object code files.
Link Editor
If a source file references library functions or functions defined in other source files the link editor
combines these functions (with main()) to create an executable file.

© Computer Engineering Dept. Page 10


In Linux:
 User should open the Terminal.
 Inside the Terminal user can create a c file:
o vi or gedit
 vi program1.c // i to insert text, :wq to save and exit
or
 gedit program1.c // user can save and exit to the terminal

 Compile the C program on Terminal:


o gcc
 gcc program1.c

 Output of the C program on Terminal:


o ./a.out // to know the output of the current program

Program 1: Write a C program to display “Welcome to C Programming”.


#include<stdio.h>
void main()
{
printf(" Welcome to C Programming ");
}

Welcome to C Programming
Output/Conclusion:

Program 2: Write a C program to add two numbers.


#include<stdio.h>
void main()
{ int num1=10, num2=20, sum;
sum = num1 + num2;
printf(" Sum of two numbers: %d ",sum);
}
Output/Conclusion: Sum of two numbers: 30

© Computer Engineering Dept. Page 11


Program 3: Write a C program to add two numbers by accepting input from the
keyboard.
#include<stdio.h>
void main()
{ int num1, num2, sum;
printf("Enter num1: ");
scanf("%d", &num1);
printf("Enter num2: ");
scanf("%d", &num2);
sum = num1 + num2;
printf(" Sum of two numbers: %d ",sum);
}
Output/Conclusion: Enter num1: 135
Enter num2: 642
Sum of two numbers: 777

Program 4: Write a C program to demonstrate escape sequence characters.


#include<stdio.h>
void main()
{
printf(" \n Welcome to \t C \n Programming ");
}

Output/Conclusion: Welcome to C

Programming

Activity-Program-5: Write a C program to find Area(𝝅𝒓𝟐 ) and Circumference(2𝝅𝒓)


of a Circle. (𝝅 = 𝟑. 𝟏𝟒). (For float input-output you can use %f )

Activity-Program-6: Write a C program to find Area(length*breadth) and


Perimeter(2*[length+breadth]) of a Rectangle by accepting input from the keyboard.

© Computer Engineering Dept. Page 12


Experiment # 2
Programs using I/O statements, Data types
Aim: Input Output Statements and Data types

Objectives:
1. Familiarize the usage of Input Output Statements.
2. Understand the use of data types.

Points to Remember:
INPUT AND OUTPUT
C provides standard functions scanf() and printf(), for performing formatted input and output.
These functions accept, as parameters, a format specification string and a list of variables.
FormattedOutput: The function printf() is used for formatted output to standard output based on a
format specification. The format specification string, along with the data to be output, are the
parameters to the printf() function.
Syntax: printf (format, data1, data2,……..);
In this syntax format is the format specification string. This string contains, for each variable to be output, a
specification beginning with the symbol % followed by a character called the conversion character.
Example: printf (“%c”, data1);
The conversion character % allows one data type to be converted to another type and printed. It is followed by
the format specifier letter i.e: d  The data is converted to decimal (integer)
c  The data is taken as a character.
s  The data is a string and character from the string , are printed until a NULL, character is reached.
f  The data is output as float or double with a default Precision 6.
Formatted Input: The function scanf() is used for formatted input from standard input and provides
many of the conversion facilities of the function printf().
Syntax: scanf (format, num1, num2,……);
The function scanf() reads and converts characters from the standards input depending on the string format
specification and stores the input in memory locations represented by the other arguments (num1, num2,….).
Example: scanf(“%c %d”,&Name, &Roll No);
Note: the data names are listed as &Name and &Roll No instead of Name and Roll No respectively. This is
how data names are specified in a scnaf() function. In case of string type data names, the data name is not
preceded by the character &.

© Computer Engineering Dept. Page 13


C TOKENS
C tokens are the basic buildings blocks in C language which are constructed together to write a C
program. Each and every smallest individual unit in a C program is known as C tokens. C tokens are
of six types. They are
 Keywords (eg: int, while),
 Identifiers (eg: main, total),
 Constants (eg: 10, 20),
 Strings (eg: “total”, “hello”)
 Special symbols (eg: (), {})
 Operators (eg: +, /, ,*)

VARIABLES
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
 The name of a variable can be composed of letters, digits, and the underscore character.
 It must begin with either a letter or an underscore.
 Upper and lowercase letters are distinct because C is case-sensitive.
 It should not be a keyword and white spaces are not allowed.
Ex: Mohammed x1 T_raise

© Computer Engineering Dept. Page 14


Data Types

Type Size(byte) Description


char 1 Typically a single octet(one byte).This is an integer type
int 2 or 4 The most natural size of integer for the machine.
float 4 A single-precision floating point value.(6digit precision)
double 8 A double-precision floating point value.(14digit precision)
void -na- Represents the absence of type. It doen’t return any value

Program 1: Write a C program to sum and average of Three subject marks.


Display the output with Name and id of the student with total and average marks.
All the inputs should be through the keyboard.
#include<stdio.h>
void main()
{ char name[20];
int id;
float msub1, msub2, msub3, msum, avg;
printf("Enter Name of Student: ");
scanf("%[^\n]", name); /*can use scanf(“%s”,name) but it reads single word only. */
printf ("University Id: ");
scanf("%d", &id);
printf ("Enter Marks of three Subjects[0-100]: \n");
scanf("%f %f %f", &msub1, &msub2, &msub3);
msum=msub1+msub2+msub3;
avg = msum/300*100;
printf("\n Name of Student: %s", name);
printf("\n Univesity Id: %d", id);
printf ("\n Total Marks Secured: %.2f", msum);
printf ("\n Average Marks Secured: %.2f%c", avg,'%');
}

© Computer Engineering Dept. Page 15


Output/Conclusion:
Enter Name of Student: Mohammed Ali
University Id: 412356789
Enter Marks of three Subjects[0-100]:
80
70
60

Name of Student: Mohammed Ali


Univesity Id: 412356789
Total Marks Secured: 210.00
Average Marks Secured: 70.00%

Program 2: Write a C program to convert temperature from Farenheit to Celcius.


[Formula: C = ((F – 32) *5 ) /9 ]. All the inputs should be through the keyboard.
#include <stdio.h>
void main()
{
float celsius, fahrenheit;
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);
celsius =( (fahrenheit - 32) * 5 )/ 9;
printf("%.2f Fahrenheit = %.2f Celsius", fahrenheit, celsius);
}
Output/Conclusion:
Enter temperature in Fahrenheit: 100

100.00 Fahrenheit = 37.78 Celsius

Activity-Program-3: Assume that any month is of 30 days. Now you are given
total days. Find out the exact number of Years, Months & Days. Make a program
in which the total numbers of days are given and you have to convert that in
perfect no of days, year and month.

Activity-Program-4: You are given time in total seconds. Convert it into Hour:
Min: Seconds format. Same as the above program but here instead of days the
seconds are given and you need to convert it into hour, min and seconds format.

© Computer Engineering Dept. Page 16


Experiment # 3
Programs with Operators and Expressions
Aim: Understand of Operators and Expressions

Objectives:
3. Familiarize the usage of Operators.
4. Familiarize the usage of different Expressions.

Points to Remember:
OPERATORS : C language offers many types of operators. They are,
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

S.no Types of Operators Description


These are used to perform mathematical calculations like
1 Arithmetic operators addition, subtraction, multiplication, division and modulus.
+, - , * / %
This is used to assign the values for the variables in C
2 Assignment operator programs. = (Shorthand/Compound assignment operators: +=,
-=, *=, /=, %= )
These operators are used to compare the value of two variables.
3 Relational operators
(<, >, <=, >=, ==, !=)
These operators are used to perform logical operations on the
4 Logical operators
given two variables. (&&, ||, !) i.e Logical AND, OR, NOT
These operators are used to perform bit operations on given two
5 Bitwise operators
variables. &, |, ~, ^, >>, <<
Conditional (ternary) Conditional operators return one value if condition is true and
6
operators returns another value if condition is false. ? :
Increment/decrement These operators are used to either increase or decrease the value
7
operators of the variable by one. ++ and --
& This is used to get the address of the variable,
8 Special operators * This is used as pointer to a variable.
sizeof( ) This gives the size of the variable.

© Computer Engineering Dept. Page 17


Program 1: Write a C program to demonstrate arithmetic modulus and
Conditional Opertors.
#include <stdio.h>
void main()
{ int x=11, y, z=3;
y = ( x==11?2 : 0);
printf("x value is %d\n", x);
printf("y value is %d\n", y);
printf("Modulus is %d\n", (x%z));
}
Output/Conclusion: x value is 11
y value is 2
Modulus is 2

Program 2: Write a C program to demonstrate Relational Operators.


#include <stdio.h>
void main()
{ int x=1, y=2, z=1;
printf("Relation of x>y is %d\n", (x>y));
printf("Relation of y>=x is %d\n", (y>=x));
printf("Relation of y<x is %d\n", (y<x));
printf("Relation of x<=z is %d\n", (x<=z));
printf("Relation of x==y is %d\n", (x==y));
printf("Relation of y!=x is %d\n", (y!=x));
}
Relation of x>y is 0
Output/Conclusion: Relation of y>=x is 1
Relation of y<x is 0
Relation of x<=z is 1
Relation of x==y is 0
Relation of y!=x is 1

EXPRESSIONS: Arithmetic expression in C is a combination of variables, constants and operators


written in a proper syntax. C can easily handle any complex mathematical expressions but these
mathematical expressions have to be written in a proper syntax. Some examples of mathematical
expressions written in proper syntax of C are Note: C does not have any operator for exponentiation.

C OPERATOR PRECEDENCE AND ASSOCIATIVITY


C operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of
equal precedence in an expression are applied.

© Computer Engineering Dept. Page 18


EVALUATION OF EXPRESSION
At first, the expressions within parenthesis are evaluated. If no parenthesis is present, then the
arithmetic expression is evaluated from left to right. There are two priority levels of operators in C.

High priority: * / %

Low priority: + -

The evaluation procedure of an arithmetic expression includes two left to right passes through the
entire expression. In the first pass, the high priority operators are applied as they are encountered and
in the second pass, low priority operations are applied as they are encountered. Suppose, we have an
arithmetic expression as: x = 9 - 12 / 3 + 3 *2 - 1

This expression is evaluated in two left to right passes as:

First Pass
Step 1: x = 9-4 + 3 * 2 - 1

Step 2: x = 9 - 4 + 6 – 1

Second Pass

Step 1: x = 5 + 6 - 1

Step 2: x = 11 - 1

Step 3: x = 10

But when parenthesis is used in the same expression, the order of evaluation gets changed. i.e its high
priority compare to other operators in the above expression.

Program 3: Write a C program to demonstrate Increment or Decrement


Operators.
#include<stdio.h>
void main()
{ int i = 99; 101
101
i++; ++i; 103
printf("%d\n",i); 103
101
printf("%d\n",i++);
printf("%d\n",++i);
printf("%d\n",i--);
printf("%d\n",--i);
}

© Computer Engineering Dept. Page 19


Program 4: Write a C program to demonstrate EXPRESSIONS.
#include<stdio.h>
void main()
{ int a=12,b=8,c=4,d=2,res;
res=a+b/c*d;
printf("Res = %d \n",res);
res=a+b*c-d;
printf("Res = %d \n",res);
res=(a+b)*c-d;
printf("Res = %d \n",res);
res=a+b%(c-d);
printf("Res = %d \n",res);
}
Output/Conclusion:
Res = 16
Res = 42
Res = 78
Res = 12

Activity Program 5: Write a C program to evaluate the arithmetic expression


((a + b / c * d - e) * (f - g)). Read the values a, b, c, d, e, f, g from the standard
input device.

Activity Program 6:. Write a C program to find the sum of individual digits of a 3
digit number. (Hint: 547 = 5+ 4+ 7 i.e sum=16)

Activity Program 7:. Write a C program to read the values of x and y and print
the results of the following expressions in one line:
i. (x + y) / (x - y)
ii. (x + y)(x - y)

© Computer Engineering Dept. Page 20


Experiment # 4
Programs using decision-making constructs if and if-else
Aim: Understanding of different decision making statements

Objectives:
1. Familiarize the usage different if else.

Points to Remember:
The if Statement: A simple condition is expressed in the form
if (condition)
statement;
It starts with the keyword if, followed by a condition (a logical expression) enclosed within
parenthesis, followed by the result statement. The resulting statement is executed if the
condition is evaluated as TRUE. Note that there is no semicolon (;) after the condition
expression. Consider the following example:
if (marks >50)
printf("You have passed the exam!");
If the value of the variable “marks” is greater than 50, the message “You have passed the
exam!” is displayed on the screen; otherwise the statement is skipped and no message is
displayed.
Program 1: Write a program which accepts a number (an amount of money to be
paid by a customer in riyals) entered from the keyboard. If the amount is greater
than or equal to 1000 riyals, a 5% discount is given to the customer. Then display
the final amount that the customer has to pay.
#include <stdio.h>
void main()
{ float amount,final_amount, discount;
printf("Enter amount: ");
scanf("%f", &amount); //get amount
if (amount >= 1000) // if amount >= 1000 give discount
{ discount = amount* 0.05;
final_amount = amount - discount; Enter amount: 1234

printf ("Discount: %.2f", discount); Discount: 61.70


}
Total: 1172.30
printf ("\nTotal: %.2f", final_amount);
}

© Computer Engineering Dept. Page 21


if-else Statement : We can use if-else statement in c programming so that we can check any
condition and depending on the outcome of the condition we can follow appropriate path. We have
true path as well as false path.
Syntax : if(expression)
statement^
else { statement^
statement2;
}
next_statement;
When the condition is evaluated, one of the two statements will be executed and then the program
resumes its original flow. Blocks make it possible to use many statements rather than just one.

Program 2: Write a program which accepts a number (an amount of money to be paid
by a customer in riyals) entered from the keyboard. If the amount is greater than or
equal to 1000 riyals, a 5% discount is given. If the amount is less than 1000 riyals, a 3%
discount is given to the customer. Display the final amount that the customer has to pay.
#include <stdio.h>
void main()
{ float amount,final_amount, discount;
printf("Enter amount: ");
scanf("%f", &amount); //get amount
if (amount >= 1000) // if amount >= 1000 give discount
{ discount = amount*0.05;
final_amount = amount - discount;
printf ("Discount 5 percent: %.2f", discount);
}
else Enter amount: 900
{ discount = amount*0.03;
Discount 3 percent: 27.00
final_amount = amount - discount;
printf ("Discount 3 percent: %.2f", discount); Total: 873.00
}
printf ("\nTotal: %.2f", final_amount);
}

The if-else-if Ladder: In certain cases multiple conditions are to be detected. In such cases the
conditions and their associated statements can be arranged in a construct that takes the form.
if (condition-1)
statement-1; else if (condition-2)
statement-2; else if (condition-3)
statement-3;
… else
statement-n;

© Computer Engineering Dept. Page 22


The above construct is referred as the if-else-if ladder. The different conditions are
evaluated starting from the top of the ladder and whenever a condition is evaluated as
TRUE, the corresponding statement(s) are executed and the rest of the construct it skipped.
Program 3: Write a program to display the student’s grade based on the
following table:
skraM erkrG
>=75 and <=100 A
>=50 and <75 B
>=25 and<50 C
<25 F
#include <stdio.h>
void main()
{ int marks;
printf("Enter marks: ");
scanf("%d", &marks); //read marks
if(marks >= 75 && marks<=100) // if over and equal 75
printf("Your grade is: A");
else if(marks >= 50 && marks <75) // if between 50 & 75
printf("Your grade is: B");
else if(marks >= 25 && marks <50) // if between 25 & 50
printf("Your grade is: C");
else
printf ("Your grade is: F"); // if less than 25
}
Activity Program 4: Write a C Program to accept four numbers and find minimum.

Activity Program 5: Write a C Program to accept a character and check whether the

given character is UpperCase, LowerCase or Not_Alphabet.

Activity Program 6: Write a C Program to swap two numbers without third variable.

Activity Program 7: Write a C Program to insert any number and check whether the

given number is Positive, Negative or ZERO.

Activity Program 8: Write a C Program to insert values of length and breadth.

 If any or both the values are <=0, print the output as “Wrong Input Values”.

 If both the values are equal, find Area(s*s) and Perimeter(4*s) of Square.

 If both the values are different, find Area(l*b) and Perimeter(2*[l+b])of Rectangle.

© Computer Engineering Dept. Page 23


Experiment # 5
Programs using decision-making constructs nested if, switch
Aim: Understanding of different decision making statements

Objectives:
5. Familiarize the usage of Nested if.
6. Familiarize the usage of switch.

Points to Remember:
Nesting Conditions : Sometimes we need to check for multiple decisions. This can be accomplished
by two approaches; using compound relational tests or using nested conditions. When conditions are
nested the if-else/if- else-if construct may contain other if-else/if-else-if constructs within themselves.

Program 1: Write a C program to find maximum of three numbers using nested if-else.
#include <stdio.h>
void main()
{ int a=10, b=20, c=15;
if(a>b)
{ if(a>c)
printf("A is Big %d",a);
else
printf("C is Big %d",c);
}
else
{ if(b>c)
printf("B is Big %d",b);
else
printf("C is Big %d",c);
}
}
Program 2: Write a C program to calculate electricity bill as per the give below.

(User can enter the Consumption Kwh and Mention Consumption Category 1 as Residential, 2 as
Commercial and 3 as Agricultural & Charities.)

© Computer Engineering Dept. Page 24


#include <stdio.h>
void main()
{ int Kwh, n;
printf("Enter Electricity Consumption in Kwh: ");
scanf("%d",&Kwh);
printf("Enter Electricity Consumption Category: \n 1.Residential \n 2.Commercial \n 3.Agricultural \n
Enter choice: ");
scanf("%d",&n);
if(Kwh>6000)
{ if(n==1 || n==2)
printf("Your Bill is %.2f Riyals",(30*Kwh/100.0));
else if(n==3)
printf("Your Bill is %.2f Riyals",(20*Kwh/100.0));
}
else
{ if(n==1)
printf("Your Bill is %.2f Riyals",(18*Kwh/100.0));
if(n==2)
printf("Your Bill is %.2f Riyals",(20*Kwh/100.0));
if(n==3)
printf("Your Bill is %.2f Riyals",(16*Kwh/100.0));
}
}
Switch statement
Why we should use Switch Case?
• One of the classic problem encountered in nested if-else / else-if ladder called problem of Confusion.
• It occurs when no matching else is available for if .
• As the number of alternatives increases the Complexity of program increases drastically.
• To overcome this , C Provide a multi-way decision statement called ‘ Switch Statement‘
See how difficult is this scenario?
if(Condition1)
Statement 1
else
{ Statement 2
if(condition2)
{ if(condition 3)
statement 3
else
if(condition 4)
{ statement 4
}
}
else
{ statement 5
}
}
First Look of Switch Case
switch(expression)
{
case value1 : body1 break;
case value2 : body2 break;
case value3 : body3 break;
default : default-body break;
}

next-statement;

© Computer Engineering Dept. Page 25


Program 3: Write a program to display the following menu on the screen and let
the user select a menu item. Based on the user’s selection display the category of
software that the user selected program belongs to.
Menu
1 – Facebook
2 – Instagram
3 – Snapchat
4 – Twitter
5 - Exit
Enter number of your preference:
#include <stdio.h>
void main()
{ int a;
printf("\t\tMenu"); printf("\n -------------------------- ");
printf("\n1 - Facebook"); printf("\n2 - Instagram");
printf("\n3 - Sanpchat"); printf("\n4 - Twitter");
printf("\n5 - Exit"); printf("\n -------------------------- ");
printf("\nEnter number of your preference: ");
scanf("%d",&a); //read input
switch(a)
{ case 1: printf("\n Welcome to Facebook"); break;
case 2: printf("\n Welcome to Instagram"); break;
case 3: printf("\n Welcome to Sanpchat"); break;
case 4: printf("\n Welcome to Twitter"); break;
case 5: printf("\n Thank You"); break;
default:printf("\n Wrong Input ");
}
}

Activity Program 4: Write a C program to input marks of five subjects Physics,


Chemistry, Biology, Mathematics and Computer. Calculate percentage and grade
according to following: Percentage >= 90% : Grade A
Percentage >= 80% : Grade B
Percentage >= 70% : Grade C
Percentage >= 60% : Grade D
Percentage < 60% : Grade F

Activity Program 5: Write a C Program to print "ONE", "TWO",... , "NINE".


Using switch case print the value of each case from number to CHARACTERS i.e
[1-9]. (Read input from the keyboard in integer and print the word).

© Computer Engineering Dept. Page 26


Experiment # 6
Programs using loops – while, do-while, for
Aim: Understanding of different loops

Objectives:
1. Familiarize the usage of for loop.
2. Familiarize the usage of while loop.
3. Familiarize the usage of do-while loop

Points to Remember:
A Program is usually not limited to a linear sequence of instructions or conditional structures and it is
sometimes required to execute a statement or a block of statements repeatedly. These repetitive
constructs are called loops or control structures. The C language supports three constructs; namely
for, while and do-while loops.
The for loop: The for loop construct is used to repeat a statement or block of statements a
specified number of times. The general form of a for loop is:
for (counter-initialization; condition; increment-decrement)
statement(s);

Program 1: Write a C program to calculate the sum of all the even numbers up to 100.
#include <stdio.h>
void main()
{
int counter, sum = 0;
for(counter=0; counter <= 100; (counter += 2)) //increment by 2
{
sum += counter;
}
printf("Total : %d", sum);
}

The while loop:The while loop construct contains only the condition. The programmer has to take
care about the other elements (initialization and incrementing). The general form of the while loop is:
while (condition)
{ statement(s);
}

© Computer Engineering Dept. Page 27


The do-while loop: Another useful loop is the do-while loop. The only difference between the do-while
loop and other loops is that in the do-while loop the condition comes after the statement(s). It takes the
following form: do
{ statement(s);
}while (condition);

Break and Continue: The break keyword is used to terminate a loop, immediately bypassing any
conditions. The control will be transferred to the first statement following the loop block. If you have nested
loops, then the break statement inside one loop transfers the control to the immediate outer loop. The break
statement can be used to terminate an infinite loop or to force a loop to end before its normal termination.
Consider the following example’s:

Program 2a: Program 2b:


Break Continue
#include<stdio.h> #include<stdio.h>
void main() void main()
{ int i; { int i;
for(i=1;i<=10;i++) for(i=1;i<=10;i++)
{ {
printf("Number: %d\n",i); printf("Number: %d\n",i);
if(i==5) if(i==5)
{ printf("Loop terminated"); { printf("Loop terminated");
break; continue;
} }
} }
} }

Program 3: Write a C program to to print even numbers up to 10 using ‘while’ loop.


#include<stdio.h>
void main()
{ int i=2;
printf("even numbers");
while(i<=10)
{ if(i%2==0)
printf("\n %d",i);
i=i+1;
}
}

© Computer Engineering Dept. Page 28


Program 4: Write a C program to to check whether the given three digit number is an
Armstrong or not. (Read the input from keyboard)
#include<stdio.h>
void main()
{ int a,n,num,sum=0;
printf("Enter a positive three-digit number: ");
scanf("%d",&n);
num=n;
do
{ a=num%10;
sum=sum+(a*a*a);
num=num/10;
}while(num>0);
if(sum==n)
printf("\n Number is an Armstrong: %d ",n);
else
printf("\n Number NOT a Armstrong: %d ",n);
}

Activity Program 5: Write a program to calculate the factorial of any given


positive integer. (Read the input from keyboard)

Activity Program 6: Write a program to compute the sum of all integers between
any given two numbers. (Read the input from keyboard)

Activity Program 7: Write a program to check whether the given number is


Palindrome or not. (Read the input from keyboard)

Activity Program 8: Write the only logic(i.e code) for the following programs:

0 *
1 0
* *
2 1 0
3 2 1 0 * * *
4 3 2 1 0 * * * *
* * * * *

© Computer Engineering Dept. Page 29


Experiment # 7
Programs with Array – One dimensional array
Aim: Understanding of Arrays.

Objectives:
1. Familiarize the usage of one dimensional arrays in C Programming.

Points to Remember:
Arrays are a series of elements of the same data type placed consecutively in memory that can be individually
referenced by adding an index to a unique name. Using an array we can store five values of type int with a
single identifier without having to declare five different variables with a different identifier. Arrays are useful
when you store related data items, such as grades received by the students, sine values of a series of angles, etc.
Like any other variable in C an array must be declared before it is used. The typical declaration of an array is:

data-type array-name[no-of-elements];

Intialization of an Array:
An array will not be initialized when it is declared; therefore its contents are undetermined
until we store some values in it. The following array can hold marks for five subjects.
int marks[5];

The elements of an array can be initialised in two ways. In the first approach, the value of
each element of the array is listed within two curly brackets ({}) and a comma (,) is used to
separate one value from another. For example:
marks[5] = {55, 33, 86, 81, 67};

In the second approach elements of the array can be initialised one at a time. This approach
makes use of the format:
array-name[index];

For example:
marks[0] = 55;

marks[1] = 33;

marks[2] = 86;

marks[3] = 81;

marks[4] = 67;

© Computer Engineering Dept. Page 30


Program 1: Write a C program to create one dimenstion array of 5 integers.
#include <stdio.h>
void main()
{ int i;
int number[5]= {10, 20 , 50, 60, 90};
printf("Array[5]: ");
for (i=0;i<5;i++)
printf(" %d ", number[i]);
}

Output:

Array[5]: 10 20 50 60 90

Program 2: Write a C program to calculate the sum and average of 5 subject


marks of a student using One dimenstional array.
#include <stdio.h>
void main()
{
int i,sum=0;
int marks[5]; //array of 5 elements
float average;
for(i=0;i<5;i++)
{
printf("Enter marks for subject %d: ", i+1);
scanf("%d", &marks[i]); //get the marks
}
for(i=0;i<5;i++) //total marks
{
sum +=marks[i];
}
average = sum/5.0; //5.0 indicates a float value
printf("Average : %.2f", average);
}

© Computer Engineering Dept. Page 31


Output:

Enter marks for subject 1: 80

Enter marks for subject 2: 80

Enter marks for subject 3: 80

Enter marks for subject 4: 60

Enter marks for subject 5: 60

Average : 72.00

Activity Program 3: Write a C program to find the common elements between

two arrays of integers. (Read the input from keyboard)

Activity Program 4: Write a C program to input six numbers in single dimension

array and print out only the odd numbers.

Input: Enter any six numbers: 15 78 45 98 25 11

Output: Odd numbers are: 15 45 25 11

Activity Program 5: Write a C program that asks the user to type any five

numbers and save them in an array. The program finds and prints the average

and the minimum values among elements.

Example : If the inputs are 2, 4, 5, 1, 3. Then, the program will print:

Minimum = 1, Average = 3

© Computer Engineering Dept. Page 32


Experiment # 8
Programs with Array – Multi dimensional array
Aim: Understanding of Arrays.

Objectives:
1. Familiarize the usage of multi dimensional arrays in C Programming.

Points to Remember:
One-dimensional (or single dimensional) array, as it takes one index and store only one type of data.
Multi dimensional array can takes more than one index and strore the data. Two- dimensional array
can be declared in the following form:

data-type array-name[size-1][size-2];

You can declare an array to hold marks of 100 students with store marks of 5 subjects as in the
following example:
int students[100][5];

The first index defines the number of students and the second index defines the number of subjects.
Altogether it declares 500 (1005) memory locations. Initialising marks of the first student can be
performed in the following manner.
marks[0][0] = 55;
marks[0][1] = 33;
marks[0][2] = 86;
marks[0][3] = 81;
marks[0][4] = 67;
Similarly we can define arrays with n dimensions and such arrays are called n-dimensional or
multidimensional arrays. A two-dimensional array is initialised in the same way. The following
statement declares and initialises a two-dimensional array of type int which holds the scores of three
students in five different tests.

int students[3][4]= { {55, 33, 86, 81},


{45, 46, 86, 30},
{39, 82, 59, 57}
};

© Computer Engineering Dept. Page 33


Program 1: Write a C program to store marks of 3 students for 4 subjects given
through the keyboard. Calculate the average of each students marks and the
average of marks taken by all the students.

#include <stdio.h>
void main()
{ int i,j;
int marks[3][4]; //array of 5 elements
int sum[3];
float avg=0, average[3];
for(i=0;i<3;i++)
{ printf("==========Marks of STUDENT_%d========== \n", i+1);
sum[i]=0;
for(j=0;j<4;j++)
{ printf("Enter marks for subject %d: ", j+1);
scanf("%d", &marks[i][j]); //get the marks
sum[i]=sum[i]+marks[i][j]; // sum of marks for each student
}
}
for(i=0;i<3;i++)
{ average[i] = sum[i]/4.0;
printf("\n Average marks of STUDENT_%d : %.2f ", i+1, average[i]);
avg=avg+average[i]; // sum of all average marks for each student
}
printf("\n Average marks taken by all the 3 students== %.2f ", avg/3.0);
}

Output:
==========Marks of STUDENT_1==========
Enter marks for subject 1: 55
Enter marks for subject 2: 33
Enter marks for subject 3: 86
Enter marks for subject 4: 81

© Computer Engineering Dept. Page 34


==========Marks of STUDENT_2==========
Enter marks for subject 1: 45
Enter marks for subject 2: 46
Enter marks for subject 3: 86
Enter marks for subject 4: 30

==========Marks of STUDENT_3==========
Enter marks for subject 1: 39
Enter marks for subject 2: 82
Enter marks for subject 3: 59
Enter marks for subject 4: 57

Average marks of STUDENT_1 : 63.75


Average marks of STUDENT_2 : 51.75
Average marks of STUDENT_3 : 59.25
Average marks taken by all the 3 students== 58.25

Activity Program 2: Write a C program for addition of two 2x2 matrixes.

1 0 2 2 3 2
+ =
0 1 2 2 2 3

Activity Program_3: Write a C program to store nine elements for 3x3 matrixes

and print only diagonal elements.

1 2 3 1

4 5 6 = 5

7 8 9 9

© Computer Engineering Dept. Page 35


Experiment # 9
Programs using functions
Aim: Understanding of functions.

Objectives:
1. Familiarize the usage of functions.
2. Understand Recursive functions with return value.

Points to Remember:
The C functions that you have used so far (such as printf and scanf) are built into the C libraries, but
you can also write your own functions. Therefore functions can be classified as built-in and user
defined. A modular program is usually made up of different functions, each one accomplishing a
specific task such as calculating the square root or the factorial. In general a modular program consists
of the main( ) function followed by set of user defined functions as given below
#include
……
#define …..
Prototypes of functions
int main( )
{ ……….
}
function_1( )
{ ………..
}
function_2( )
{ ………..
}
…………
function_n()
{ ………..
}

The source code contains other elements in addition to the function blocks. It starts with
the #include directive, followed by the #define directive (if any) then followed by the
prototypes of functions. The prototype is a declaration of a function used in the program.
Then comes the program building block which includes the main() function and
implementation of the user defined functions.

© Computer Engineering Dept. Page 36


WHAT IS C FUNCTION?
A large C program is divided into basic building blocks called C function. C function contains set of
instructions enclosed by “{ }” which performs specific operation in a C program. Actually,
Collection of these functions creates a C program.

USES OF C FUNCTIONS:
 C functions are used to avoid rewriting same logic/code again and again in a program.
 There is no limit in calling C functions to make use of same functionality wherever required.
 We can call functions any number of times in a program and from any place in a program.
 A large C program can easily be tracked when it is divided into functions.
 The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve
the functionality and to improve understandability of very large C programs.

C FUNCTION DECLARATION, FUNCTION CALL AND FUNCTION DEFINITION:


There are 3 aspects in each C function. They are,
 Function declaration or prototype – This informs compiler about the function name, function
parameters and return value’s data type.
 Function call – This calls the actual function
 Function definition – This contains all the statements to be executed.

HOW TO CALL C FUNCTIONS IN A PROGRAM?


1) Call by value 2) Call by reference

CALL BY VALUE:
 In call by value method, the value of the variable is passed to the function as parameter.
 The value of the actual parameter can not be modified by formal parameter.
 Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.

© Computer Engineering Dept. Page 37


Program 1: Write a C program to find the factorial of given number.
#include<stdio.h>
void main()
{ int n,f=1;
int fact(int);
printf("Enter a no.");
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
}
int f=1;
int fact(int n)
{ int i;
for(i=n;i>=1;i--)
{ f=f*i;
}
return(f);
}

Program 2: Write a C program to find the factorial of given number by using


Recursive Function with return value.
#include <stdio.h>
int func(int num)
{ int res = 0;
if(num<= 0)
{ printf("\n Error \n");
}
else if(num == 1)
{ return num;
}
else
{ res =num * func(num -1);
return res;
}
return -1;
}
int main(void)
{ int num = 5 ;
int fact = func(num);
if (fact > 0)
printf("\n The factorial of [%d] is [%d]\n", num, fact);
return 0;

© Computer Engineering Dept. Page 38


}

Program 3: Write a C program to calculate the circumference and area of a


circle given its radius. Implement calculation of circumference and areas as
separate functions.
#include<stdio.h>
const float pi = 3.141;
float area(float r); //function prototype
float circumference(float r); //function prototype
void main()
{ float radius;
printf("Enter radius: ");
scanf("%f",&radius); //read radius
printf("\nArea : %.2f", area(radius));
printf("\nCircumference : %.2f", circumference(radius));
}
/* Function computes the area of a circle given its radius*/
float area(float r)
{ return (pi*r*r);
}
/* Function computes the circumference of a circle given radius*/
float circumference(float r)
{ return (2*pi*r);
}

Output:
Enter radius: 10

Area : 314.10
Circumference : 62.82

Activity Program 4: Write a C Program to swap two numbers using functions and
without using temporary variable.

Activity Program 5: Write a C Program to print Fibonacci series with limit upto
10 numbers using Recursive function. (Fibonacci series: 0,1,1,2,3,5,8,13….etc.)

© Computer Engineering Dept. Page 39


Experiment # 10
Programs using String functions
Aim: Understanding of String functions.

Objectives:
1. Familiarize the usage of String functions.
2. Understand character array’s.

Points to Remember:
Strings are defined as an array of characters. The difference between a character array and a string is
the string is terminated with a special character ‘\0’. We can perform String operations using the pre-
defined Standard Library functions of “string.h” header file.

What is NULL Char ‘\0’: ‘\0’ represents the end of the string. It is also referred as String
terminator & Null Character.

Program 1: Write a C program using two string functions gets() and puts() to
take string input from the user and display it respectively
#include<stdio.h>
void main()
{ char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user like scanf("%s",&name);
printf("Name: ");
puts(name); //Function to display string like printf("%s",name); but limited to word
}

© Computer Engineering Dept. Page 40


String library function: There are several string library functions used to manipulate string
and the prototypes for these functions are in header file “string.h”. Several string functions are
strlen(): This function return the length of the string. i.e. the number of characters in the string
excluding the terminating NULL character. For example strlen(“abdullah”); // return value 8.
In array version to calculate length:
int strlen(char str[])
{ int i=0;
while(str[i]!=’\o’)
i++;
return i;
}
Program 2: Write a C program that will calculate the length of the string and
display it as output.
#include<stdio.h>
#include<string.h>
void main()
{ char str[50];
printf("Enter a string: ");
gets(str);
printf("Length of the string is %ld\n",strlen(str));
}

strcat: The strcat() function will append a copy of the source string to the end of destination string.
The strcat() function takes two arguments: 1) dest 2) src
It will append copy of the source string in the destination string. The terminating character at the end
of dest is replaced by the first character of src. Return value: The strcat() function returns dest.
Program 3: Write a C program that will concatenate one string to the end of
another string and display it as output.
#include<string.h>
#include<stdio.h>
void main()
{ char dest[50] = "This is an";
char src[50] = " example";
strcat(dest, src);
puts(dest);
}

© Computer Engineering Dept. Page 41


Program 4: Write a C program to concatenate two strings without using library
functions and display it as output.
#include<stdio.h>
void main(void)
{ char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{ str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}

Activity Program 4: Write a C Program that will read two strings. If given two
strings are same then print “Given strings are same”. If given two strings are not
same then print “Given strings are not same”.

© Computer Engineering Dept. Page 42


Experiment # 11
Programs using Pointers
Aim: Demonstration of pointers in C programming.

Objectives:
3. Familiarize with pointers.

Points to Remember:

Pointer in C language is a variable that stores/points the address of another variable. A Pointer in C is
used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of
the data type such as int, float, char, double, short etc.
 Pointer Syntax : data_type *var_name; Example : int *p; char *p;
 Where, * is used to denote that “p” is pointer variable and not a normal variable.

KEY POINTS TO REMEMBER ABOUT POINTERS IN C:


 Normal variable stores the value whereas pointer variable stores the address of the variable.
 The content of the C pointer always be a whole number i.e. address.
 Always C pointer is initialized to null, i.e. int *p = null.
 The value of null pointer is 0.
 & symbol is used to get the address of the variable.
 * symbol is used to get the value of the variable that the pointer is pointing to.
 If a pointer in C is assigned to NULL, it means it is pointing to nothing.
 Two pointers can be subtracted to know how many elements are available between these two pointers.
 But, Pointer addition, multiplication, division are not allowed.
 The size of any pointer is 2 byte (for 16 bit compiler).

Declaring Pointers
A pointer is declared using the indirection (*) operator. The typical declaration of a pointer is:
data-type *pointer-name;
If a pointer “a” is pointing to an integer, it is declared as:
int *a;
Since a pointer is a variable, its value is also stored in another memory location. Therefore in
computation even the address of the pointer can be used. The location of a variable in memory is
system dependent and therefore the address of a variable is not known directly. The address
operator (&) allow us to retrieve the address from a variable associated with it.

© Computer Engineering Dept. Page 43


Program 1: Write a C program to demonstrate pointer with an address of the
variable.

#include <stdio.h>
void main()
{ int number = 20; int *pnt;
pnt = &number;
printf("\nThe number is: %d", number);
printf("\nThe address of the number is: %d", &number);
printf("\nThe pointer is: %d", pnt);
printf("\nThe address of the pointer is: %d", &pnt);
printf("\nThe value of the pointer is: %d", *pnt);
}
The number is: 20

The address of the number is: 703981396

The pointer is: 703981396

The address of the pointer is: 703981400

The value of the pointer is: 20

Text Strings and Pointers: A character pointer is used to point to the first character of a string
as given in the following example:
char *a;
a = "Hello World!";

Program 2: Write a C program to demonstrate Text String.


#include <stdio.h>
void main()
{ char *a;
a = "Hello World";
printf("String: %s\n", a);
printf("First character: %c\n", *a);
printf("Starting memory address: %d\n", a);
printf("First character: %d\n", *a);
}

String: Hello World

First character: H

Starting memory address: 4195892

First character: 72

© Computer Engineering Dept. Page 44


Pointers in Detail: Pointers have many but easy concepts and they are very important to C
programming. The following important pointer concepts should be clear to any C programmer −

Sr.No. Concept & Description

1 Pointer arithmetic
There are four arithmetic operators that can be used in pointers: ++, --, +, -

2 Array of pointers
You can define arrays to hold a number of pointers.

3 Pointer to pointer
C allows you to have pointer on a pointer and so on.

4 Passing pointers to functions in C


Passing an argument by reference or by address enable the passed argument to be
changed in the calling function by the called function.

5 Return pointer from functions in C


C allows a function to return a pointer to the local variable, static variable, and
dynamically allocated memory as well.

CALL BY REFERENCE:
 In call by reference method, the address of the variable is passed to the function as parameter.
 The value of the actual parameter can be modified by formal parameter.
 Same memory is used for both actual and formal parameters since only address is used by both
parameters.

Program 3: Write a C program to swap two integer numbers using pointers.


#include<stdio.h>
void swap(int *a, int *b); // function prototype, also called function declaration
int main()
{ int m = 22, n = 44; // calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
void swap(int *a, int *b)
{ int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}

© Computer Engineering Dept. Page 45


values before swap m = 22

and n = 44

values after swap a = 44

and b = 22

EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):


 In this program, the address of the variables “m” and “n” are passed to the function “swap”.
 These values are not copied to formal parameters “a” and “b” in swap function.
 Because, they are just holding the address of those variables.
 This address is used to access and change the values of the variables.

Program 4: Write a C program to print the elements of array using pointers*.


#include <stdio.h>
void main()
{ int a[5]={5,4,6,8,9};
int *p=&a[0];
int i;
for(i=0;i<5;i++)
printf("%d ",*(p+i));
}

5 4 6 8 9

Activity Program 5: Write a C Program to find the maximum number in array


using pointer.

Activity Program 6: Write a C program to find the length of string using pointers.

© Computer Engineering Dept. Page 46


Experiment # 12
Structures and Unions
Aim: Demonstration of Structures and Unions in C programming.

Objectives:
1. Familiarize with Structures.
2. Familiarize with Unions.

Points to Remember:
Structure: As we know that Array is collection of the elements of same type , but many time we have
to store the elements of the different data types. Suppose Student record is to be stored, then for
storing the record we have to group together all the information such as Roll, name, Percent which
may be of different data types. Ideally Structure is collection of different variables under single name.
Basically Structure is for storing the complicated data. A structure is a convenient way of grouping
several pieces of related information together.

Definition of Structure in C: Structure is composition of the different variables of different data types,
grouped under same name.

typedef struct
{ char name[64];
char course[128];
int age;
int year;
} student;

Each member declared in Structure is called member. Name given to structure is called as tag.
Structure member may be of different data type including user defined data-type also. Declaration of
Structure reserves no space. Struct keyword is used to declare structure.

Program 1: Write a C Program to demonstrate struct student with id, name and percentage
of marks.
#include <stdio.h>

© Computer Engineering Dept. Page 47


#include <string.h>
struct student
{ int id;
char name[20];
float percentage;
};
int main()
{ struct student record = {0};
record.id=1;
strcpy(record.name, "Ali");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %.2f \n", record.percentage);
return 0;
}

Output/Conclusion:

Id is: 1
Name is: Ali
Percentage is: 86.50

REFERENCES
1. E. Balagurusamy, “Computing fundamentals and C Programming”, 2nd edition, McGraw-
Hill, India, 2017. ISBN-13: 978-9352604166

© Computer Engineering Dept. Page 48


2. Yashavant P. Kanetkar. “ Let Us C”, BPB Publications, 2011.
3. Kernighan, B.W and Ritchie, D.M, “The C Programming language”, Second Edition, Pearson
Education, 2006. ISBN-13: 978-0131103627
4. Byron S Gottfried, “Programming with C”, Schaum’s Outlines, Second Edition, Tata
McGraw-Hill, 2006. ISBN-13: 978-0070240353
5. Dromey R.G., “How to Solve it by Computer”, Pearson Education, Fourth Reprint, 2007.

© Computer Engineering Dept. Page 49

You might also like