lab manual - simplycs.inwrite a program to perform file operations: a. opening a file b. reading the...

87
i Department of Information Technology Lab Manual First Year- Semester II Department of Engineering Sciences Subject: Structured Programming Approach Even Semester

Upload: others

Post on 25-Apr-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

i

Department of Information Technology

Lab Manual First Year- Semester II

Department of Engineering Sciences Subject: Structured Programming Approach

Even Semester

Page 2: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

ii | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Institute Vision, Mission & Quality Policy

Vision To foster and permeate higher and quality education with value added engineering, technology programs, providing all facilities in terms of technology and platforms for all round development with societal awareness and nurture the youth with international competencies and exemplary level of employability even under highly competitive environment so that they are innovative adaptable and capable of handling problems faced by our country and world at large.

Mission The Institution is committed to mobilize the resources and equip itself with men and materials of excellence thereby ensuring that the Institution becomes pivotal center of service to Industry, academia, and society with the latest technology. RAIT engages different platforms such as technology enhancing Student Technical Societies, Cultural platforms, Sports excellence centers, Entrepreneurial Development Center and Societal Interaction Cell. To develop the college to become an autonomous Institution & deemed university at the earliest with facilities for advanced research and development programs on par with international standards. To invite international and reputed national Institutions and Universities to collaborate with our institution on the issues of common interest of teaching and learning sophistication.

Quality Policy

Our Quality Policy

It is our earnest endeavour to produce high quality engineering professionals who are innovative and inspiring, thought and action leaders, competent to solve problems faced by society, nation and world at large by striving towards very high standards in learning, teaching and training methodologies.

Our Motto: If it is not of quality, it is NOT RAIT!

Dr. Vijay D. Patil President, RAES

Page 3: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

iii | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Departmental Vision, Mission

Vision

Addressing the basic technical skills of students and make them understand the

basics of engineering.

Training the students in leadership capabilities which will prepare them for future

significant roles at the organizational level.

Developing their emotional and spiritual quotient through Stress Management

seminars and workshops.

Strengthening the foundation of students, by providing exposure to diverse technical

fields. Including practical learning through innovative teaching and learning

techniques, inculcating ethical values and preparing them to face the challenges of

the future.

Mission To impart quality education pertaining to First year Engineering.

To prepare the students for leadership roles and strengthen the basic concepts which will

make them understand the engineering concepts better at higher semesters.

To develop the overall character and personality through spiritual workshops so that they

not only emerge as excellent engineers but also ethical human beings.

Page 4: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

4 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Index Sr. No. Contents Page No.

1. Course Objective, Outcomes and Program Outcomes 4

2. List of Experiments 6

3. Experiment Plan 8

4. Study and Evaluation Scheme 9

5. Experiment No. 1 10

6. Experiment No. 2 15

7. Experiment No. 3 19

8. Experiment No. 4 22

9. Experiment No. 5 26

10. Experiment No. 6 30

11. Experiment No. 7 35

12. Experiment No. 8 38

13. Experiment No. 9 41

14. Experiment No. 10 44

15. Experiment No. 11 48

16. Experiment No. 12 51

17. Experiment No. 13 56

18. Experiment No. 14 59

19. Experiment No. 15 62

20. Experiment No. 16 65

21. Experiment No. 17 69

22. Experiment No. 18 73

23. Experiment No. 19 77

24. Experiment No. 20 81

Page 5: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

5 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Course Objectives

Course Objectives

1 To familiarise the logic of structured programming approach. 2 To provide exposure in developing algorithm, flowchart and thereby writing

efficient codes for user defined problem.

Course Outcomes & Program Outcomes

Course Outcomes

CO1 Illustrate the basic terminology used in computer programming.

CO2 Illustrate the concept of data types, variables and operators using C.

CO3 Design and Implement control statements and looping constructs in C.

CO4 Apply function concept on problem statements.

CO5 Demonstrate the use of arrays, strings, structures and files handling in C.

CO6 Demonstrate the dynamics of memory by the use of pointers to construct various

data structures.

Page 6: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

6 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Program Outcomes

PO1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering Fundamentals, and an engineering specialization to the solution of complex engineering problems.

PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences.

PO3 Design/development of solutions: Design solutions for complex engineering problems and design system components or processes that meet the specified needs with appropriate Consideration for the public health and safety, and the cultural, societal, and environmental considerations.

PO4 Conduct investigations of complex problems: Use research-based knowledge and research methods including design of experiments, analysis and interpretation of data, and synthesis of the information to provide valid conclusions.

PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools including prediction and modeling to complex engineering activities with an understanding of the limitations

PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice.

PO7 Environment and sustainability: Understand the impact of the professional engineering solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development.

PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering practice.

PO9 Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and in multidisciplinary settings.

PO10 Communication: Communicate effectively on complex engineering activities with the engineering community and with society at large, such as, being able to comprehend and write effective reports and design documentation, make effective presentations, and give and receive clear instructions.

PO11 Project management and finance: Demonstrate knowledge and understanding of the engineering and management principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in multidisciplinary environments.

PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent and life-long learning in the broadest context of technological change.

Page 7: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

7 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

List of Experiments

Subject: Structured Programming Approach Term: Jan 2018-May 2018

Year & Semester :FE(All Branches)

Subject Incharge-: Dr. Pallavi Vijay Chavan

Lab Session: 2hr/week

No. of Lectures per week: 5

No. of Weeks: 15

Sr. No. Title

1 To study Operating System components and its type.

2

Write a C program for following arithmetic operations. Input any two numbers from keyboard.

a. Addition

b. Subtraction

c. Multiplication

d. Division

3 WAP to find out given no is Armstrong or not.

4 WAP to display class of students according to range given (use if else ladder).

5 WAP to find how many days are there in month considering leap year.

6 WAP to display pyramid and Pascal triangle.

7 Write a C program to generate Fibonacci series for n number of terms using do-while loop.

8 Calculate the sum of the series: 1/1!+2/2!+....up to nth term using while loop.

9 WAP to find out the factorial of number using recursive method.

10 WAP to implement Binary search using function.

11 a. Write a function to swap two integers using call by value.

b. Write a function to swap two integers using call by reference.

12

Write a menu driven program to perform following operations:

a. Perform addition of two 3X3 matrices.

b. Obtain transpose of a given 3X3 matrix.

c. Multiplication of two 3X3 matrices.

Page 8: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

8 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

13 WAP to check whether given string is palindrome or not.

14 WAP to implement bubble sort.

15 WAP to perform different string operations.

16 Write a program using structure to calculate areas of various rooms like hall, kitchen and

bedroom. Declare a structure for room details like length and breadth.

17

Write a program to perform file operations:

a. Opening a file

b. Reading the contents of file.

c. Appending the contents to the file.

18 WAP to perform arithmetic operations using pointers.

19 WAP to demonstrate usage of Dynamic Memory allocation using standard C library functions.

20 Write a program to display contents of array using pointers.

Page 9: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

9 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment Plan

Module No.

Week No.

Experiments Name Course

Outcome

1 W1 To study Operating System components and its type. CO1

2 W2

Write a C program for following arithmetic operations. Input any two numbers from keyboard.

a. Addition b. Subtraction c. Multiplication d. Division

CO2

3 W3 WAP to find out given no is Armstrong or not. CO3

3 W3 WAP to display class of students according to range given (use if else ladder).

CO3

3 W4 WAP to find how many days are there in month considering leap year. CO3 3 W4 WAP to display pyramid and Pascal triangle. CO3

3 W5 Write a C program to generate Fibonacci series for n number of terms using do-while loop.

CO3

3 W5 Calculate the sum of the series: 1/1!+2/2!+....up to nth term using while loop.

CO3

4 W6 WAP to find out the factorial of number using recursive method. CO4

4 W7 WAP to implement Binary search using function. CO4

4 W8 a. Write a function to swap two integers using call by value. b. Write a function to swap two integers using call by reference.

CO4

5

Write a menu driven program to perform following operations: d. Perform addition of two 3X3 matrices. e. Obtain transpose of a given 3X3 matrix. f. Multiplication of two 3X3 matrices.

CO5

5 W9 WAP to check whether given string is palindrome or not. CO5

5 W9 WAP to implement bubble sort.

CO5

5 W10 WAP to perform different string operations. CO5

5 W11 Write a program using structure to calculate areas of various rooms like hall, kitchen and bedroom. Declare a structure for room details like length and breadth.

CO5

6 W12

Write a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file.

CO5

6 W13 WAP to perform arithmetic operations using pointers. CO6

6 W14 WAP to demonstrate usage of Dynamic Memory allocation using standard C library functions.

CO6

6 W15 Write a program to display contents of array using pointers. CO6

Page 10: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

10 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Study and Evaluation Scheme

Course

Code Course Name Teaching Scheme Credits Assigned

FEC205 Structured Programming Approach

Theory Practical Tutorial Theory Practical Tutorial Total

04 02 -- 04 01 -- 05

Course Code

Course Name

Examination Scheme

Theory Marks Term Work

Practical and Oral

Total

Internal assessment End Sem. Exam

Test1 Test2 Ave. of Test

1 and Test 2

FEC205 Structured Programming Approach

20 20 20 80 25 25 150

Term Work:

1. Term work assessment must be based on the overall performance of the student

with every experiment graded from time to time. The grades should be converted

into marks as per the Credit and Grading System manual and should be added and

averaged.

2. The final certification and acceptance of term work ensures satisfactory

performance of laboratory work and minimum passing marks in term work.

Practical & Oral:

Oral exam will be based on the entire syllabus of Advanced Database Management Systems.

Page 11: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

11 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:1

To study Operating System components

and its type.

Page 12: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

12 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 1

Aim: To study Operating System components and its type.

Objective:To familiarise operating system and their components with its type.

Outcome: Students will be able to understand the operating system concept. Students will

be able to learn various operating system types and the key components of OS

Theory:

An Operating System acts as an intermediary between a user of a computer and the

computer hardware.

Operating system goals:

Execute user programs and make solving user problems easier

Make the computer system convenient to use

Use the computer hardware in an efficient manner

Operating system components:- The operating system comprises a set of software

packages that can be used to manage interactions with the hardware. The following

elements are generally included in this set of software:

The kernel, which represents the operating system's basic functions such as

management of memory, processes, files, main inputs/outputs and communication

functionalities.

The shell, allowing communication with the operating system via a control

language, letting the user control the peripherals without knowing the

characteristics of the hardware used, management of physical addresses, etc.

The file system, allowing files to be recorded in a tree structure.

Page 13: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

13 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Types of Operating Systems

Following are some of the most widely used types of Operating system.

1. Simple Batch System

2. Multiprogramming Batch System

3. Multiprocessor System

4. Distributed Operating System

5. Real time Operating System

1. SIMPLE BATCH SYSTEMS

In this type of system, there is no direct interaction between user and the computer.

The user has to submit a job (written on cards or tape) to a computer operator.

Then computer operator places a batch of several jobs on an input device.

Jobs are batched together by type of languages and requirement.

Then a special program, the monitor, manages the execution of each program in the

batch.

The monitor is always in the main memory and available for execution.

Following are some disadvantages of this type of system:

Zero interaction between user and computer.

No mechanism to prioritize processes.

2. MULTIPROGRAMMING BATCH SYSTEMS

In this the operating system, picks and begins to execute one job from memory.

Once this job needs an I/O operation operating system switches to another job

(CPU and OS always busy).

Jobs in the memory are always less than the number of jobs on disk (Job Pool).

Page 14: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

14 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

If several jobs are ready to run at the same time, then system chooses which one to

run (CPU Scheduling).

In Non-multiprogrammed system, there are moments when CPU sits idle and does

not do any work.

In Multiprogramming system, CPU will never be idle and keeps on processing.

Time-Sharing Systems are very similar to Multiprogramming batch systems. In fact time

sharing systems are an extension of multiprogramming systems. In time sharing systems

the prime focus is on minimizing the response time, while in multiprogramming the prime

focus is to maximize the CPU usage.

3. MULTIPROCESSOR SYSTEMS

A multiprocessor system consists of several processors that share a common physical

memory. Multiprocessor system provides higher computing power and speed. In

multiprocessor system all processors operate under single operating system. Multiplicity of

the processors and how they do act together are transparent to the others.

Following are some advantages of this type of system.

Enhanced performance

Execution of several tasks by different processors concurrently, increases the

system's throughput without speeding up the execution of a single task.

If possible, system divides task into many subtasks and then these subtasks can be

executed in parallel in different processors. Thereby speeding up the execution of

single tasks.

4. DISTRIBUTED OPERATING SYSTEMS

The motivation behind developing distributed operating systems is the availability of

powerful and inexpensive microprocessors and advances in communication technology.

Page 15: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

15 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

These advancements in technology have made it possible to design and develop distributed

systems comprising of many computers that are inter connected by communication

networks. The main benefit of distributed systems is its low price/performance ratio.

Following are some advantages of this type of system.

As there are multiple systems involved, user at one site can utilize the resources of

systems at other sites for resource-intensive tasks.

Fast processing.

Fewer loads on the Host Machine.

5. REAL-TIME OPERATING SYSTEM

It is defined as an operating system known to give maximum time for each of the critical

operations that it performs, like OS calls and interrupt handling.

The Real-Time Operating system which guarantees the maximum time for critical

operations and complete them on time are referred to as Hard Real-Time Operating

Systems.

While the real-time operating systems that can only guarantee a maximum of the time, i.e.

the critical task will get priority over other tasks, but no assurity of completing it in a

defined time. These systems are referred to as Soft Real-Time Operating Systems.

Conclusion:

Thus we have studied Operating system and its components.

Page 16: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

16 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Page 17: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

17 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:2

WAP and an algorithm to perform

different arithmetic operations on

numbers.

Page 18: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

18 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 2

Aim: WAP and an algorithm to perform different arithmetic operations on numbers.

Objective: To provide exposure in basic of ‘C’ language.

Outcome: Students will be able to learn basic terminology in ‘C’, with this student will be

able to perform program related to multiple operators. Here student will perform program

of different arithmetic operators.

Theory:

The basic operators for performing arithmetic operations are the same in many

computer languages. The arithmetic operators used for arithmetic operations are as

follows:-

Operator Operation

+

Addition

-

Subtraction

*

Multiplication

/

Division

% modulus (remainder)

‘+’ operator: - This operator is used to add two numbers as a+b

‘-‘operator: - This operator is used to subtract two numbers (as in a – b)

‘/’ operator: - When applied to integers, the division operator ‘ /’ discards any remainder,

so 1 / 2 is 0 and 7 / 4 is 1.But when either operand is a floating-point quantity (type float or

double), the division operator yields a floating-point result, with a potentially non-zero

Page 19: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

19 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

fractional part. So 1 / 2.0 is 0.5, and 7.0 /4.0 is 1.75.

‘%’ operator:-The modulus operator % gives the remainder when two integers are

divided: 1 % 2 is 1; 7 %4 is 3. (The modulus operator can only be applied to integers.)

Exponentiation is an additional arithmetic operation which is used in some languages other

than C because C doesn’t have an exponentiation operator (typically ^ or **). (To square or

cube a number, just multiply it by itself in C)

Precedence: - The term ``precedence'' refers to how ``tightly'' operators bind to their

operands (that is, to the things they operate on). Multiplication, division, and modulus all

have higher precedence than addition and subtraction. In mathematics, multiplication has

higher precedence than addition, so 1 +2 * 3 is 7, not 9. In other words, 1 + 2 * 3 is

equivalent to 1 + (2 * 3). C is the same way.

Associativity:-All of these operators ``group'' from left to right, which means that when

two or more of them have the same precedence and participate next to each other in an

expression, the evaluation conceptually proceeds from left to right. For example, 1 - 2 - 3 is

equivalent to (1 - 2) - 3 and gives -4, not +2. (``Grouping'' is sometimes called

associativity, although the term is used somewhat differently in programming than it is in

mathematics. Not all C operators group from left to right; a few groups from right to

left.).Whenever the default precedence or associativity doesn't give you the grouping you

want, you can always use explicit parentheses. For example, if you wanted to add 1 to 2

and then multiply the result by 3, you could write (1 + 2) * 3.

Algorithm:

1. Start

2. Declare the variables of required type

3. Accept two numbers say ‘a’ and ‘b’ from user

4. Perform Addition operation using ‘+‘ operator i.e. a + b and store it in to

temporary variable

5. Perform Subtraction operation using ‘-‘ operator i.e. a - b and store it in to

temporary variable

6. Perform Multiplication operation using ‘*‘ operator i.e. a * b and store it in to

temporary variable

7. Perform Division operation using ‘/‘ operator i.e. a / b and store it in to temporary

Variable

Page 20: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

20 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

8. Perform Modulus operation using ‘%‘ operator i.e. a % b and store it in to

temporary variable

9. Stop

Conclusion:

In this program, we have performed different mathematical operations using

different arithmetic operators.

Page 21: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

21 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:3

Write a program to check whether the

entered number is Armstrong or not

Page 22: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

22 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 3

Aim: Write a program to check whether the entered number is Armstrong or not.

Objective: To familiarise basics of ‘C’ and their basic components.

Outcome: Students will be able to illustrate data types, variables in ‘C’. Students will be

able to learn how to get numbers and checking number is Armstrong or not.

Theory:

Those numbers for which the sum of cube of its digits is equal to that number are

known as Armstrong numbers. For example 153 since 1^3 + 5^3 + 3^3 = 1+ 125 + 9 =153

General definition:

The number for which the sum of its digits to power of number of its digits is equal to that

number is known as Armstrong number.

Example 1: 153

Total digits in 153 is 3

And 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Example 2: 1634

Total digits in 1634 is 4

And 1^4 + 6^4 + 3^4 +4^4 = 1 + 1296 + 81 + 64 =1634

Examples of Armstrong numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208,

9474, 54748, 92727, 93084, 548834, 1741725

Algorithm:

1. Start

2. Declare the required variables

3. Accept the number to be checked from the user

4. Create a copy of the entered number and initialize a variable sum to zero.

5. Check if the user entered number is greater than zero if yes than goto step 6.

Page 23: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

23 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

6. Separate a digit from the entered number by using the modulus operator and add the

cube of this digit to the sum variable.

7. Separate the digit from user entered number by using divide operator.

8. Go to step 5.

9. If user entered number i.e. the copy variable is equal to sum calculated then display

message as the entered number is Armstrong number else display that entered

number is not Armstrong number.

10. .Stop

Conclusion:

We have successfully written the program to check whether a number is

Armstrong number or not by using the given algorithm.

Page 24: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

24 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:4

WAP to display grade of students

according to range given

Page 25: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

25 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 4

Aim: WAP to display grade of students according to range given (use if else ladder).

Objective: To provide exposure in if else statements.

Outcome: Students will be able to demonstrate if-else ladder. Students will learn

variations of if-else ladder and their related programs. So students will be able to learn how

to compare data and calculated grades.

Theory:

The if-else ladder is used when there are multiple conditional statements that may

all evaluate to true, yet you want only one if statement's body to execute. You can use an

"else if" statement following an if statement and its body; that way, if the first statement is

true, the "else if" will be ignored, but if the if statement is false, it will then check the

condition for the else if statement. If the if statement was true the else statement will not be

checked. It is possible to use numerous else if statements to ensure that only one block of

code is executed.

Syntax:

if (condition)

{

statements;

}

else if (condition)

{

statements;

}

else if (condition)

{

statements;

Page 26: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

26 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

}

:

:

:

else

{

statements;

}

The grade of the student is calculated from the percentage obtained. The percentage is

calculated from the total maximum marks and the mark obtained by the student. The

equation for calculating percentage is as follows:-

Percentage = (total maximum marks/ total obtained marks) * 100

From the percentage obtained the grade of the student is calculated. The grade of the

student is displayed with the help of the ranges given in the table below:

Grade A+

per>75

Grade A

75>per>=60

Grade B

60>per>=50

Grade C

50>per>=40

Fail

40>per

Algorithm:

1. Start.

2. Declare variable for percentage, total maximum marks and total obtained marks.

3. Accept the total maximum marks and the total marks obtained by the student

4. Calculate the percentage from the formula given above.

5. Check if percentage is greater than 75 display grade as A+

Page 27: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

27 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

6. else if percentage is less than 75 and greater than equal to 60 display grade as A

7. else if percentage is less than 60 and greater than equal to 50 display grade as B

8. else if percentage is less than 50 and greater than equal to 40 display grade as C

9. else display result as FAIL

10. Stop

Conclusion:

After implementing the above algorithm we understood the working of if-else

ladder in selecting a particular choice among multiple choices.

Page 28: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

28 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:5

WAP to find how many days are there

in month considering leap year

Page 29: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

29 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 5

Aim: WAP to find how many days are there in month considering leap year.

Objective: To familiarise switch case with its variations.

Outcome: Students will be able to design and implement switch case. Students will design

many possible ways of switch cases and learn what are cases, break and default case.

Theory:

The control statement that allows us to make a decision from the number of choices

is called a switch statement, or more correctly a switch-case-default, since these three

keywords go together to make up the control statement. The syntax for switch statement is

as follows:

switch (expression)

{

case constant1: statement;

break;

case constant2: statement;

break;

.

.

case constantn: statement;

break;

default: statement;

}

The integer expression following the keyword switch is any expression that will yield an

integer value. It could be an integer constant like 1, 2 or 3, or an expression that evaluates

to an integer. The keyword case is followed by an integer or a character constant. Each

constant in each case must be different from all the others. The statement lines in the above

form of switch represent any valid C statement. When we run a program containing a

Page 30: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

30 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

switch First, the integer expression following the control to the statement following the

keyword switch is evaluated. The value it gives is then matched, one by one, against the

constant values that follow the case statements. When a match is found, the program

executes the statements following that case up to the break statement. Break transfers

control to the statement following the switch case.

The switch statement is very useful in writing menu driven program.

Consider the following program:

#include<stdio.h>

void main ()

{

int i = 1;

switch (i )

{

case 1: printf (“I am in case 1 \n") ;

break;

case 2: printf (“I am in case 2 \n") ;

break;

case 3: printf (“I am in case 3 \n") ;

break;

default: printf (“I am in default case \n") ;

}}

Output: I am in case 1

A year is leap if the year on dividing by 4 leaves remainder as 0 but not by 100 or is

divisible by 400. Thus, 1996, 2000 and 2004 are leap years but 1900, 2002 and 2100 are

not.

Algorithm:

1. Start.

2. Declare the variable for month number

3. Accept month number from user.

4. By using switch statement, select the no. of days according to month number

4.1 If month number (1 ||3||5||7||8||10||12), then Output=31. Display Output.

Page 31: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

31 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

4.2 If month number (4 ||6||5||9||11), then Output=30. Display Output.

4.3 If month number (2), then

4.3.1 Accept the year number

4.3.2 Check whether the entered year is leap year or not

4.3.3 If leap year, then Output=29

4.3.4 Else, output=28

5. Stop

Conclusion:

Thus we have studied case control statement i.e. switch statement. We use switch-

case statement when we design any menu driven program. So using switch statement a

menu driven program to find the number of days of a month has been implemented.

Page 32: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

32 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:6

WAP to display pyramid and Pascal

triangle.

Page 33: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

33 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 6

Aim: WAP to display pyramid and Pascal triangle.

Objective: To familiarise loops of ‘C’ language like for loop.

Outcome: Students will be able to demonstrate loops in ‘C’. Student will demonstrate

various forms of loops with their variations. With this they will design different structures

like Pascal triangle and pyramid.

Theory:

“for -loops” are used where we need to execute a statement fixed number of times.

Nested “for -loop” is used in a program to construct pyramid of digits and Pascal triangle

in c. If one for-loop is inside other for-loop then it is known as nested for-loop

Syntax:

for (initialization; condition; increment)

{

for (initialization; condition; increment)

{

statement;

}

}

Inner loop will be executed if the condition holds true for the outer loop. If the condition is

false then the statements after the outer loop will be executed.

Pascal triangle:

Pascal’s triangle is a triangular array of the binomial coefficients. To build the pascal

triangle, start with "1" at the top, then continue placing numbers below it in a triangular

pattern. Each number is build just sum of above two numbers, (except for the edge, which

are all ‘1’). To print triangle the loop Statement will be used many times, so nested Loop

Statements are used to construct triangular pattern.

Page 34: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

34 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Pascal Structure:

1

1 1

1 2 1

1 3 3 1

Pyramid Triangle:

There are different ways to create pyramid:

Star pyramid

String Pyramid

Number pyramid

4 for loops are used to construct above pyramid structure.

One loop controls the number of lines i.e. the depth/height of the pyramid.

One loop will print the spaces.

One loop will print the numbers in ascending order.

One loop will print the numbers in descending order.

Algorithm:

Pascal Triangle

1. Start

2. Declare the required variables.

3. Accept number of rows

4. Initialize the outer counter to 1, for counting the number of lines

5. Check the value of outer counter variable is less than the total number of rows. If

yes, goto step 6 else goto step 15

6. Initialize the inner counter variable to 1, to display the digits.

7. Check if the value of inner counter variable is <=outer counter variable. If yes, goto

Pyramid structure:

1

121

12321

1234321

123454321

12345654321

Page 35: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

35 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

step 8 else goto step 14

8. Check whether the value of inner counter variable is equal to 1 if yes goto step 9

else goto step 11

9. Assign the value of inner counter variable to another variable say x

10. Display value of x

11. Calculate value of x as(x*(outer counter-inner counter+1)/(outer counter-1))

12. Display value of x

13. Increment inner counter variable and goto step 7

14. Increment outer counter variable and goto step 5

15. Stop

Pyramid

1. Start

2. Declare the required variables.

3. Accept number of rows

4. Initialize the outer counter to 1, for counting the number of lines

5. Check the value of outer counter variable is less than the total number of rows. If

yes, goto step 6 else goto step 19

6. Initialize the inner counter variable to 1, for counting the number of spaces.

7. Check if the value of inner counter variable is less than the value of the total

number of lines minus the value of the outer counter variable. If yes, goto step 8

else goto step 10

8. Display a space using the printf() statement

9. Increment the value of the inner counter variable and goto step 7.

10. Initialize inner counter variable to 1 display left half of pyramid

11. Check if the value of inner counter variable <= outer counter variable. If yes, goto

step 12 else goto step 14

12. Display the value of inner counter variable for left half of pyramid

13. Increment counter variable and goto step 11

14. Initialize inner counter variable to display right half of pyramid as outer counter

variable minus 1

15. Check if the value of inner counter variable is >=1. If yes, goto step 16 else goto

step 18

Page 36: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

36 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

16. Display the value of inner counter variable

17. Decrement counter variable and goto step 15

18. Increment Outer Counter Variable and goto step 5

19. Stop

Conclusion:

Thus, Pascal triangle and Pyramid algorithms are implemented using nested for

loops.

Page 37: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

37 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:7

Write a C program to generate Fibonacci

series for n number of terms using do

while loop.

Page 38: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

38 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 7

Aim: Write a C program to generate Fibonacci series for n number of terms using do while

loop.

Objective: To provide exposure of do-while loop.

Outcome: Students will be able to apply do-while loop for Fibonacci numbers generations.

Students will learn what Fibonacci numbers is and how they are generated with do-while

loop. With this they will be able to perform different programs related to do-while loop.

Theory:

Fibonacci series is defined as a sequence of numbers in which the first two numbers

are 1 and 1, or 0 and 1, depending on the selected beginning point of the sequence, and

each subsequent number is the sum of the previous two. So, in this series, the nth term is the

sum of (n-1)th term and (n-2)th term. In this tutorial, we’re going to discuss a simple

algorithm and flowchart for Fibonacci series along with a brief introduction to Fibonacci

Series and some of its important properties. In C, do while statement creates a structured

loop that executes as long as a specified condition is true at the end of each pass through

the loop. The syntax for a do while statement is:

do

{

loop_body_statement

}

while (cond_exp);

where: loop_body_statement is any valid C statement or block.

cond_exp is an expression that is evaluated at the end of each pass through the loop. If the

value of the expression is "false" (i.e., compares equal to zero) the loop is exited. Since

cond_expr is checked at the end of each pass through the loop, loop_body_statement is

always executed at least once, even if cond_expr is false.

Page 39: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

39 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Algorithm:

1. Start.

2. Declare variables i, n, f, f1,f2

3. Initialize the variables ,f =0, f1=0, and f2=1

4. Enter the number of terms of Fibonacci series to be printed

5. Use do while loop for the following steps:

f=f1+f2

f1=f2

f2=f

increase the value of i each time by 1

print the value of f

6. Stop

Conclusion:

Thus we have studied the use of do_while statement to implement Fibonacci series

of n number.

Page 40: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

40 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:8

Calculate the sum of the series:

1/1!+2/2!+....up to nth term using while

loop.

Page 41: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

41 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 8

Aim: Calculate the sum of the series: 1/1!+2/2!+....up to nth term using while loop.

Objective: To familiarise while loop of ‘C’ language.

Outcome: Students will be able to illustrate various loops in ‘C’. Here they will

demonstrate while loop with its variations for series generation. Students will apply while

loop and other basic terminology of ‘C’ to generate sum of given series.

Theory:

C – while loop

The while construct consists of a block of code and a condition/expression. The

condition/expression is evaluated, and if the condition/expression is true, the code within

the block is executed. This repeats until the condition/expression becomes false. Because

the while loop checks the condition/expression before the block is executed, the control

structure is often also known as a pre-test loop. Compare this with the do while loop, which

tests the condition/expression after the loop has executed.

Syntax of while loop:

while (condition test)

{

//Statements to be executed repeatedly

// Increment (++) or Decrement (--) Operation

}

Page 42: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

42 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Algorithm:

1. Start

2. Declare variables n, b, i, fact and sum of integer datatype.

3. Initialize the value of fact=1, i=1, and sum=0.

4. Accept the nth number from user

5. Use while loop to execute the following statement

while (i!=n)

Calculate factorial in one variable let say ‘a’

Calculate b=1/a

Calculate sum= sum+b

Print the value of sum

6. Stop

Conclusion:

In this experiment, by using while loop statement we efficiently calculate sum of

series of n number.

Page 43: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

43 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:9

WAP to find out the factorial of number

using recursive method

Page 44: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

44 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 9

Aim: WAP to find out the factorial of number using recursive method

Objective: To familiarise with recursive function.

Outcome: Students will be able to apply function with its prototype, definition and its call.

Students will design and apply recursive function for factorial.

Theory:

Recursion refers to the technique of defining a process in terms of itself. It is used

to solve complex programming problems that are repetitive in nature. The basic idea

behind recursion is to break a problem into smaller versions of itself, and then build up a

solution for the entire problem. This may sound similar to the divide and conquer

technique. However, recursions not similar to the divide and conquer technique. Divide

and conquer is a theoretical concept that may be implemented in a computer program with

the help of recursion. Recursion is implemented in a program by using a recursive

procedure or function. A recursive procedure is a function which invokes itself.

Example:

To understand this concept, consider a factorial function. A factorial function is defined

as:-

n! = 1 * 2 *3 x*4 *.. * n

This same factorial function can be redefined as:-

n! = n*(n-1)! , where n > 1 and 0! = 1

This definition of n! is recursive because it refers to itself when it uses (n – 1)!.The value

of n! is explicitly given where n = 0; and the value of n! for arbitrary n is defined in terms

of the smaller value of n, which is closer to the base value 0.

If you have to calculate 3! by using recursion, you first define 3! in terms of 2!, i.e3! = (3 x

2!)

Now, you will define 2! in terms of 1!: 3! = (3 x (2 x 1!))

Now, 1! will be defined in terms of 0!: 3! = (3 x (2 x (1 x 0!)))

As, 0! is defined as 1, the expression becomes: 3! = (3 x (2 x (1 x 1)))

Page 45: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

45 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

3! = (3 x (2 x 1 ))

3! = (3 x 2)

3! = 6

Algorithm:

1. Start

2. Declare the required variable

3. Accept the number from the user

4. Call the function to compute factorial ,i.e. factorial(n)

5. Check value of n. If n = 0, then goto step 6 else goto step 7

6. return (1) //Terminating condition

7. return (n * factorial(n – 1))

8. Stop

Conclusion:

Thus we have implemented factorial of a number using recursion method.

Page 46: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

46 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:10

WAP to implement Binary search using

function

Page 47: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

47 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 10

Aim: WAP to implement Binary search using function

Objective: To familiarise function and function call with its definition.

Outcome: Students will be able to understand different search methods. They will be able

to design and implement code with applying function for Binary searching technique.

Theory:

Very often in computer programs there is some code that must be executed multiple

times in different places in the program. Separating such code is accomplished by using

functions.

Syntax for Function

type name ( parameter1, parameter2, ...)

{

Statements

}

Where:

- type is the type of the value returned by the function.

- name is the identifier by which the function can be called.

- parameters (as many as needed): Each parameter consists of a type followed by an

identifier, with each parameter being separated from the next by a comma. Each parameter

looks very much like a regular variable declaration (for example: int x), and in fact acts

within the function as a regular variable which is local to the function. The purpose of

parameters is to allow passing arguments to the function from the location where it is

called

- statements is the function's body. It is a block of statements surrounded by braces { } that

specify what the function actually does.

Page 48: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

48 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Example:

int add( int a, int b )

{

int sum;

sum = a + b;

return sum;

}

Where type is int, name is add and parameters are int a,int b.

A binary search is used to find if a value exists or what its position in a sorted list. In each

step, the algorithm compares the input key value with the key value of the middle element

of the array. If the keys match, then a matching element has been found so its index, or

position, is returned. Otherwise, if the sought key is less than the middle element's key,

then the algorithm repeats its action on the sub-array to the left of the middle element or, if

the input key is greater, on the sub- array to the right. If the remaining array to be searched

is reduced to zero, then the key cannot be found in the array and a special "Not found"

indication is returned.

Example:

Find 6 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}

Low=0, high=9, mid= (low+high)/2= (0+9)/2=4

Element at 4th position is 19 so step 1 is followed

Step 1 (middle element is 19 > 6): -1 5 6 18 19 25 46 78 102 114

If the number is less than mid number change high as mid-1 else change low as

mid+1.As 6<19 change high as mid-1 and calculate new mid position.

Step 2 (middle element is 5 < 6): -1 5 6 18 19 25 46 78 102 114

Step 3 (middle element is 6 == 6): -1 5 6 18 19 25 46 78 102 114

In step 3 element 6 is found

Algorithm:

1. Start

2. Declare required variables as low, high, mid and an array a[]

3. Read the number of elements say n

4. Read the number to search

5. Initialize low as 0,high as n-1

Page 49: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

49 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

6. Check low<=high, if yes repeat step 7 to12 else go to step13

7. Calculate mid as (low+ high)/2

8. Check whether number to be searched is equal to a [mid].If yes goto step 9 else

goto 10

9. Display message as element found and exit from the loop

10. Check whether number to be searched is < a[mid] .If yes goto step 11 else goto 12

11. Assign mid-1 as high and goto step 6

12. Assign mid+1 as low and goto step 6

13. Stop

Conclusion:

Binary Search algorithm has been implemented successfully to search an element in

an array of sorted elements.

Page 50: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

50 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:11

WAP to implement swapping of two

integers using call by value and call by

reference

Page 51: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

51 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 11

Aim: 1. Write a function to swap two integers using call by value.

2. Write a function to swap two integers using call by reference.

Objective: To provide exposure in variable call methods .

Outcome: Students will be able to demonstrate how variables are handle in ‘C’, how they

are invoked or call. Student will be able to learn calling methods of variables and then they

will compare result by swapping example of two variables.

Theory:

Call By Value

Passing a variable by value makes a copy of the variable before passing it onto a function.

This means that if you try to modify the value inside a function, it will only have the

modified value inside that function. One the function returns, the variable you passed it

will have the same value it had before you passed it into the function.

Call By Reference

There are two instances where a variable is passed by reference:

1. When you modify the value of the passed variable locally and also the value of the

variable in the calling function as well.

2. To avoid making a copy of the variable for efficiency reasons.

If data is passed by reference, a pointer to the data is copied instead of the actual variable

as is done in a call by value. Because a pointer is copied, if the value at that pointers

address is changed in the function, the original value is also changed

Page 52: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

52 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Algorithm:

1. Start

2. Declare the required variables say a and b

3. Display values of a and b before swap

4. Call function with value for swap as swap(a,b)

4.1 Assign temp=a

4.2 Assign a=b

4.3 Assign b=temp

5. Display values of a and b after swap

6. Call function with reference for swap as swap(&a,&b)

6.1 Assign temp=*a

6.2 Assign *a=*b

6.3 Assign *b=*temp

7. Display values of a and b after swap

8. Stop

Conclusion:

Thus we have found that the call by reference is faster than call by value.

Page 53: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

53 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:12

WAP to implement matrix operations

Page 54: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

54 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 12

Aim: Write a menu driven program to perform following operations:

a. Perform addition of two 3x3 matrices.

b. Obtain transpose of a given 3x3 matrices

c. Multiplication of two 3x3 matrices

Objective: To familiarise with array with its variations.

Outcome: Students will be able to demonstrate use of array in ‘C’, types of array, how

elements are stored, how to display elements. Students will be able to perform operations

on multidimensional array.

Theory:

Array: An array is a collection of data items, all of the same type, accessed using a

common name.

Declaring Arrays

Array variables are declared identically to variables of their data type, except that the

variable name is followed by one pair of square [ ] brackets for each dimension of the

array.

Uninitialized arrays must have the dimensions of their rows, columns, etc. listed

within the square brackets.

Dimensions used when declaring arrays in C must be positive integral constants or

constant expressions.

Using Arrays

Elements of an array are accessed by specifying the index ( offset ) of the desired

element within square [ ] brackets after the array name.

Array subscripts must be of integer type. ( int, long int, char, etc. )

Array indices start at zero in C, and go to one less than the size of the array. For

example, a five element array will have indices zero through four. This is because the

index in C is actually an offset from the beginning of the array. (The first element is at

the beginning of the array, and hence has zero offset)

Page 55: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

55 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Initializing a 2-Dimensional Array:

int stud[4][2] = { { 1234, 56 }, { 1212, 33 }, { 1434, 80 }, { 1312, 78 } } ;

int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;

An array with more than one dimension is called multidimensional array. The two

dimensional arrays is known as matrix.

Consider following sample program that stores roll number and marks obtained by a

student in a matrix.

/* Program to illustrates Two-dimensional Array */

#include<stdio.h>

void main ()

{

int stud[4][2] ;

int i ;

for ( i = 0; i <=3 ; i++)

{

printf("\n Enter Student Roll_ No. and Marks : ");

scanf(“%d %d”,&stud[i][0],&stud[i][1]);

}

printf("\nStudent Roll Number \t Marks ");

for ( i = 0; i <=3 ; i++)

printf("\n%d \t\t%d",stud[i][0],stud[i][1]);

}

There are two parts to the program—in the first part through a for loop we read in the

values of roll no. and marks, whereas, in second part through another for loop we print out

these values. In stud[i][0] and stud[i][1] the first subscript of the variable stud, is row

number which changes for every student. The second subscript indicates the column

number—the zeroth column which contains the roll no. or the first column which contains

the marks. The counting of rows and columns begin with zero. The complete array

arrangement is shown below.

col no 0 col no 1

Page 56: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

56 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

row no 0 1234 56

row no 1 1212 33

row no 2 1434 80

row no 3 1312 78

Thus, 1234 is stored in stud[0][0], 56 is stored in stud[0][1] and so on. The above

arrangement highlights the fact that a two- dimensional array is nothing but a collection of

a number of one- dimensional arrays placed one below the other.

Algorithm:

1. Start.

2. Declare 2-D array x[][], y[][] for input and z[][] for output

3. Read row1, row2, col1, col2.

4. Display menu to user and accept choice from user

1. Addition of matrices

2. Transpose of Matrix

3. Multiplication of Matrix

5. If choice=1 then goto step 8

6. If choice=2 then goto step 14

7. If choice=3 then goto step 17

8. If row1==row2 and col1==col2 then goto step 9 else goto 14

9. Initialise loop variable for rows of matrix say i and for column of matrix say j

10. Read Matrix x[i][j] and Read Matrix y[i][j]

11. Perform addition of matrix as per rows and column of both matrix

Z[i][j]=x[i][j]+y[i][j]

12. Display resultant matrix z[i][j]

13. Display message Addition is not possible and goto exit.

14. Initialise loop variable for rows, column say i and j and read matrix x[i][j]

15. While reading elements of matrix x[i][j], store same element in some another

matrix say y[j][i]

16. Display y[i][j] matrix as a transpose of matrix x[i][j]

17. If col1 != row2 then goto step 19 else goto step 20

Page 57: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

57 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

18. Display message multiplication is not possible

19. Initialize outer loop variable for rows and for column to read matrix x and y, say i

and j

20. Read matrix x as x[i][j]

21. Read matrix y as y[i][j]

22. Initialize outer loop variable for rows to multiply ,say i

23. Check whether i<row1 ,if yes goto step 25 else goto step 32

24. Initialize inner loop variable say j

25. Check whether j<col2 ,if yes goto step 27 else increment i

26. Initialize z[][] as 0 in loop

27. Initialize inner loop variable say k

28. Check whether k<col1 ,if yes goto step 29 else increase k

29. z[i][j]=z[i][j]+x[i][k]*y[k][j]

30. Print x,y,z matrix using for loop

31. Stop

Conclusion:

Using nested for loop we have studied how to read and display the matrix or 2- D

array and how to perform addition, transpose and multiplication of two matrices.

Page 58: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

58 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:13

WAP to check whether given string is

palindrome or not.

Page 59: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

59 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 13

Aim: WAP to check whether given string is palindrome or not

Objective: To familiarise in array flow and some operations on strings.

Outcome: Students will be able to understand array working format. Student will illustrate

array for storing string to check for palindrome. Student will be able to learn some string

functions.

Theory:

Palindrome:

Palindrome is a Greek word which is divided in two or three word as (palin=Again

+ drome/deamein=Run). So a palindrome is word or phrase which reads the same in both

direction .e. left to right and right to left are character must be same. Example of string

palindrome as follows:

1. POP

2. MALAYYALAM

3. LEVEL

4. LIVE EVIL

5. MADAM

Algorithm:

1. start

2. Declare the required variables as str1[], str2[].

3. Accept the string str1[]

4. Copy str1 to str2 using strcpy( ).

5. reverse the string str2 using strrev( ) function

6. Initialize i =0.

7. check whether str1[i]!=’\0’. If yes goto step 8 else goto step 11

8. Check str1[i]=str2[i] if yes goto step 9 else exit the loop using break

9. Increment i and goto step 7.

10. If str1[i]==’\0’ then

Page 60: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

60 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

10.1 print “String is palindrome”

10.2 else print “String is not palindrome”

11. stop

Conclusion:

Thus we have checked whether given string is palindrome or not using above given

algorithm.

Page 61: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

61 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:14

WAP to implement Bubble sort using

function

Page 62: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

62 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 14

Aim: WAP to implement bubble sort using function

Objective: To provide exposure in sorting techniques .

Outcome: Students will be able to demonstrate functions. Students will be able to learn

sorting technique. Students will apply function for bubble sorting technique.

Theory:

Bubble sort is a simple and well-known sorting algorithm .Bubble sort, sometimes

incorrectly referred to as sinking sort, is a simple sorting algorithm that works by

repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and

swapping them if they are in the wrong order. The pass through the list is repeated until

number of swaps are needed, which indicates that the list is sorted.

The algorithm gets its name from the way smaller elements "bubble" to the top of the list.

Because it only uses comparisons to operate on elements, it is a comparison sort. Although

the algorithm is simple, most of the other sorting algorithms are more efficient for large

lists.

Example:

First Pass:

(51428) - ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps 1 and 5

since 1<5

(15428)- ( 1 4 5 2 8 ), Swap since 5 > 4

14528)- ( 1 4 2 5 8 ), Swap since 5 > 2

(14258)( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm

does not swap them.

Second Pass:

(14258)- (14258)

(14258)- ( 1 2 4 5 8 ), Swap since 4 > 2

(12458)-( 12458)

(12458)- (12458)

Page 63: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

63 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Now, the array is already sorted, but our algorithm does not know if it is completed. The

algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:

(12458)- (12458)

(12458)- (12458)

(12458)- (12458)

(12458)- (12458)

Algorithm:

1. Start

2. Declare the required variables.

3. Accept number of elements n

4. Read the array say a[]

5. Initialize outer loop variable say i as 1for passes

6. Check whether i< n,if yes repeat step 7 to 12 else goto step13

7. Initialize outer loop variable say j as 0

8. Check whether j< n-1,if yes repeat step 9 to 11 else goto step12

9. Check whether a[j]>a[j+1],if yes goto step else goto step

10. Swap a[j] and a[j+1]

11. Increment j and goto step 8

12. Increment i and goto step 6

13. Print Sorted array a[]

14. Stop

Conclusion:

Thus we have implemented bubble sort technique for sorting a set of elements in

ascending order.

Page 64: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

64 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:15

WAP to perform different string

operations

Page 65: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

65 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 15

Aim: WAP to perform different string operations

Objective: To familiarise different string operations.

Outcome: Students will be able to demonstrate string handling in ‘C’. Students will

understand how to use string.h header file. Students will learn various string related

functions from string.h header file.

Theory:

The C language provides no explicit support for strings in the language itself. The

string-handling functions are implemented in libraries. String I/O operations are

implemented in <stdio.h> (puts , gets, etc). A set of simple string manipulation functions

are implemented in <string.h>, or on some systems in <strings.h>. The string library

(string.h or strings.h) has some useful functions for working with strings, like strcpy, strcat,

strcmp, strlen, strcoll, etc. We will take a look at some of these string operations.

Important: Don‘t forget to include the library string.h (or on some systems strings.h) if

you want to use one of these library functions.

strcpy

This library function is used to copy a string and can be used like this: strcpy(destination,

source). (It is not possible in C to do this: string1 = string2).

str_one = "abc";

str_two = "def";

strcpy(str_one , str_two); // str_one becomes "def"

strcmp

This library function is used to compare two strings and can be used like this: strcmp(str1,

str2). If the first string is greater than the second string a number greater than null is

returned. If the first string is less than the second string a number less than null is returned.

If the first and the second string are equal a null is returned.

printf("Enter you name: ");

scanf("%s", name);

if( strcmp( name, "jane" ) == 0 )

Page 66: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

66 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

printf("Hello, jane!\n");

strcat

This library function concatenates a string onto the end of the other string. The result is

returned.

Take a look at the example:

printf("Enter you age: ");

scanf("%s", age);

result = strcat( age, " years old." ) == 0 )

printf("You are %s\n", result);

strlen

This library function returns the length of a string. (All characters before the null

termination.)

Take a look at the example:

name = "jane";

result = strlen(name); //Will return size of four.

Algorithm:

1. Start

2. Declare the required variables as str1[],str2[],str3[],str[] ,c and len

3. Read the strings str1 and 2

4. Calculate len as strlen(str1) //str1 length

5. Display len

6. Copy str2 to str3 as strcpy(str3,str2)

7. Display str3

8. c=strcmp(str1,str2)

9. Check whether c is equal to 0,if yes goto step 10 else goto step 11

10. Display both Strings are equal

11. Display both strings are not equal

12. Concatenate str1 and str2 as strcat(str1,str2)

13. Display str1

14. Stop

Page 67: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

67 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Conclusion:

Thus we have implemented different string operations by using built-in functions

which is included in the header file string.h

Page 68: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

68 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:16

Write a program using structure to

calculate areas of various rooms like hall,

kitchen and bedroom. Declare a structure

for room details like length and breadth.

Page 69: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

69 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 16

Aim: Write a program using structure to calculate areas of various rooms like hall, kitchen

and bedroom. Declare a structure for room details like length and breadth.

Objective: To familiarise with structure in ‘C’.

Outcome: Students will be able to demonstrate use of structure in ‘C’. Student will

understand how various types of data are stored in structure and how to display all data

from structure. In this program student will create structure form area calculation.

Theory:

In C a structure is derived data type consisting of a collection of data members and

their data types. It is heterogeneous in nature i.e. it can store any type of data.

Structure Definition:

A structure definition can be given using following syntax-:

struct structure_name

{

Data-type member1;

Data-type member2;

Data-type member3;

.

.

.

};

where struct is a keyword

Structure variable declaration:

struct structure_name var_name;

e.g.

struct room

{

char name[9];

float length;

Page 70: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

70 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

float breath;

float area;

};

struct room s;

Accessing data members:

Data members of structure can be accessed using period/ dot (.) operator.

e.g. s.length, s.breath, s.name, s.area

Structure Initialization:

There are three ways to initialize a structure.

Room r = {‘Hall’, 50, 60, 200.3}

Another way is

Room r = {.name=’Hall’, length=50, breath=60, area=200.3}

And we can assign one object of structure to another object also like

Room r= s;

Array of Structures:

When we work with group of entities and their attributes, we need to create array of

structures. An array of sturctures can be created using

struct structure_name variable_name[size];

e.g. struct room s[5];

This creates an array of 5 room structure.

Algorithm:

1. Start

2. Write structure definition of room with data members name, length, breath, area

3. Enter details for kitchen as read room name as s[i].name, read length as

s[i].length, read breath as s[i].breath

4. s.area=s.length*s.breath;

5. Display s.area of kitchen

6. Enter details for Hall as read room name as s[i].name, read length as s[i].length,

read breath as s[i].breath

Page 71: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

71 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

7. s.area=s.length*s.breath;

8. Display s.area of hall

9. Enter details for bedroom as read room name as s[i].name, read length as

s[i].length, read breath as s[i].breath

10. s.area=s.length*s.breath;

11. Display s.area of bedroom

12. Stop

Conclusion:

After writing this program we understood structures can store different type of

data, how to declare structure variables and array of structures. With the knowledge of

structures we are able to calculate area of different room details and display them.

Page 72: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

72 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:17

Write a program on file handling.

Page 73: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

73 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 17

Aim: WAP on File handling

Objective: To familiarise with file operations in ‘C’.

Outcome: Students will be able to demonstrate file handling in ‘C’. Students will

understand how to open, name, read and writing in a file. Student will understand different

modes of files.

Theory:

A file is a place on the disk where a group of related data is stored. C supports a

number of functions that have the ability to perform basic file operations, which include:

1. Naming a file

2. Opening a file

3. Reading from a file

4. Writing data into a file

5. Closing a file

The following table shows the list of functions used for file handling along with the

operations

Function

Name

Operation Syntax

fopen() Creates a new file for use

Opens a new existing file for use

FILE *fp;

fp=fopen(“filename”, “mode”);

where

FILE- data structure of all files

fp- a pointer associated with a file of type FILE

filename – name of file

mode - modes of file

fclose Closes a file which has been opened

for use

fclose(file-pointer);

getc() Reads a character from a file char c =getc(file pointer);

Page 74: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

74 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

putc() Writes a character to a file int putc(int char,FILE *stream)

fprintf() Writes a set of data values to a file fprintf(fp,”control string”, list);

fscanf() Reads a set of data values from a file fscanf(fp,”controlstring”,list);

getw() Reads a integer from a file getw(fp);

putw() Writes an integer to the file putw(integer,fp);

fseek() Sets the position to a desired point in

the file

fseek(file pointer,offset, position);

Offset is a number or variable of type long, and

position is an integer number. Offset specifies

the number of positions (bytes) to be moved

from the location specified bt the position. The

position can take the 3 values.

Value Meaning

0 Beginning of the file

1 Current position

2 End of the file.

ftell() Gives the current position in the file long int ftell(FILE *stream)

rewind() Sets the position to the begining of the

file

void rewind (FILE *stream)

The different modes of file are listed below

Mode Operation

R open the file for

reading only

W open the file for

writing only

A

the file for

appending (or

adding) data to it

Page 75: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

75 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Algorithm:

1. Start

2. Declare the variables of required type

3. Create file pointer

4. Open text file in write mode Initialize counter i=1

5. Repeat steps 7 to 9 till i<=5

6. Read employee name as empname

7. Store name in file using fprintf

8. Read employee id as empid

9. Store id in file using fprintf

10. Read employee salary as empsal

11. Store salary in file using fprintf

12. Increment counter i by 1

13. Close file pointer.

14. Open file in read mode

15. Repeat steps 13 to 14 file pointer is not reached at end of file (eof)

16. Open the text file in read mode

17. Repeat the step 19 to 24 till end of file

18. Read the empname from the file using fscanf

19. print empname using printf statement

20. Read the empsal from the file using fscanf

21. print empsal using printf statement

22. Read the empid from the file using fscanf

23. print empid using printf statement

24. close the file using fclose

25. stop

Conclusion:

After implementing this program we are able to understand file, its different

operations and different ways of accessing them.

Page 76: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

76 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:18

Write a program to perform arithmetic

operations using pointers.

Page 77: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

77 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 18

Aim: WAP to perform arithmetic operations using pointers.

Objective: To provide exposure in Pointers in ‘C’ .

Outcome: Students will be able to apply pointers in ‘C’. Students will learn what address

of variable is and what is value of variable. Students will demonstrate use of pointer by

arithmetic operations.

Theory:

Pointers are variables that are used to store the address of another variable.

Address of a variable is the memory location number which is allotted to the variable. The

memory addresses are up to capacity of memory. The address is normally displayed in

hexadecimal form. Pointers do not store values they store addresses. A pointer is also a

variable thus it requires memory and we can also have another pointer which will point the

address of pointer.

Syntax-:

data_type *ptr_name;

data_type - data_type of a variable whose address it is storing

ptr_name – rules for naming ptr_name is same as that of rules for naming identifiers

E.g. int *p;

There are two operators required in pointer based programs Address operator (&) and

value of operator (*)

Address of operator (&)-:

It is also called as referencing operator

This operator returns the address of the variable associated with the pointer.

Hence if we have a pointer p which we want to point to variable x then we need

to copy the address of variable x in pointer variable p.

P=&x;

Value operator (*)-: It returns value stored in variable pointed by pointer variable.

Pointer Arithmetic-:

Increment (++)-: It increments value by 1.

Page 78: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

78 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

E.g.1

int *p;

int x=10;

p=&x;

(*p)++;

Output-: 11

int *p;

int x=10;

p= &x;

p++; // It does not increments value of variable whose address it is storing but increments

address by 2 bytes (since integer pointer)

Decrement (++)-: It decrements value by 1.

E.g.2

int *p;

int x=10;

p=&x;

(*p)--;

Output-: 9

int *p;

int x=10;

p= &x;

p--; // It does not decrements value of variable whose address it is storing but decrements

address by 2 bytes (since integer pointer)

Algorithm-:

11. Start

12. Declare two pointer variables *p1, *p2 and two integer variables a,b;

13. Accept values for a and b.

14. Store addresses of a and b in pointers p1 and p2 respectively.

15. Find addition using pointer variables as c= (*p1) + (*p2) and display result

16. Difference using pointer variables as c= (*p1)- (*p2) and display result

17. Multiplication using pointer variables as c= (*p1) * (*p2) and display result

18. Division using pointer variables as c= (*p1)/ (*p2) and display result

Page 79: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

79 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

19. Stop

Conclusion:

After implementing this program we understood use of pointers and pointer

arithmetic.

Page 80: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

80 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:19

WAP to demonstrate usage of Dynamic

Memory allocation using standard C

library functions.

Page 81: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

81 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No. 19

Aim: WAP to demonstrate usage of Dynamic Memory allocation using standard C library

functions.

Objective: To familiarise memory allocation.

Outcome: Students will be able to demonstrate dynamic memory allocation. Student will

learn how memory is handling in ‘C’. Students will also understand various functions of

dynamic memory allocation.

Theory:

Dynamic memory allocation in C: The process of allocating memory during

program execution is called dynamic memory allocation.

Dynamic memory allocation functions in C: C language offers 4 dynamic

memory allocation functions. They are,

1. malloc()

2. calloc()

3. realloc()

4. free()

1. malloc () function in C:

malloc () function is used to allocate space in memory during the execution of the

program.

malloc () does not initialize the memory allocated during execution. It carries

garbage value.

malloc () function returns null pointer if it couldn’t able to allocate requested

amount of memory.

Syntax of malloc()

ptr = (cast-type*) malloc(byte-size)

Page 82: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

82 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of

memory with size of byte size. If the space is insufficient, allocation fails and returns

NULL pointer.

ptr = (int*) malloc(100 * sizeof(int));

This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes

respectively and the pointer points to the address of first byte of memory.

2. calloc () function in C:

calloc () function is also like malloc () function. But calloc () initializes the

allocated memory to zero. But, malloc () doesn’t.

The name calloc stands for "contiguous allocation".

The only difference between malloc() and calloc() is that, malloc() allocates single

block of memory whereas calloc() allocates multiple blocks of memory each of

same size and sets all bytes to zero.

Syntax of calloc()

ptr = (cast-type*)calloc(n, element-size);

This statement will allocate contiguous space in memory for an array of n elements. For

example:

ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for an array of 25 elements each of

size of float, i.e., 4 bytes.

3. realloc () function in C:

realloc () function modifies the allocated memory size by malloc () and calloc ()

functions to new size.

Page 83: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

83 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

If enough space doesn’t exist in memory of current block to extend, new block is

allocated for the full size of reallocation, then copies the existing data to new block

and then frees the old block.

Syntax of realloc()

ptr = realloc(ptr, newsize);

Here, ptr is reallocated with size of newsize.

4. free () function in C:

free () function frees the allocated memory by malloc (), calloc (), realloc ()

functions and returns the memory to the system.

Syntax of free()

free (ptr);

This statement frees the space allocated in the memory pointed by ptr.

Conclusion:

Thus, we conclude that in C dynamic memory allocation refers to performing

manual memory management through a group of functions from C standard library,

namely malloc, realloc, calloc and free.

Page 84: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

84 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Structured Programming Approach

Experiment No:20

Write a program to display contents of

array using pointers

Page 85: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

85 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Experiment No 20

Aim: Write a program to display contents of array using pointers

Objective: To familiarise array operations using pointers.

Outcome: Students will be able to illustrate array. Students will demonstrate pointers.

With pointers and array students design array contents and display their contents.

Theory:

Pointers in C are easy to learn. C programming tasks are performed easily with

pointers. So it becomes necessary to learn pointers to. A variable is a memory location

and every memory location has its address defined which can be accessed using

ampersand (&) operator, which denotes an address in memory.

A pointer is a variable whose value is the address of another variable, i.e., direct

address of the memory location. Like any variable or constant, you must declare a

pointer before using it to store any variable address. The general form of a pointer

variable declaration is –

datatype *varname;

Where * indicate it’s a pointer, datatype is pointers base address and varname is name of

variable.

Examples:

int *a; //pointer to int

double *b; //pointer to double

char *c; //pointer to char

float *d; //pointer to float

Array:

Array a kind of data structure that can store a fixed-size collection of elements of

the same data type. An array is used to store data, but it is more to think of an array as a

collection of variables of the same type.

Page 86: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

86 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Arrays are closely related to pointers in C programming but the important difference

between them is that, a pointer variable takes different addresses as value whereas, in case

of array it is fixed.

Relation between array and pointers:

Suppose array int abc[5], in this name of the array always points to address of the first

element of an array.

Here abc and &abc[0] points to address of first element. Since address is same so values

of both are also same.

Same way &abc[1] is same to (abc+1) and abc[1] is same as *(abc+1)

Same &abc[2] is same to (abc+2) and abc[2] is same as *(abc+2)

And &abc[3] is same to (abc+3) and abc[3] is same as *(abc+3)

In general we can say &abc[i] is same to (abc+i) and abc[i] is same as *(abc+i)

Algorithm:

1. Start

2. Declare array arr[10]

3. Declare a pointer variable say p

4. Initialize *p=&arr[0] (Address of first element of array)

5. Repeat until all elements get display from array

6. If loop variable say i > total array elements goto stop else goto 7

7. Display array value as *(p+i)

8. Display address as (p+i)

9. Stop

Page 87: Lab Manual - SimplyCS.inWrite a program to perform file operations: a. Opening a file b. Reading the contents of file. c. Appending the contents to the file. 18 WAP to perform arithmetic

87 | P a g e

Department of Engineering Sciences Academic Year: 2017-18

Conclusion:

As per above discussion we have studied use of array, pointers. So now we are

able to understand how to display array using pointer.