SlideShare a Scribd company logo
Programming for Problem Solving Lab
Page 1
BVRIT HYDERABAD College of Engineering for Women
BVRIT HYDERABAD
College of Engineering for Women
The Temple for Women Empowerment & Human Values
Approved by AICTE & Affiliated to JNTUH, Hyderabad
Nizampet Road, Bachupally, Hyderabad – 500 090, Telangana, India.
Student Notebook
Department Basic Science and Humanities
Year / Semester I B.Tech / I & II Semester
Subject Programming for Problem Solving Lab
Academic Year(Regulation) 2021-22 (R18)
Subject Code CS106ES / CS206ES
Vision
To emerge as the best among the institutes of technology and research in the
country dedicated to the cause of promoting quality technical education.
Mission
At BVRITH, we Strive to
 Achieve academic excellence through innovative learning practices.
 Enhance intellectual ability and technical competency for a successful career.
 Encourage research and innovation.
 Nurture students towards holistic development with emphasis on leadership skills ,
Life skills and human values.
Programming for Problem Solving Lab
Page 2
BVRIT HYDERABAD College of Engineering for Women
IT - DEPARTMENT VISION
To emerge as a Center of excellence in Information Technology and to produce women
technocrats, global leaders for better tomorrow.
IT - DEPARTMENT MISSION
M1: To impart quality education and inculcate problem solving skills using latest Technologies
in the field of Information Technology.
M2: To encourage multidisciplinary research and consultancy projects.
M3: To promote industry academia linkage and also enhance entrepreneurship skills in women
engineers.
IT- Programme Educational Objectives (PEOs)
After three to six years of graduation, the graduates of this program will be able to:
PEO 1: Develop strong analytical skills using fundamental concepts of science & engineering
subjects.
PEO 2: Excel in programming and critical thinking by applying core technical knowledge
PEO 3: Exhibit continuous learning related to evolving technologies in their professional career
PEO 4: Demonstrate ethical behavior, team work & leadership qualities to solve problems
in broader social context.
Programming for Problem Solving Lab
Page 3
BVRIT HYDERABAD College of Engineering for Women
CSE – DEPARTMENT VISION
Develop women as technocrats, researchers and entrepreneurs in the field of computer science and
engineering.
CSE - DEPARTMENT MISSION
M1: To impart quality education in Computer Science and Engineering by means of learning
techniques and value-added courses.
M2: To inculcate professional excellence and research culture by encouraging projects in cutting-
edge technologies through industry interactions.
M3: To build leadership skills, ethical values and teamwork among the students.
M4: To strengthen the collaboration of department and industry through internships, mentorships and
professional body activities.
CSE -Programme Educational Objectives (PEOs)
After three to six years of graduation, the graduates of this program will be able to:
PEO–1: Adapt emerging technologies to contribute to the technical innovations for the progressive
development in their respective fields.
PEO–2: Productively engage in multidisciplinary research areas by applying the basic principles
of engineering sciences.
PEO–3: Demonstrate strong technical skills to bring out novel designs/products to address the
social & environmental issues.
PEO–4: Exhibit professional attitude, teamwork and practice code of ethics.
Programming for Problem Solving Lab
Page 4
BVRIT HYDERABAD College of Engineering for Women
ECE - DEPARTMENT VISION
To emerge as a centre of academic and research excellence in Electronics and Communication
Engineering and create globally competent women technocrats with a high degree of social
consciousness in a holistic learning environment
ECE - DEPARTMENT MISSION
M1: To provide quality education to the students with emphasis on training related to latest
technologies as per industrial needs
M2: To impart research culture, professional ethics and moral values to the students by
committed and competent faculty striving for excellence.
M3: To inculcate a perceptive alacrity in students to identify real life problems, formulate
strategies and evolve into contextually effective solutions.
ECE- Programme Educational Objectives (PEOs)
After three to six years of graduation, the graduates of this program will be able to:
PEO-1: Excel in contemporary problem solving in Electronics and Communication
Engineering and the allied fields through the knowledge-base provided by the
programme.
PEO-2: Demonstrate their technical, communication and leadership skills in professional
environment or as entrepreneurs with social responsibility.
PEO-3: Analyze the latest issues and technology growth in the field of Electronics and
Communication Engineering and update their knowledge and skills accordingly
through continuous learning.
PEO-4: Demonstrate ethical and human values in multicultural and multidisciplinary
environments
Programming for Problem Solving Lab
Page 5
BVRIT HYDERABAD College of Engineering for Women
EEE - DEPARTMENT VISION
To develop comprehensively trained and socially responsible women electrical and electronics
engineers with competencies and capabilities to adapt to new challenges.
EEE - DEPARTMENT MISSION
M1: To empower the students adept at latest technologies by providing innovative learning
environment.
M2: To cultivate interdisciplinary research mindset and outlook to develop engineering solutions.
M3: To inculcate ethical behavior and professional attitude in order to embrace holistic concept of
living.
EEE - Programme Educational Objectives (PEOs)
After three to six years of graduation, the graduates of this program will be able to:
PEO–1: Propose effective solutions for complex electrical and electronics engineering problems
using modern techniques.
PEO–2: Excel in their career and compete with their global peers in Techno-Scientific fields.
PEO–3: Exhibit good communication skills, ethical behavior & social perception.
PEO–4: Stimulate economic growth and job opportunities through entrepreneurship.
Programming for Problem Solving Lab
Page 6
BVRIT HYDERABAD College of Engineering for Women
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD
PROGRAMMING FOR PROBLEM SOLVING LAB
B.Tech I Year I/II Sem.
Course Code: CS106ES/CS206ES L T P C
0 0 3 1
CONTENTS
1 Syllabus .………………..…………..……………... 9
2 Instructions to Students …………….……………………………... 14
3 Introduction to UNIX commands ...………………………….……… ……. 15
4 Introduction to C Concepts .…………………………………………... 18
5 Steps in program development ….………………….................................. 22
6 Lab Cycle-1 Algorithms …………………………………………… 25
7 Lab Cycle-2 Algorithms …………………………………………… 31
8 Lab Cycle-3 Algorithms …………………………………………… 39
9 Viva Questions with Solutions …………………………………………… 48
i. Introduction to C ….……………………….......................... 48
ii. Arrays & functions …………………………………………… 52
iii. Strings ………………………. ………………….. 56
iv. Structures ……...….………………………………… 57
v. Files …………………………………………... 58
Programming for Problem Solving Lab
Page 7
BVRIT HYDERABAD College of Engineering for Women
PROGRAMMING FOR PROBLEM SOLVING LAB
INTERNAL ASSESSMENT SHEET
LIST OF EXPERIMENTS
S.No Name of the Experiment Date of Exp done
Lab
[5M]
Record
[5M]
Viva
[5M]
Total
[15M]
Remarks
Signature of the
Faculty
Programming for Problem Solving Lab
Page 8
BVRIT HYDERABAD College of Engineering for Women
List of Experiments
Department Computer Science & Engineering
Information Technology
Year / Semester I B. Tech (CSE, IT, ECE, EEE, AI&ML) – I & II Semester
Subject Programming for Problem Solving Lab
Academic Year (Regulation) 2021-22 (R18)
Subject Code CS106ES/CS206ES
Course Objectives: The students will learn the following:
• To work with an IDE to create, edit, compile, run and debug programs
• To analyze the various steps in program development.
• To develop programs to solve basic problems by understanding basic concepts in C like
operators, control statements etc.
• To develop modular, reusable and readable C Programs using the concepts like functions,
arrays etc.
• To Write programs using the Dynamic Memory Allocation concept.
• To create, read from and write to text and binary files
Course Outcomes: The candidate is expected to be able to:
• Design and test programs to solve mathematical and scientific problems.
• Apply control structures and functions for structured programs.
• Construct programs using the concept of array and pointer to solve the problems.
• Build efficient Solution for complex problems by using various programming constructs
Programming for Problem Solving Lab
Page 9
BVRIT HYDERABAD College of Engineering for Women
SYLLABUS
CYCLES PROGRAMS
CYCLE-1
Practice sessions:
a. Write a simple program that prints the results of all the operators available in C
(including pre/ post increment, bitwise and/or/not, etc.). Read required operand
values from standard input.
b. Write a simple program that converts one given data type to another using auto
conversion and casting. Take the values form standard input.
Simple numeric problems:
a. Write a program to find the max and min from the three numbers.
b. Write the program for the simple, compound interest.
c. Write program that declares Class awarded for a given percentage of marks, where
mark <40%= Failed, 40% to <60% = Second class, 60% to <70%=First class, >=
70% = Distinction. Read percentage from standard input.
d. Write a program that prints a multiplication table for a given number and the
number of rows in the table. For example, for a number 5 and rows = 3, the output
should be:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
e. Write a program that shows the binary equivalent of a given positive number
between 0 to 255.
Expression Evaluation:
a. A building has 10 floors with a floor height of 3 meters each. A ball is dropped from
the top of the building. Find the time taken by the ball to reach each floor. (Use the
formula s = ut+(1/2)at^2 where u and a are the initial velocity in m/sec (= 0) and
acceleration in m/sec^2 (= 9.8 m/s^2)).
Programming for Problem Solving Lab
Page 10
BVRIT HYDERABAD College of Engineering for Women
b. Write a C program, which takes two integer operands and one operator from the
user, performs the operation and then prints the result. (Consider the operators +,-,*,
/, % and use Switch Statement)
c. Write a program that finds if a given number is a prime number
d. Write a C program to find the sum of individual digits of a positive integer and test
given number is palindrome
e. A Fibonacci sequence is defined as follows: the first and second terms in the
sequence are 0 and 1. Subsequent terms are found by adding the preceding two terms
in the sequence. Write a C program to generate the first n terms of the sequence.
f. Write a C program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user.
g. Write a C program to find the roots of a Quadratic equation.
h. Write a C program to calculate the following, where x is a fractional value.
1-x/2 +x^2/4-x^3/6
i. Write a C program to read in two numbers, x and n, and then compute the sum of this
geometric progression: 1+x+x^2+x^3+ ................+x^n. For example: if n is 3 and x
is 5, then the program computes 1+5+25+125
CYCLE-2
Arrays and Pointers and Functions:
a. Write a C program to find the minimum, maximum and average in an array of
integers.
b. Write a functions to compute mean, variance, Standard Deviation, sorting of n
elements in single dimension array.
Programming for Problem Solving Lab
Page 11
BVRIT HYDERABAD College of Engineering for Women
c. Write a C program that uses functions to perform the following:
i) Addition of Two Matrices
ii) Multiplication of Two Matrices
iii) Transpose of a matrix with memory dynamically allocated for the new matrixas
row and column counts may not be same.
d. Write C programs that use both recursive and non-recursive functions
i) To find the factorial of a given integer.
ii) To find the GCD (greatest common divisor) of two given integers.
iii)To find x^n
e. Write a program for reading elements using pointer into array and display the values
using array.
f. Write a program for display values reverse order from array using pointer.
g. Write a program through pointer variable to sum of n elements from array.
Files:
a. Write a C program to display the contents of a file to standard output device.
b. Write a C program which copies one file to another, replacing all lowercase
characters with their uppercase equivalents.
c. Write a C program to count the number of times a character occurs in a text file. The
file name and the character are supplied as command line arguments.
d. Write a C program that does the following:
It should first create a binary file and store 10 integers, where the file name and 10
values are given in the command line. (hint: convert the strings using atoi function)
Now the program asks for an index and a value from the user and the value at that
index should be changed to the new value in the file. (hint: use fseek function) The
program should then read all 10 values and print them back.
e. Write a C program to merge two files into a third file (i.e., the contents of the firs t
file followed by those of the second are put in the third file).
Programming for Problem Solving Lab
Page 12
BVRIT HYDERABAD College of Engineering for Women
CYCLE-3
Strings:
a. Write a C program to convert a Roman numeral ranging from I to L to its decimal
equivalent.
b. Write a C program that converts a number ranging from 1 to 50 to Roman equivalent
c. Write a C program that uses functions to perform the following operations:
i) To insert a sub-string in to a given main string from a given position.
ii) To delete n Characters from a given position in a given string.
d. Write a C program to determine if the given string is a palindrome or not (Spelled
same in both directions with or without a meaning like madam, civic, noon, abcba,
etc.)
e. Write a C program that displays the position of a character ch in the string S or – 1 if
S doesn„t contain ch.
f. Write a C program to count the lines, words and characters in a given text.
Miscellaneous:
a. Write a menu driven C program that allows a user to enter n numbers and then
choose between finding the smallest, largest, sum, or average. The menu and all the
choices are to be functions. Use a switch statement to determine what action to take.
Display an error message if an invalid choice is entered.
b. Write a C program to construct a pyramid of numbers as follows:
1 * 1 1 *
1 2 * * 2 3 2 2 * *
1 2 3 * * * 4 5 6 3 3 3 * * *
4 4 4 4 * *
*
Sorting and Searching:
a. Write a C program that uses non recursive function to search for a Key value in a
given list of integers using linear search method.
Programming for Problem Solving Lab
Page 13
BVRIT HYDERABAD College of Engineering for Women
b .Write a C program that uses non recursive function to search for a Key value in a
given sorted list of integers using binary search method.
c. Write a C program that implements the Bubble sort method to sort a given list of
integers in ascending order.
d. Write a C program that sorts the given array of integers using selection sort in
descending order
e. Write a C program that sorts the given array of integers using insertion sort in
ascending order
f. Write a C program that sorts a given array of names
Suggested Reference Books for solving the problems:
i. Byron Gottfried, Schaum‟s Outline of Programming with C, McGraw-Hill
ii. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage
Learning, 3rd Edition)
iii. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice
iv. Hall of India
v. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
vi. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
vii. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition
Programming for Problem Solving Lab
Page 14
BVRIT HYDERABAD College of Engineering for Women
INSTRUCTIONS TO THE STUDENTS
(1) On entering the lab you should make an entry in the log book available with thedetails
regarding student name, roll no, system no and signature.
(2) You must bring Observation notebook for every lab session. Observation book should be duly
signed by your faculty, failing which your report will not be graded. You must complete all
experimental programs allotted during the session.
(3) You should shutdown the system properly and leave the lab neat and tidy.
Programming for Problem Solving Lab
Page 15
BVRIT HYDERABAD College of Engineering for Women
INTRODUCTION TO ‘UNIX’ COMMANDS
In order to create and run programs in UNIX environment the following are the some of the basic
editors and commands used.
Creating Directory:
Directories are used to group files together in a hierarchical structure.
mkdir dirname --- creates a new directory
cd dirname --- to change to the specified directory
cd.. --- will get you one level up from your current position(directory) rmdir
dirname --- removes/deletes directory
rm --- deletes files in directory
Editors:
Nano Editor: Basic editors used for creating the programs are nano, vim, emacs.
GNU nano is a small and friendly text editor for beginners. Nano is installed by default in Ubuntu and
many other editors.
To run nano you can use the following syntax:
nano path_filename.c
Nano will follow the path and open that file if it exists. If it does not exist, it‟ll start a new buffer
with that filename in that directory.
It‟s a WYSIWYG editor; “what you say is what you get.” What you type directly goes into the text
input, unless you modify it with a key like Control or Meta.
Shortcuts:
Ctrl+o --- to save the file contents
Ctrl+x --- to Quit the editor. Nano will politely ask you if you want to save your buffer, and you
can cancel this action as well.
Ctrl+w --- to search for the text in the program
Creating and Running Programs in Nano Editor:
1. To open the file ,at the command prompt type ------nano filename.c
2. Create the program and save the file---- ctrl+o , ctrl+s
3. Quit the editor----- ctrl+x
4. At the command prompt type
gcc/c99 filename.c
Above command is used to compile the program to generate object code.
5. To run the program type
./a.out(executable file)
Programming for Problem Solving Lab
Page 16
BVRIT HYDERABAD College of Engineering for Women
Vim Editor: Vim is an advanced text editor that provides the power of the de-facto Unix editor 'Vi'
with a more complete feature set. Vim is often called a "programmer's editor," and is so seful for
programming that many consider it an entire IDE. It's not just for programmers, though. Vim is perfect
for all kinds of text editing.
Vim editor is best for program creation where the user will have the flexibility of differentiating the
keywords and text what the user enters.
To run vim you can use the followingsyntax:
vim path_filename.c
Shortcuts:
Shift+:+w --- to save the file contents
Shift+:+q --- to Quit the editor without saving the contents of file.
Shift+:+wq --- to save contents and quit the editor
Running Programs in vim Editor:
1. To open the file, at the command prompt type --- vim filename.c
2. Create the program and save the file and quit --- Shift+:+wq
3. At the command prompt type
C99/gcc filename.c
Above command is used to compile the program to generate object code.
4. To run the program type
./a.out(executable file)
Configuration:
vim is a highly configurable editor, and it is best to configure vim to your liking as vim by default
has all the nice features turned off. A list of files and their locations are given below.
~/.vimrc is the vim configuration file which vim reads on startup
~/.vim/ is the directory in which the user can add utility plugins, syntax highlighting
plugins, and indent plugins.
Sample .vimrc file
" Turn on line numbering. Turn it off with "set onu" set nu
" Set syntax on
syntax on
" Indent automatically depending on filetype
filetype indent on
set auto indent
Programming for Problem Solving Lab
Page 17
BVRIT HYDERABAD College of Engineering for Women
Basic UNIX Commands used:
man command:
man commandname --- shows you the manual page for the command
ls command:
ls --- lists your files in the directory
ls-l --- lists our file in long format, it gives information about size of file, owner of
file, rights for file and last modified time.
Copy command:
cp filename1 filename2 --- copies contents of file1 to file2, where both file1 and file2 will have
same content.
Move command:
mv filename1 filename2 --- moves contents of file1 to file2 and file1 contents will be erased.
Remove command:
rm filename --- removes a file. It is wise to use the option rm -i, which will ask you for
confirmation before actually deleting anything.
Programming for Problem Solving Lab
Page 18
BVRIT HYDERABAD College of Engineering for Women
INTRODUCTION TO ‘C’ CONCEPTS
Keywords in C:
Auto Break Case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
Standard Input / Output functions in C:
SCANF - Read formatted data from stdin(standard input device)
Reads data from stdin and stores them according to the parameter format into the locations
pointed by the additional arguments. The additional arguments should point to already allocated
objects of the type specified by their corresponding format tag within the format string.
PRINTF - Print formatted data to stdout(standard output device)
Writes to the standard output (stdout) a sequence of data formatted as the format argument
specifies. After the format parameter, the function expects at least as many additional arguments as
specified in format.
printf ("Characters: %c %c n", 'a', 65);
Common format specifiers in control string for printf and scanf functions are
%d--- for reading integer data
%f --- for reading float data
%c--- for reading character data
%s--- for reading strings
%ld--- for reading double data
CONTROL STATEMENTS
IF Statement: The if statement controls conditional branching. The body of an if statement is
executed if the value of the expression is nonzero. The syntax for the if statement has two forms.
selection-statement:
if ( expression ) statement
Programming for Problem Solving Lab
Page 19
BVRIT HYDERABAD College of Engineering for Women
if ( expression ) statement else statement
In both forms of the if statement, the expressions, which can have any value except a
structure, are evaluated, including all side effects.
In the first form of the syntax, if expression is true (nonzero), statement is executed. If
expression is false, statement is ignored. In the second form of syntax, which uses else, the second
statement is executed if expression is false. With both forms, control then passes from the if
statement to the next statement in the program unless one of the statements contains a break,
continue, or goto.
FOR Statement: The for statement lets you repeat a statement or compound statement a specified
number of times. The body of a for statement is executed zero or more times until an optional
condition becomes false. You can use optional expressions within the for statement to initialize
and change values during the for statement's execution.
Syntax:
iteration-statement:
for ( init-expression opt ; cond-expression opt ; loop-expression opt )statement
Execution of a for statement proceeds as follows:
1. The init-expression, if any, is evaluated. This specifies the initialization for the loop. There
is no restriction on the type of init-expression.
2. The cond-expression, if any, is evaluated. This expression must have arithmetic or pointer
type. It is evaluated before each iteration. Three results are possible:
o If cond-expression is true (nonzero), statement is executed; then loop-expression, if
any, is evaluated. The loop-expression is evaluated after each iteration. There is no
restriction on its type. Side effects will execute in order. The process then begins
again with the evaluation of cond-expression.
o If cond-expression is omitted, cond-expression is considered true, and execution
proceeds exactly as described in the previous paragraph. A for statement without a
cond-expression argument terminates only when a break or return statement
within the statement body is executed, or when a goto (to a labeled statement
outside the for statement body) is executed.
o If cond-expression is false (0), execution of the for statement terminates and control
passes to the next statement in the program.
A for statement also terminates when a break, goto, or return statement within the statement
body is executed. A continue statement in a for loop causes loop-expression to be evaluated. When a
break statement is executed inside a for loop, loop-expression is not evaluated or executed.
WHILE Statement: The while statement lets you repeat a statement until a specified expression
becomes false.
Programming for Problem Solving Lab
Page 20
BVRIT HYDERABAD College of Engineering for Women
Syntax:
iteration-statement:
while ( expression ) statements
The expression must have arithmetic or pointer type. Execution proceeds as follows:
1. The expression is evaluated.
2. If expression is initially false, the body of the while statement is never executed, and
control passes from the while statement to the next statement in the program.
3. If expression is true (nonzero), the body of the statement is executed and the process is
repeated beginning at step 1.
The while statement can also terminate when a break, goto, or return within the statement
body is executed. Use the continue statement to terminate an iteration without exiting the while loop.
The continue statement passes control to the next iteration of the while statement.
DO WHILE Statement: The do-while statement lets you repeat a statement or compound statement
until a specified expression becomes false.
Syntax:
iteration-statement:
do statements while ( expression ) ;
The expression in a do-while statement is evaluated after the body of the loop is executed.
Therefore, the body of the loop is always executed at least once.
Programming for Problem Solving Lab
Page 21
BVRIT HYDERABAD College of Engineering for Women
The expression must have arithmetic or pointer type. Execution proceeds as follows:
1. The statement body is executed.
2. Next, expression is evaluated. If expression is false, the do-while statement terminates and
control passes to the next statement in the program. If expression is true (nonzero), the
process is repeated, beginning with step 1.
The do-while statement can also terminate when a break, goto, or return statement is executed within
the statement body.
Programming for Problem Solving Lab
Page 22
BVRIT HYDERABAD College of Engineering for Women
STEPS IN PROGRAM DEVELOPMENT
In today‟s world, a computer is used to solve various types of problems, because it takes very less time
as compared to a human being. The following steps are performed while solving a problem:
Define the problem Outline the solution
Develop the outline into an algorithm
Test the algorithm into a programming language Code the algorithm into a programming
language. Run the program on computer
Document and maintain the program
Programming for Problem Solving Lab
Page 23
BVRIT HYDERABAD College of Engineering for Women
C Program Compilation Process
Programming for Problem Solving Lab
Page 24
BVRIT HYDERABAD College of Engineering for Women
Descriptions of the steps follow below:
Design and Code
Involves designing a program to meet a specified requirement, and creating the programming
language text files that will comprise the program source.
Compile
After checking for syntactical correctness, converts the programming language source files
into machine readable instructions, where C variables are associated with memory addresses, and C
statements are turned into a series of machine language instructions. The compiler can produce
various forms of output, depending on the compiler options selected.
Linkage Editor
Links compiler output with external modules requested by the compiled program. C
programs can use routines from C libraries or any object or archive file from the IBM XL family of
languages. C programs can also use modules produced by the current or previous compilations. As
well as linking the external modules, the linkage editor resolves addresses within the objectmodule.
Run and Test
This stage can be both the final step in program Development, or it can be an intermediate
point in the program design and implementation process. A program‟s design commonly is further
refined as a result of information gathered during testing.
Programming for Problem Solving Lab
Page 25
BVRIT HYDERABAD College of Engineering for Women
a) Write a simple program that prints the result of all the operators available in c.
(Including pre, post, increment, bitwise and, or, not etc.,). Read the requiredoperand
values from standard input.
b) Write a simple program that converts one given data type to another using auto
conversion and casting. Take the value from standard input.
a) Write a C program to find the max and min from three numbers
LAB CYCLE-1
Practice Session
Step 1: Start
Step 2: Take two operands „A‟ and „B‟ from standard input.
Step 3: Apply operators of c on „A‟ and „B‟.
Step 4: Print output values using printf statement.
Step 5: End.
Step 1:
Step 2:Declare a , b as integer and c,d as float
Step 3: Read a and b
Step 4: compute c=a/b /*auto conversion, as a/b is assigned to c where c is float so the final
result will be in float */
Step 5:d can be assigned in following way
d=(float)a/b; /*Type casting, here explicitly we are converting the type of a and b into float
Simple Numeric Problems
STEP 1: start
Step 2:Read a,b &c
Step 3:Calculate max using Ternary Operator
max=(a>=b&&a>=c)?a:(b>=a&&b>=c)?b:c
Claculate min using Ternary Operator
min=(a<=b&&a<=c)?a:(b<=a&&b<=c)?b:c;
Step 4: Print max and min
STEP 5: End
Programming for Problem Solving Lab
Page 26
BVRIT HYDERABAD College of Engineering for Women
Step 1:Input principle amount. Store it in some variable say principle.
Step 2:Input time in some variable say time.
Step 3: Input rate in some variable say rate.
Step 4: Calculate compound interest using formula, CI = principle * pow((1 + rate / 100), time).
Step 5: Finally, print the resultant value of CI.
C Program to find the simple interest
Step 1:Start
Step 2:Read Principal Amount, Rate and Time
Step 3:Calculate Interest using formula SI= ((amount*rate*time)/100)
Step 4:Print Simple Interest
Step 5:Stop
C Program to find the compound interest
Step 1: Start
Step 2: Input percentage P from standard input
Step 3: Initialize a switch case or if-else ladder to write below conditions
i.e if P < 40 then „fail‟
else if P > 40 and P < 60 then „Second Class‟
else if P > 60 and P < 70 then „First Class‟
else „Distinction‟
Step 4: End
c) Write program that declares class awarded for a given percentange of marks ,where
marks < 40%=failed, 40% to 60% = second class, 60 to 70% first class, >= 70% = distinction.
Read percentage from standard input.
b) Write a C program to find the Simple and compound Interest
Programming for Problem Solving Lab
Page 27
BVRIT HYDERABAD College of Engineering for Women
e) Write a program to show the binary equivalent of a given positive number between 0 to 255.
Step 1: Start
Step 2: Input a number N through standard input which is greater than 0 and less than 255.
Step 2: Store the remainder when the number N is divided by 2 in an array.
Step 3: Divide the number by 2.
Step 4: Repeat the above two steps until the number is greater than zero.
Step 5: Print the array in reverse order now.
Step 6: End
Step1:Start
Step 2: Input number n and rows r from standard Input.
Step 3:Intialize For loop
I=1;I<=r;I++
Print n*I
Step 4: End
Expression Evaluation
a) A building has 10 floors with a floor height of 3 meters each. A ball is dropped from thetop
of the building. Find the time taken by the ball to reach each floor. (Use the formula s
=ut+(1/2)at^2 where u and a are the initial velocity in m/sec (= 0) and acceleration in m/sec^2
(= 9.8 m/s^2)).
Step 1:- start
Step 2:- take u=0,a=9.8
Step 3:- Set s=3,t=0
Step 4:- for(i=1;i<=10l;i++,s+3)
t=u+sqrt(u*u+2*a*s)
print t ,s ,i
Step 5:- stop
d) Write a C program that prints a multiplication table for a given number andthe
number of rows in the table.
For e.g.
For a number 5 and rows =3 ,the output should be :
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
Programming for Problem Solving Lab
Page 28
BVRIT HYDERABAD College of Engineering for Women
b) Write a ’C’ program which takes two integer operands and one operator from theuser,
performs the operation and the prints the result.(consider the operators +,-,*,/,% and use
switch statement).
Algorithm
Step 1:- start
Step 2:- read a,b,ch
Step 3:- switch(ch)
(a) case 1 :
c=a+b
Print c
break;
(b)case 2 :
c =a-b
Print c
break;
(c)case 3 :
c=a*b
Print c
break;
(d) case 4 :
c=a/b
Print c
break;
(e)case 5:
c=a%b
Print c
break;
Step 4:- stop
c) Write a ‘C’ program to find out given number is prime number or not.
Algorithm
Step 1: start
Step 2: read num,flag=0
Step 3:
(a)for(i=2;i<num/2;i++)
(i)if(num%i==0)
flag++
(b)if(flag==0)
Print Prime
Else
Print NoPrime
Step 4:- stop
Programming for Problem Solving Lab
Page 29
BVRIT HYDERABAD College of Engineering for Women
d) Write a ‘C’ program to find the sum of individual digits of a positive integer and testgiven
number is palindrome or not
Algorithm
Step 1: start
Step 2: take sum=0,rev=0
Step 3: read n,num=n
Step 4: while (n>0)
(a) r=n%10
(b)Sum=sum+ r
c)rev=rev+r*10
(d) n=n/10
Step 5: if(num==rev)
Step 6: print palindrome
Step 7: else
Step 8: print Not Palindrome
Step 6: stop
e) A Fibonacci Sequence is defined as follows: the first and second terms in the sequence are0
and 1.Subsequent terms are found by adding the preceding two terms in the sequence
.Write a ‘C’ program to generate the first n terms of the sequence.
Algorithm
Step 1: start
Step 2: let a=0,b=1
Step 3: read n
Step 4: print a,b
Step 5: for(i=3;i<=n;i++)
(a) c=a+b
(b)print c
(c)a=b
d) b=c
step 6: stop
f) Write a ‘C’ program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user.
Algorithm
Step 1: start
Step 2: read n
Step 3: for(i=1;i<n;i++)
(a)for(j=2;j<i;j++)
(i)if(i%j==0)
m++
(b)if(m==0)
Print i
(c) m=0
Step 4:- stop
Programming for Problem Solving Lab
Page 30
BVRIT HYDERABAD College of Engineering for Women
g) Write a ‘C’ program to find the roots of a quadratic equation.
Algorithm
Step 1: start
Step 2: read a,b,c
Step 3: d=b*b-4*a*c
Step 4: if(d>0)
(i)
(a) root1=(-b+sqrt(d))/(2*a)
(b) root2=(-b-sqrt(d))/(2*a)
(c)print root1,root2
(d)print roots are real
Else
if(d==0)
(i)
(a) root1=-b/(2*a)
(b) root2=-b/(2*a)
(c)print root1,root2
(d)print roots are equal
Else
(ii) print roots are imaginary
Step 5: stop
h) Write a ‘C’ program to calculate the following ,where x is fractionalvalue.
sum=1-x/2+ x2/4-x3/6
Algorithm
Step 1: start
Step 2: take sum=1,k=1
Step 3: read x as real value
Step 4: a)for(i=1 ,j=2;i<=3;i=i++,j+2)
(b)sum=sum+pow(x,i)/j;
Step 5: print sum
Step 6: stop
i) Write a ‘C’ program to read in two numbers, x and n, and then compute the sum ofthis
geometric progression:
1+x+x2+x3+ ................+xn For example: if n is 3 and x is 5, then the program computes
1+5+25+125.
Algorithm
Step 1: Start
Step 2: Sum=0
Step 3: Read x
Step 4: Read n
Step 5: Repeat step 6 to 7 until i>n
Step 6: Sum =sum+(x)^i
Step 7: i=i+1
Step 8: Print sum
Step 9: Stop
Programming for Problem Solving Lab
Page 31
BVRIT HYDERABAD College of Engineering for Women
LAB CYCLE - 2
Arrays and Pointers and Functions
a. Write a C program to find the minimum, maximum and average in an array of integers.
Algorithm
Step 1: Start
Step 2: Enter the array elements
Step 3: Initialize Max= a[0] , Min =a[0],Sum=0;
Step 4: Check each from first element whether they are greater than Max or not
For (i=1;i<n;i++)
{
if(a[i]>Max)
{
Max=a[i]
}
Check each from first element whether they are less than Min or not
For (i=1;i<n;i++)
{
if(a[i]<Min)
{
Min=a[i]
}
Step 5: Perform Summation for each arrayelements
for(i=0;i<n;i++)
{
Sum=Sum+a[i];
}
Step 6: Calculate average
Avg= Sum/n
Step 7:Print Max,Min,Sum,Avg
b. Write a functions to compute mean, variance, Standard Deviation, sorting of n elementsin
single dimension array.
Algorithm
Step 1: Initialize sum and sum 1 to 0
Step 2: Read array elements with all real numbers
Step 3: Compute the sum of all elements
for(i=0; i<n; i++){
sum = sum + x[i];
}
Step 4: Find Mean
Programming for Problem Solving Lab
Page 32
BVRIT HYDERABAD College of Engineering for Women
Step 6: Check each two adjust elements then swap with each other in ascending order
Mean= sum /(float) n;
Step 5: Compute variance var and standard deviation SD
for(i=0; i<n; i++)
{
sum1 = sum1 + pow((x[i] - avrg),2); /* calculate the variance using general equation */
}
var = sum1 / (float) n;
SD = sqrt(var); /* calculating standard deviation */
for(i=1;i<=n-1;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
Step 7: Continue with all the passes until all the elements are sorted in the array
step 8: print After sorting, the element are
step 9: for(i=0;i<n;i++)
print a[i]
step10: end
c. Write a C program that uses functions to perform the following:
Addition of Two Matrices
i. Addition of Two Matrices
Algorithm
Step 1: Start
Step 2: Repeat step 3 for i=1 to 3 insteps of 1
Step 3: Repeat step 4 for j=1 to 3 insteps of 1
Step 4. Read A[i][j]
Step 5: Repeat step 6 for i=1 to 3 insteps of 1
Step 6: Repeat step 7 for j=1 to 3 insteps of 1
Step 7: Read B[i][j]
Step 8: Repeat step 9 for i=1 to 3 insteps of 1
Step 9: Repeat step 10 for j=1 to 3 insteps of 1
Step 10: Read C[i][j] = A[i][j] + B[i][j]
Step 11: Print C[i][j]
Step 12: Stop
Programming for Problem Solving Lab
Page 33
BVRIT HYDERABAD College of Engineering for Women
ii. Multiplication of Two Matrices
Algorithm
Step 1: Start
Step 2: Repeat step 3 for i=1 to 3 insteps of 1
Step 3: Repeat step 4 for j=1 to 3 insteps of 1
Step 4: Read A[i][j]
Step 5: Repeat step 6 for i=1 to 3 insteps of 1
Step 6: Repeat step 7 for j=1 to 3 insteps of 1
Step 7: Read B[i][j]
Step 8: Repeat step 9 for i=1 to 3 insteps of 1
Step 9: Repeat step 10 to 13 for j=1 to 3 insteps of 1
Step 10: C[i][j]=0
Step 11: Repeat step12 for k=1 to 3 insteps of 1
Step 12: C[i][j]= C[i][j]+ A[i][k]* B[k][j]
Step 13: Print C[i][j]
Step 14: stop
iii. Transpose of a matrix with memory dynamically allocated for the new matrix as rowand
column counts may not be same.
Algorithm:
Step 1: start
Step 2: read matrix size m,n
Step 3: read matrix elements
for(i=0;i<m;i++)
for(j=0;j<n;j++)
read a[i][j]
Step 4: print The Matrix is
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
print a[i][j]
print "n"
}
Step 5: for(i=0;i<m;i++)
{
for(j=i+1;j<n;j++)
{
temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
Step 6: print The Matrix after transpose,is
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
print a[i][j]
Programming for Problem Solving Lab
Page 34
BVRIT HYDERABAD College of Engineering for Women
print "n"
}
Step 7: end
d. Write C programs that use both recursive and non-recursivefunctions
i)To find the factorial of a given integer.
Algorithm without recursion Algorithm with recursion
1. Start 1. start
2. Read n 2. read n
3. f=1 3. if(n>0)
4. for i=1 repeat step 5 until i>n 4. fact=fact(n)
5. f=f*I 5. read i=1,fact=1
6. print „factorial is‟,f 6. if(i<=n)
7. stop 7. fact=fact*i
8. i=i+1
9. display fact
ii) To find the GCD (greatest common divisor) of two given integers.
Algorithm with recursion Algorithm without recursion
1. GCD( int small , int large) 1. Read a,b
{ 2. function call gcd(a,b)
2. While(( large % small )!=0) 3. function called gcd(m,n)
{ 4. if(m<n)
3. Int tmp = large % small; 5. return gcd(n,m)
4. large=small 6. if(n==0)
5. Small=tmp; 7. return m
} 8. return gcd(n,m%n)
Return small;
}
Programming for Problem Solving Lab
Page 35
BVRIT HYDERABAD College of Engineering for Women
iii ) To find x^n
Algorithm with recursion
def power(x, n):
if n == 0:
return 1
else if n == 1:
return x
else if n % 2 == 0:
return power(x*x, n / 2)
else:
return x*power(x*x, (n-1) /2)
Algorithm without recursion
Step 1: Start
Step 2: Read base and exponent
Step 3: Initialize result=1
Step 4: while (exponent > 0) perform step 5 to step 8
Step 5: while ((exponent & 1) == 0) perform step 6
Step 6: exponent =exponent/2
base=base*base
Step 7: Perform exponent - -
Step 8: Result=result*base
Step 9: Print result
Step 10: End
e) Write a program for reading elements using pointer into array and display the values using
array.
Step 1: Start
Step 2: Read elements
for(i = 0; i < n; ++i)
{
scanf("%d", data + i);
}
Step 3: Print elements
for(i = 0; i < 5; ++i)
{
printf("%dn", *(data + i));
}
f) Write a program for display values reverse order from array using pointer.
Algorithm
Step 1: Start
Step 2: Assign address of first element to pointer variable
ptr = &arr[0];
Step 3: Enter the size of array and array elements
for (i = 0; i < size; i++) {
Programming for Problem Solving Lab
Page 36
BVRIT HYDERABAD College of Engineering for Women
scanf("%d", ptr);
ptr++;
}
Step 4: Assign last element address to pointer to access the array in reverse order
ptr = &arr[size - 1];
Step 5: Print Elements of array in reverse order
for (i = size - 1; i >= 0; i--) {
printf("nElement%d is %d : ", i, *ptr);
ptr--;
}
Step 6: End
g)Write a program through pointer variable to sum of n elements fromarray.
Algorithm
Step 1: Start
Step 2: Initialize sum = 0;
Step 3: Read Array elements
Step 4: Assign ptr to base address
ptr = numArray; /* a=&a[0] */
Step 5: Perform addition for array elements using pointer
for (i = 0; i < 10; i++) {
sum = sum + *ptr;
ptr++;
}
Step 6: Print sum
Step 7:End
Files
a) Write a C program to display the contents of a file to standard output device.
Algorithm
Step 1: Start
Step 2: Open file f1 in read mode with file pointer fp
Step 3: While not end of file f1 do the steps 5 to 6
Step 4: putchar(fp,stdout)
Step 5: Close the files f1
Step 6: Stop
b. Write a C program which copies one file to another, replacing all lowercase characters with
their uppercase equivalents
Algorithm
Step 1: Start
Step 2: Open file f1 in read mode
Step 3: Open file f2 in write mode
Step 4: While not end of file f1 do the steps 5 to 6:
Step 5: ch = read a char from f1
Programming for Problem Solving Lab
Page 37
BVRIT HYDERABAD College of Engineering for Women
Step 6: if (islower(ch))
ch=ch-32
Step 7: Copy ch into file f2
Step 8: Close the files f1,f2
Step 9 :Stop
c. Write a C program to count the number of times a character occurs in a text file.
The file name and the character are supplied as command-line arguments.
Algorithm
Step1: Start
Step2: argv[0] is filename argv[1] is character to search
Step3: count=0
Step4: Open the file in read mode
Step5: c= argv[1][0]
Step6: while(ch=fgetc(fp) && ch !=EOF&& ch== c)
Step7: Count ++
Step8: Close the file
Step9: Display count
d) Write a C program for the following.
It should first create a binary file and store 10 integer values ,where file name and 10 values are
given in the command line .Now program ask for the index and value from the user and value at that
index should be changed to the new value in the file .The program should read all 10 values and print
them back.
Algorithm:
Step1: Start
Step2: argv[0] is filename argv[1] to argv[10] are 10 values.
Step3: read character in to ch
Step4: open the file with file pointer fp in w+ mode
Step5:read n (n is index value)
Step6: move to nth character using fseek( fp, n, SEEK_SET );
Step7: replace the character using fputc(ch, fp);
Step8:Adust cursor to last position of file using seek(p,0,SEEK_END)
Step9: Read and display contents of file using fgetc()
Step10:Stop.
e. Write a C program to merge two files into a third file (i.e., the contents of the firs t file
followed by those of the second are put in the third file).
Algorithm
Step 1: Start
Step 2: Read file pointers fs,ft
Step 3: Open a file in read mode with file pointer fs
Step 4: Open a file in write mode with file pointer ft
Step 5: Check file pointer with arguments passed till null
Step 6: If NULL display file cannot be opened,close fs
Programming for Problem Solving Lab
Page 38
BVRIT HYDERABAD College of Engineering for Women
Step 7: Check the condition with argv[1](file name) then do steps 8 to 10
Step 8: Read charecters of file fs to ft
Step 9: If EOF,break
Step 10: Display contents ( copied content)
Step 11: Close two files
Step 12: Stop
Programming for Problem Solving Lab
Page 39
BVRIT HYDERABAD College of Engineering for Women
LAB CYCLE - 3
Strings
a) Write a C program to convert a Roman numeral to its decimal equivalent.
Algorithm:
Step 1: Start
Step 2: read the roman numerical as string
Step 3: find length of roman numerical
Step 4: for each charcter in the string
i) if(char = I) then decimal = 1
ii) if(char = V) then decimal = 5
iii) if(char = X) then decimal = 10
iv) if(char = L) then decimal = 50
v) if(char = C) then decimal = 100
vi) if(char = D) then decimal = 500
vii) if(char = M) then decimal = 1000
viii) otherwise invalid character
Step 5: repeat step 4 until the length of the string
Step 6: k = char[length - 1]
Step 7: for each character of decimal string
i) if(decimal[i] > dec[i - 1]) then k = k - decimal[i - 1]
ii) else if(decimal[i] = decimal[i - 1 or decimal[i] < decimal[i - 1) then k = k + decimall[i - 1]
Step 8: repate step 7 until the length of decimal string
Step 9: print decimal value
Step 10: Stop
b. Write a C Program to convert number ranging from 1 to 50 to roman equivalent.
Algorithm
Step 1: Start
Step 2: Read input value between 1 to 50 from user.
Step 3: ten = ((input/10)%10)*10;
Step 4: one = ((input/1)%10)*1;
//checking for tens
Step 5: if(ten==10)
Step6: print("X");
Step 7: else if(ten==20)
Step 8: print("XX");
Step 9: else if(ten==30)
Step 10: print("XXX");
Step 11: else if(ten==40)
Step 12: print("XL");
Step 13: else if(ten==50)
Step 14: print("L");
Step 15: else if(ten==60)
Step 16: print("LX");
Step 17: else if(ten==70)
Step 18: print("LXX");
Programming for Problem Solving Lab
Page 40
BVRIT HYDERABAD College of Engineering for Women
Step 19: else if(ten==80)
Step 20: print("LXXX");
Step 21: else if(ten==90)
Step 22: print("XC");
Step 23: if(one==1)
Step 24: print("I");
Step 25: else if(one==2)
Step 26: print("II");
Step 27: else if(one==3)
Step 28: print("III");
Step 29: else if(one==4)
Step 30: print("IV");
Step31: else if(one==5)
Step32: print("V");
Step 33: else if(one==6)
Step34: print("VI");
Step 35: else if(one==7)
Step 36: print("VII");
Step 37: else if(one==8)
Step 38: print("VIII");
Step 39: else if(one==9)
Step 40: print("IX");
Step 41: Stop
c. Write a C program that uses functions to perform the following operations:
1. to insert a sub-string into a given main string from a given position.
2. to delete n characters from a given position in a given string.
1) To insert a sub string into a given main string from a given position
Algorithm
Step 1. start
Step 2. read str1,str2,str3,position
Step 3. strncpy of str3,str1,position
Step 4. strcat of str3,str2
Step 5. strcpy of str3,str1+position
Step 7. print str3
Step 8. stop
Programming for Problem Solving Lab
Page 41
BVRIT HYDERABAD College of Engineering for Women
2) Delete n characters from string
Algorithm
Step 1. start
Step 2. read str1,pos,n,m
Step 3. calculate m=strlen(str1)
Step 4. if pos > m
Step 5. print deletion not possible
Step 6. else j=pos;
Step 7. for(i=pos+n; i<=m; i++){
Step 8. str1[j]=str1[i];
Step 9. j++;}
Step 10. print str1
Step 11. Stop
d) Write a C program to determine if the given string is a palindrome or not.
Algorithm
Step 1. start
Step 2. read s1
Step 3. i=0
Step 4. repeat step 5 to 6 until s1[i]==‟0‟
Step 5. s2[i]=s1[i]
Step 6. i=i+1
Step 7. length=I
Step 8. repeat step 9 from j=0 to i
Step 9. if s1[j]<>s2[j]
Step 10. print „string is not palindrome‟
Step 11. else print „string is palindrome‟
Step 12. Stop
e) Write a C program that displays the position of character ch in the string S , or – 1 if S
doesn’t contain ch.
Algorithm
Step 1: Start
Step 2: read the string and then displayed
Step 3: read the character „ch‟ to be searched and then displayed
Step 4: searching the string ch in string S and then perform the following steps
i. found = strstr(S, ch)
ii. if found print the position of character , If not goto step5
Step 5: print the -1
Step 6: Stop
Programming for Problem Solving Lab
Page 42
BVRIT HYDERABAD College of Engineering for Women
f) Write a C program to count the lines, words and characters in a given text.
Alogrithm
Step 1: Start
Step 2: Read the text until an empty line
Step 3: Compare each character with newline char „n‟ to count no of lines
Step 4: Compare each character with tab char „t‟ or space char „ „ to count no of words
Step 5: Compare first character with NULL char „0‟ to find the end of text
Step 6: No of characters = length of each line of text
Step 7: Print no of lines, no of words, no of chars
Step 8: Stop
Miscellaneous
a. Write a menu driven C program that allows a user to enter n numbers and then choose
between finding the smallest, largest, sum, or average. The menu and all the choices are to be
functions. Use a switch statement to determine what action to take. Display an error message if
an invalid choice is entered.
Algorithm
Step1. Start
Step 2. read n
Step 3. read the values in to the array a
Step 4. read the choice if it is valid goto step 5 otherwise goto step 11
Step 5. use switch case to select the the menu
1. smallest 2. largest 3. sum 4.average
Step 6.smallest() s=a[i]
for(i=1;i<n;i++){ if(a[i]<s)
s=a[i]
}
return(s)
Step 7. largest()
l=a[i]
for(i=1;i<n;i++){
if(a[i]>l)
l=a[i]
}
return(l)
Step 8. sum()
s=0
for(i=0;i<n;i++){
s+=a[i]
}
return(s)
Programming for Problem Solving Lab
Page 43
BVRIT HYDERABAD College of Engineering for Women
Step 9.average()
s=a[i]
for(i=0;i<n;i++){
s+=a[i]
}
return(s/n)
Step 10. goto step 4
Step 11. display invalid choice
Step 12. stop
a) Write a C program to construct a pyramid of numbers as follows:
1
1 2
1 2 3
Algorithm:
step1: Start
step2: Read rows
step3: initialize i=1
step4: Repeat step 4 through 10 until i<=rows
step5: initialize j=1
step6: Repeat step 6 through 8 until j<=i
step7: print j
step8: end of inner loop
step9: go to next line
step10: end of outer loop
step11: stop.
*
* *
* * *
Algorithm:
step1: Start
step2: Read number num
step3: [initialize]
r=1
step4: Repeat step 4 through 10 until num>=r
step5: [initialize]
c=1
step6: Repeat step 6 through 8 until c<=r
step7: print *
step8: c=c+1
[end of loop step6]
step9: go to next line
step10: r=r+1
Programming for Problem Solving Lab
Page 44
BVRIT HYDERABAD College of Engineering for Women
[end of loop step4]
step11: stop
1
2 3
4 5 6
Algorithm:
step1: Start
step2: Read rows, initialize num=1
step3: [initialize]
i=1
step4: Repeat step 4 through 10 i<=rows
step5: [initialize]
j=1
step6: Repeat step 6 through 8 until j<=i
step7: print num
step8: increment num
[end of inner loop]
step9: go to next line
step10: end of outer loop
step11: stop.
1
2 2
3 3 3
Algorithm:
step1: Start
step2: Read rows
step3: initialize i=1
step4: Repeat step 4 through 10 until i<=rows
step5: initialize j=1
step6: Repeat step 6 through 8 until j<=i
step7: print i
step8: end of inner loop
step9: go to next line
step10: end of outer loop
step11: stop.
*
* *
* * *
* *
*
Programming for Problem Solving Lab
Page 45
BVRIT HYDERABAD College of Engineering for Women
Algorithm:
Step1: Input number of columns to print from user. Store it in a variable say N.
Step2:Declare a variable as loop counter for each column, say columns = 1.
Step3: To iterate through rows, run an outer loop from 1 to N * 2 - 1. The loop structure should look
like for(i=1; i<N*2; i++).
Step4: To iterate through columns, run an inner loop from 1 to columns. The loop structure should
look like for(j=1; j<=columns; j++). Inside this loop print star.
Step5: After printing all columns of a row, move to next line.
Step6: After inner loop check if(i <= N) then increment columns otherwise decrement by 1.
Sorting and Searching:
a. Write a C program that uses non recursive function to search for a Key value in a given
list of integers using linear search method.
Algorithm:
step1: Start
step2: declare integer array
step3: Read number of elements
step4: input elements in to the array
step5: input key value to be searched
step6: compare key value with every element in the array if found print the element
step7: if search reaches last element and key value not found print not found
step8: stop
b .Write a C program that uses non recursive function to search for a Key value in a given
sorted list of integers using binary search method.
Algorithm:
Step1: Find the middle element of the list
Step2: Compare the middle element with the given element.
Step3: If both are equal, return the index of the middle element.
Step4: If they are not equal, then if given element is smaller than middle element, then we must
search for given element in upper half of the list otherwise, we must search in the lower half.
Step5: Now in the smaller list, find the middle element and repeat the process.
c. Write a C program that implements the Bubble sort method to sort a given list of integersin
ascending order.
Algorithm:
void bubblesort(int numbers[],int array_size)
{
int I,j,temp;
for(i=(array_size‐1);i.=0;i‐‐)
{
for(j=1;j<=I;j++)
if(numbers[j‐1]>numbers[j])
Programming for Problem Solving Lab
Page 46
BVRIT HYDERABAD College of Engineering for Women
{
temp=numbers[j‐1];
numbers[j‐1]=numbers[j];
numbers[j]=temp;}}}
d. Write a C program that sorts the given array of integers using selection sort in descending
order
Algorithm:
Step1: start
Step2: enter the number elements to be sorted
Step3: read elements in to the array
Step4: traverse through the array from lower bound and compare adjacent elements.
Step5: if element in lower bound is less than its adjacent then perform swap
Step6: repeat until lower bound is compared with all the elements in the array to get the maximum
element is in the lower bound.
Step7: repeat step 5 &6 until all the elements are in descending order
Step8: print the sorted array
Step9: stop
e. Write a C program that sorts the given array of integers using insertion sort in ascending
order
Algorithm:
1. Start with the result as the first element of the input.
2. Loop over the input until it is empty, "removing" the first remaining (leftmost) element.
3. Compare the removed element against the current result, starting from the highest(rightmost)
element, and working left towards the lowest element.
4. If the removed input element is lower than the current result element, copy that value into the
following element to make room for the new element below, and repeat with the next lowest
result element.
5. Otherwise, the new element is in the correct location; save it in the cell left by copying the last
examined result up, and start again from (2) with the next input element.
f. Write a C program that sorts a given array of names .
Algorithm:
Step1: Start
Step2: Read n
Step3: Read the names into character array name[15][30]
Step4: Declare char temp[30]
Step5: Sort the names using
for (i = 0; i < n - 1 ; i++){
for (j = i + 1; j < n; j++){
if (strcmp(name[i], name[j]) > 0){
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
Programming for Problem Solving Lab
Page 47
BVRIT HYDERABAD College of Engineering for Women
strcpy(name[j], temp);
} }}
Step6: Display the contents of name
Step7: Stop
Programming for Problem Solving Lab
Page 48
BVRIT HYDERABAD College of Engineering for Women
VIVA QUESTIONS
INTRODUCTION TO C
1) What is an algorithm?
2) What is a flowchart?
3) What are the characteristics of an algorithm?
4) What is a procedural oriented language?
5) How can u say C is a middle-level language?
6) What are the steps required to develop a C program?
7) What are the characteristics of C language?
8) What is difference between compiler and interpreter?
9) What is preprocessor directive?
10) When preprocessing is done?
11) Name some of the activities done at the time of preprocessing?
SOLUTIONS:
1. An algorithm is a step by step procedure for calculations, data processing and automated
reasoning.
2. A flowchart is a type of diagram that represents an algorithm or process, showing the steps
as boxes of various kinds, and their order by connecting these with arrows.
3. There are five characteristics as Finiteness, Definiteness, Input, Output , Effectiveness.
4. A language based on functions rather than objects. You code to perform a series of tasks
usually sequentially to achieve an objective, rather than code objects that relate to each
other. Generally less flexible and harder to maintain.
5. C is often called a middle-level computer language as it combines the elements of high-
level languages with the functionalism of assembly language.
6. Edit, Debug, Pre processor, Compiler, Linker.
7. Modularity, Portability, Extendibility, Speed, Flexibility.
8. A compiler translates code from a source language (e.g. C, C++, Java) to a target language,
which can then be executed by a (virtual or physical) machine. And An interpreter reads
code in an interpreted language (e.g. PHP, Perl, JavaScript) and directly executes the
contained instructions.
9. Preprocessor directives, such as #define and #ifdef, are typically used to makesource
programs easy to change and easy to compile in different executionenvironments.
10. Processing done depends on the nature of the preprocessor; some preprocessors are only
capable of performing relatively simple textual substitutions and macro expansions, while
others have the power of full-fledged programming languages.
11. Inclusion of header files, Macro expansion, Conditional compilation, Line control.
Programming for Problem Solving Lab
Page 49
BVRIT HYDERABAD College of Engineering for Women
DATA TYPES AND OPERATORS
1) What is a C token?
2) What is a key word? List different keywords in C language?
3) What is a data type? Give different data types in C.
4) What is the use of typedef?
5) How to declare a constant in C?
6) What is the difference between a constant and a variable?
7) Give some examples of header files in C?
8) Why we include header files in a C program?
9) What are the different types of binary operators in C?
10)List different arithmetic operators and what is their precedence?
11)List different relational operators in C.
12)List different logical operators in C and give their precedence.
13)What is conditional operator? Write the syntax.
14)List different unary operators in C.
15)What is the associativity of assignment operator?
16)What is the use of sizeof operator?
17)What are shorthand assignment operators?
18)What is type casting?
19)List different bit-wise operators. What is the use of bit-wise operators?
SOLUTIONS:
1. In a C source program, the basic element recognized by the compiler is the "token."
A token is source-program text that the compiler does not break down into
component elements as keywords, identifiers, constants, string literals, and operators.
2. A keyword is a reserved word which identifies a syntactic form. Words used in control flow
constructs, such as if, then, and else are keywords. In these languages, keywords cannot
also be used as the names of variables or functions.
3.
compound types. Few Basic data types in C are char, int, float, double.
4. The purpose of typedef is to assign alternative names to existing types, most often
those whose standard declaration is cumbersome, potentially confusing, or likely to
vary from one implementation to another.
5. When you declare a constant it is a bit like a variable declaration except the value
cannot be changed.
6. A constant remains fixed with any kind if change in variation or the quantity where
as variables vary with certain quantities a variable is al location in a memory which
holds a piece of data ,it can be represented by anything apart from numbers. where
as a constant can be any numbers or characters.
7. #include<stdio.h>, #include<string.h>, #include<conio.h>,#define<typedef>.
8. A header file is a file with extension .h which contains C function declarations and
macro definitions and to be shared between several source files.
9. Multiplicative operators, Additive operators, Shift operator, Relative operator,
Equality operator, Bitwise operator, Logical operator.
10. Addition, Subtraction, Division, Multiplication, Module.
Data types refer to an extensive system for declaring variables of different types.
The language itself provides basic arithmetic types and syntax to build array and
Programming for Problem Solving Lab
Page 50
BVRIT HYDERABAD College of Engineering for Women
11. Equal to, Greater than equal to, Less than equal to, Equal.
12. Logical AND &&, Logical OR ||.
13. Expr1 expr2, lvalue1=expr1, expr1?expr2:expr3, expr1|| expr2,expr1 && expr2.
14. Unary plus +a, Unary minus –a.
15. Right to Left
16. The sizeof operator gives the amount of storage, in bytes, required to store anobject
of the type of the operand. This operator allows you to avoid specifying machine-
dependent data sizes in your programs.
17. V= expr, v op=expr, v=v op (expr), x+= y+1, x = x + (y+1).
18. Typecasting is a way to make a variable of one type, such as an int, act like
another type, such as a char, for one single operation.
19. Four commonly used "bitwise operators" in C are: "~", "&", "|", and "^".
These operators are used to manipulate the value of individual bits (1 or 0). There are
also two 'shift' operators that it's important to understand: "<<" and ">>". The latter are
used to 'shift' the position of a bit (or a set of bits) to another location in a multi-bit
value
CONTROL STRUCTURES
1) What are the different branch control statements in C language?
2) Is C a block structured language?
3) What is the meaning of block structured language?
4) What are the different loop control statements in C language?
5) What is the difference between while loop and do-while loop?
6) How to swap two variables?
7) How to swap two variables without using a temporary variable?
8) What is a compound statement? Give an example.
9) Write the syntax of for loop.
10)How a for loop executes?
11)How a nested for loop executes?
12)Differentiate between a for loop and a while loop?
13)What is the purpose of break statement in a loop?
14)What is the purpose of continue statement in a loop?
15)Write the syntax of switch statement.
SOLUTIONS:
.
1. If statements, if else statement, nested if statements
2. Yes C is a structured language.
3. In computer programming, a conceptual tool used to group sequences of statements into
single compound statements and to allow the programmer explicit control over the scope of
the program variables.
4. While, Do While, For Loop, Switch, Break.
Programming for Problem Solving Lab
Page 51
BVRIT HYDERABAD College of Engineering for Women
5.
Initialization, Condition, Update Initialization, Condition, Update Statements are to
be written Separately Statements are to be written Separately
Syntax : Syntax :
while(condition){ do{
statement... statement...
statement... statement...
} } while(condition);
6. C program to swap numbers we will use a temp variable to swap two numbers.
Swapping is used in sorting that is when we wish to arrange numbers in a particular
order either in ascending order or in descending order.
7. The best way to swap two variables is to use a temporary variable. As int a,b,t;
t=a;a=b;b = t;
8. A compound statement (also called a "block") typically appears as the body of another
statement, such as the if statement, for statement, while statement, etc
9. for (Start value; end condition; increase value)statement;
10. The “for loop” loops from one number to another number and increases by aspecified
value each time.
11. Break breaks out of one loop, but you can add a check to the outer loop which
breaks when the inner breaks as bool do break= false; for(..; ! do break &&..;..){
for(….){ if(…){ do break=true; break;}}}
12. In C 'for' and 'while' can be easily replaced by each other:
while(exp)stmt for(;exp;)stmt for(exp1;exp2;exp3)stmt exp1; while(exp2){stmt;exp3}}
13. Objective of the C provides the break statement which breaks out of the current loop and
resumes execution at the code directly after the loop.
14. The continue is another jump statement like the break statement as both the statements
skip over a part of code . But continue statement is somewhat different from break.
Instead of forcing termination, it forces the next iteration of loop to take place, skipping
any code in between. A continue statement will just abandon the current iteration and let
the loop start the next iteration.
15. The switch statement provides a multiway selection control structure to execute a
selected section of code determined by the run-time value of an expression. The
condition is an expression which evaluates to an integer value, which include
signed, unsigned, char, enum, and even Boolean values.
While Loop Do...While Loop
Entry-Controlled Loop Exit-Controlled Loop
Programming for Problem Solving Lab
Page 52
BVRIT HYDERABAD College of Engineering for Women
ARRAYS
1) What is an array?
2) What is the difference between an array and an ordinary variable?
3) What are the properties of array elements?
4) How to initialize one dimensional array?
5) How to initialize two dimensional array?
6) How a one dimensional array stored in memory?
7) How a two dimensional array stored in memory?
8) How can you increase the size of a dynamically allocated array?
9) How can you increase the size of a statically allocatedarray?
10)What is meant by static memory allocation?
SOLUTIONS :
1. An array is a collection of one or more repeated instances of an object, referred to in a special
way, that allows them all to have the same name, as a collection, but to be individually
numbered.
2. The difference between the definition of array and ordinary variable is the, array is always
declared, initialized, and accessed using subscript whereas ordinary variable do not have any
subscript.
3. In C and C++ you add "1" to age (that is, the address of age) to access the second element,
add "2" to age to access the third element, etc. If you hadn't seen the fancy
image showing that each element of age (each short variable) had 2 bytes, then you might
have said "1" and gotten the correct answer.
4. Static int number[3]={5,7,2};
5. Static int months_days [2] [12]= {31,30,28,31};{31,30,30,31,28};
6. The array which is used to represent and store data in a linear form is called as 'single or
one dimensional array.' As syntax: <data-type> <array_name> [size];
Example: int a[3]= {2,3,4};
Char ch[20]=”techno exam”;
Float stax[3]={5003.23,1940.32,123.20};
Total size in bytes: total size- length of array * size of data type;
7. The following syntax is used to represent two dimensional array.
Syntax: <data-type> <array_nm> [row_subscript] [column- subscript];
Example: int a[3] [3];
8. Example: * Allocate space for an array with ten elements of type int. */
int *ptr malloc(10 * sizeof (int));
if (ptr == NULL) { /* Memory could not be allocated, the program should handle the error
here as appropriate. */
9. int arr[10]; When an array is declared as above, memory is allocated for the elements
of the array when the program starts, and this memory remains allocated during the
lifetime of the program. This is known as static array allocation. Hence we cannot
increase size of statically allocated array.
10. Allocation memory at compile time is called as static memory allocation.
Programming for Problem Solving Lab
Page 53
BVRIT HYDERABAD College of Engineering for Women
FUNCTIONS
1) Define function in C?
2) What are the advantages of functions?
3) What are the different types of functions?
4) Give examples of user defined and pre-defined functions.
5) What is function prototype?
6) What is the difference between actual arguments and formal arguments?
7) What is scope and extent of a variable?
8) What is the scope of a global variable?
9) What are different types of storage classes in C?
10)What are register variables?
11)What are the different parameter passing mechanisms in C?
12)What is the difference between call by value and call by reference?
13)Define Recursion?
SOLUTIONS:
1. The function is a self contained block of statements which performs a coherent task of
a same kind. C program does not execute the functions directly. It is required to
invoke or call that functions. When a function is called in a program then program
control goes to the function body. Then, it executes the statements which are involved
in a function body. Therefore, it is possible to call function whenever we want to
process that functions statements.
2. Program testing made easy, program development made easy, code re usability
increases, function facilitates the procedural abstraction.
3. There are five types of functions and they are:
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions that return multiple values.
5. Functions with no arguments and return values.
4. Function definition or task will be implemented by user are know as user defined
function. And pre defined functions are already in built in function such as printf( )
and scanf( ).
5. All identifiers in C need to be declared before they are used. This is true for functions
as well as variables. For functions the declaration needs to be before the first call of
the function. A full declaration includes the return type and the number and type of
the arguments. This is also called the function prototype.
6. Actual arguments:
Programming for Problem Solving Lab
Page 54
BVRIT HYDERABAD College of Engineering for Women
The arguments that are passed in a function call are called actual arguments.These
arguments are defined in the calling function.
Formal arguments:
The formal arguments are the parameters/arguments in a function declaration. The
scope of formal arguments is local to the function definition in which they are used.
Formal arguments belong to the called function. Formal arguments are a copy of the
actual arguments. A change in formal arguments would not be reflected in the actual
arguments
7. The scope of a declaration is the region of C program text over which that declaration
is active.Top-level identifiers – Extends from declaration point to end of file and The
extent of an object is the period of time that its storage is allocated. An object is said
to have static extent when it is allocated storage at or before the beginning of program
execution and the storage remains allocated until program termination. All functions
have static extent, as do all variables declared in top-level declarations and variables
declared with the static qualifier.
8. The C language does not have a global keyword. However, variables declared
outside a function implicitly have a scope covering everything in the .c file or
compilation unit containing its declaration. In a small program contained in a single
file, such variables effectively have global scope.
9. Generally four types of storage classes are there in c.
1.Auto
2.Register
3.Static
4.Extern or Global
10. Register variables are a special case of automatic variables. Automatic variables
are allocated storage in the memory of the computer; however, for most
computers, accessing data in memory is considerably slower than processing in the
CPU. These computers often have small amounts of storage within the CPU itself
where data can be stored and accessed quickly. These storage cells are called
registers.
11. A parameter passing mechanism is a mechanism or facility which is provided by a
programming language to pass data (i.e. parameters) between a caller and a callee.
reach out and touch
call by value
call by result or call by return(?)
call by value result or call by value return
call by reference
call by name
12. Call By Value: Creates a new memory location for use within the
subroutine. The memory is freed once it leaves the subroutine. Changes made to
the variable are not affected outside the subroutine. Call By Reference: Passes a
pointer to the
Programming for Problem Solving Lab
Page 55
BVRIT HYDERABAD College of Engineering for Women
memory location .Changes made to the variable within the subroutine affects the
variable outside the subroutine.
13. The function which calls the same function, is known as recursive function.
Ex: recursionfunction(){
recursionfunction();//calling self function
}
Programming for Problem Solving Lab
Page 56
BVRIT HYDERABAD College of Engineering for Women
STRINGS
1) What is a string?
2) What is the difference between Strings and Arrays?
3) How to initialize a string?
4) How to read a line of text?
5) List predefined string handling functions in C.
6) Explain strcmp() function.
7) How to process array of strings?
SOLUTIONS:
1. A string is a collection of characters. Strings are always enclosed in double quotes as
"string_ constant".
2. A data item (or variable) is described as a "string" type when it contains some number of
characters. Those characters can usually be anything in the system's accepted list of
codes. Most systems use ASCII, so a string can include the letters a-z, A-Z, numbers 0-9,
and special characters like ~!@#$%^&*()_+-=[]{}|:";'<>?,/. A string is treated as a
single object, although most programming languages have methods to break strings apart
(called sub-stringing). In the Perl language, strings are named $something.
An array is a collection of individual data items, sort of like a list. Each element in an
array can be referred to in a program by its position in the list. In the Perl language, an
array would be named @SOMETHING. The first element in the array would be
named $SOMETHING[0], the second $SOMETHING[1], and so on. Each element can
be a string, or some other data type.
3. The string is created and initialized at the same time. For example: char string[] =
"Hello there, Nerdly.";
4. In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length
of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed
of getting all lines.
5. Any set or sequence of characters defined within double quotation symbols is a constant
string.In c it is required to do some meaningful operations on the strings are str len( ),
str cmp( ), str cpy( ), str cmpi( ),str lwr( ), str rev( ).
6. Strcmp will test two strings for equallity.
Returns : < 0 if s1 is less than s2
0 if s1 == s2
> 0 if s1 is greater than s2
This function probably provides too much information by indicating which string is
lexicographically greater. The net result means that the strcmp return code is logically
incorrect because it returns a FALSE value when the strings match.
7. char * [100] var ; // declaration or
char ** var; char *[] var= {"one","two","three"}; // initialize directly
use loop either for or while
for(int i = 0 ;i < no_of_string;i++)
printf("%s",var[i]);
Programming for Problem Solving Lab
Page 57
BVRIT HYDERABAD College of Engineering for Women
STRUCTURES
1. Define structure. which keyword is used to declare structure
2. What is the array of structure. why it is used
3. How memory is allocated for structure. what is the size of structure
4. What is the difference between structure and union
5. What is the structure within structure
SOLUTIONS:
1. A structure is a collection of one or more variables, possibly of different types, grouped
together under a single name for convenient handling. Structures help to organize complicated
data, particularly in large programs, because they permit a group of related variables to be
treated as a unit instead of as separate entities. keyword is used to declare structure is STRUCT
2. Block of structures is referred as array of structures. It is used to hold data of different
structures
3. Memory is allocated when a structure variable is created and size of structure is sum sizes
of all the fields in a structure.
4. Structure and union use same prototype for declarationbut
keywords used are struct and union.
size of structure is sum sizes of all the fields in a structure where as size of union is size
of the highest data field in structure memory is allocated to all field variable where as
in union all variable share the highest data field‟s memory
5.Strucure with in the structure is called as nested structure .If a structure is having another
structure as its member field then it is called as nested structure
Programming for Problem Solving Lab
Page 58
BVRIT HYDERABAD College of Engineering for Women
FILES
1) What is the use of files?
2) What is the difference between text and binary files?
3) What are the operations that can be performed on files?
4) What are the different modes applied on files?
5) Explain about REWIND() function.
SOLUTIONS:
1.A file is a collection of bytes stored on a secondary storage device, which is generally a disk of
some kind. The collection of bytes may be interpreted, for example, as characters, words, lines,
paragraphs and pages from a textual document; fields and records belonging to a database; or
pixels from a graphical image. File is used to store data permanently.
2. A text file can be a stream of characters that a computer can process sequentially. It is not only
processed sequentially but only in forward direction. For this reason a text file is usually opened
for only one kind of operation (reading, writing, or appending) at any given time.
A binary file is no different to a text file. It is a collection of bytes. r. Hence a binary file is
also referred to as a character stream, but there are two essential differences.
a.No special processing of the data occurs and each byte of data is transferred to or from
the disk unprocessed.
b. C Programming Language places no constructs on the file, and it may be read
from, or written to, in any manner chosen by the programmer.
c. Binary files can be either processed sequentially or, depending on the needs of the
application, they can be processed using random access techniques
3. The operations that can be performed on files are:
Reading (r): When an r is used, the file is opened for reading, a w is used to indicate a file to be
used for writing, and an a indicates that you desire to append additional data to the data already
in an existing file.
Writing (w): When a file is opened for writing, it will be created if it does not
already exist and it will be reset if it does, resulting in the deletion of any data already there.
Using the w indicates that the file is assumed to be a text file.
Appending (a): When a file is opened for appending, it will be created if it does not already exist
and it will be initially empty. If it does exist, the data input point will be positioned at the end of
the present data so that any new data will be added to any data that already exists in the file.
Using the a indicates that the file is assumed to be a text file.
4. The allowed modes for fopen are as follows:
r - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist) r+ - open for reading and writing, start at
beginning w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)
Programming for Problem Solving Lab
Page 59
BVRIT HYDERABAD College of Engineering for Women
5. The rewind function sets the file position to the beginning of the file for the stream pointed to
by stream. It also clears the error and end-of-file indicators for stream.
Q: Explain Sieve of Eratosthenes algorithm with Example.
Given a number n, print all primes smaller than or equal to n. It is also given that n is a small
Number.
For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be
“2, 3, 5, 7, 11, 13, 17, 19”.
The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n.
Following is the algorithm to find all the prime numbers less than or equal to a given integer n by
Eratosthenes‟ method:
1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).
2. Initially, let p equal 2, the first prime number.
3. Starting from p, count up in increments of p and mark each of these numbers greater
than p itself in the list. These numbers will be 2p, 3p, 4p, etc.; note that some of them may
have already been marked.
4. Find the first number greater than p in the list that is not marked. If there was no such
number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat
from step 3.
When the algorithm terminates, all the numbers in the list that are not marked are prime.

More Related Content

What's hot

Lecture 11 Perspective Projection
Lecture 11 Perspective ProjectionLecture 11 Perspective Projection
Lecture 11 Perspective Projection
guest0026f
 
C language industrial training report
C language industrial training reportC language industrial training report
C language industrial training report
Raushan Pandey
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
Soran University
 
CAD Lab model viva questions
CAD Lab model viva questions CAD Lab model viva questions
CAD Lab model viva questions
SHAMJITH KM
 
Anna university-ug-pg-ppt-presentation-format
Anna university-ug-pg-ppt-presentation-formatAnna university-ug-pg-ppt-presentation-format
Anna university-ug-pg-ppt-presentation-format
Veera Victory
 
3D Graphics & Rendering in Computer Graphics
3D Graphics & Rendering in Computer Graphics3D Graphics & Rendering in Computer Graphics
3D Graphics & Rendering in Computer Graphics
Faraz Akhtar
 
3D Transformation
3D Transformation 3D Transformation
3D Transformation
Mahmudul Hasan
 
C programming presentation for university
C programming presentation for universityC programming presentation for university
C programming presentation for university
Sheikh Monirul Hasan
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
Fundamental of 3D modeling
Fundamental of 3D modeling Fundamental of 3D modeling
Fundamental of 3D modeling
Hemant Wagh
 
Presentation on computer science & engineering (cse)
Presentation on  computer science  & engineering (cse)Presentation on  computer science  & engineering (cse)
Presentation on computer science & engineering (cse)
topu93
 
constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++
HalaiHansaika
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
Mahendra Yadav
 
Internship on web development
Internship on web developmentInternship on web development
Internship on web development
Rajendra Kandel
 
Object-Oriented Polymorphism Unleashed
Object-Oriented Polymorphism UnleashedObject-Oriented Polymorphism Unleashed
Object-Oriented Polymorphism Unleashed
Naresh Chintalcheru
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
3 d printing final (1) (1)
3 d printing final (1) (1)3 d printing final (1) (1)
3 d printing final (1) (1)
MahimaKumari7
 

What's hot (20)

Lecture 11 Perspective Projection
Lecture 11 Perspective ProjectionLecture 11 Perspective Projection
Lecture 11 Perspective Projection
 
Sop
SopSop
Sop
 
C language industrial training report
C language industrial training reportC language industrial training report
C language industrial training report
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
CAD Lab model viva questions
CAD Lab model viva questions CAD Lab model viva questions
CAD Lab model viva questions
 
Anna university-ug-pg-ppt-presentation-format
Anna university-ug-pg-ppt-presentation-formatAnna university-ug-pg-ppt-presentation-format
Anna university-ug-pg-ppt-presentation-format
 
3D Graphics & Rendering in Computer Graphics
3D Graphics & Rendering in Computer Graphics3D Graphics & Rendering in Computer Graphics
3D Graphics & Rendering in Computer Graphics
 
3D Transformation
3D Transformation 3D Transformation
3D Transformation
 
C programming presentation for university
C programming presentation for universityC programming presentation for university
C programming presentation for university
 
Function in c
Function in cFunction in c
Function in c
 
Fundamental of 3D modeling
Fundamental of 3D modeling Fundamental of 3D modeling
Fundamental of 3D modeling
 
Presentation on computer science & engineering (cse)
Presentation on  computer science  & engineering (cse)Presentation on  computer science  & engineering (cse)
Presentation on computer science & engineering (cse)
 
Type Casting in C++
Type Casting in C++Type Casting in C++
Type Casting in C++
 
3 D Printers
3 D Printers3 D Printers
3 D Printers
 
constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
Internship on web development
Internship on web developmentInternship on web development
Internship on web development
 
Object-Oriented Polymorphism Unleashed
Object-Oriented Polymorphism UnleashedObject-Oriented Polymorphism Unleashed
Object-Oriented Polymorphism Unleashed
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
3 d printing final (1) (1)
3 d printing final (1) (1)3 d printing final (1) (1)
3 d printing final (1) (1)
 

Similar to PPS Manual_AY_2021-22 I & II Sem.pdf

vtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdfvtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdf
LPSChandana
 
Ade manual with co po-18scheme
Ade manual with co po-18schemeAde manual with co po-18scheme
Ade manual with co po-18scheme
AMC Engineering College
 
ELECTRICAL AND ELECTRONIC ENGINEERING SYLLABUS.pdf
ELECTRICAL AND ELECTRONIC ENGINEERING SYLLABUS.pdfELECTRICAL AND ELECTRONIC ENGINEERING SYLLABUS.pdf
ELECTRICAL AND ELECTRONIC ENGINEERING SYLLABUS.pdf
GaddamMahesh7
 
Presentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeoPresentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeo
epandhari
 
Car Price prediction final pdf1.docx
Car Price prediction final pdf1.docxCar Price prediction final pdf1.docx
Car Price prediction final pdf1.docx
SUMITKUMARBEHERA11
 
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptx
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptxIntroductory PPT CSC202 SECURITY ARCHITECTURE.pptx
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptx
Akash Bhasney
 
Obe nba
Obe nbaObe nba
Obe nba
NirajNair2
 
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdfSDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
priyanshuurkade
 
OS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdfOS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdf
SuperBoy40
 
Dsp lab manual
Dsp lab manualDsp lab manual
Dsp lab manual
amanabr
 
AI_LAB_Manual in c with all the programs
AI_LAB_Manual in c with all the programsAI_LAB_Manual in c with all the programs
AI_LAB_Manual in c with all the programs
drsucharu
 
M.Sc.Syllabus 17 Nov 2022 (1).pdf
M.Sc.Syllabus 17 Nov 2022 (1).pdfM.Sc.Syllabus 17 Nov 2022 (1).pdf
M.Sc.Syllabus 17 Nov 2022 (1).pdf
hsingh5201
 
ds_mod1.pdf
ds_mod1.pdfds_mod1.pdf
ds_mod1.pdf
arjun431527
 
Computer science and information technology
Computer science and information technology Computer science and information technology
Computer science and information technology
Vivek Kumar Sinha
 
Cs8383 oop lab manual-2019
Cs8383 oop lab manual-2019Cs8383 oop lab manual-2019
Cs8383 oop lab manual-2019
Kayathri Devi D
 
FdSc Mechanical Engineering
FdSc Mechanical EngineeringFdSc Mechanical Engineering
FdSc Mechanical Engineering
bwcelearning
 
SE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdf
SRPatel10
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded Systems
RaashidFaiyazSheikh
 
Materials Engineering Digital Notes.pdf
Materials Engineering Digital Notes.pdfMaterials Engineering Digital Notes.pdf
Materials Engineering Digital Notes.pdf
SaiM624606
 

Similar to PPS Manual_AY_2021-22 I & II Sem.pdf (20)

Hdllab1
Hdllab1Hdllab1
Hdllab1
 
vtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdfvtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdf
 
Ade manual with co po-18scheme
Ade manual with co po-18schemeAde manual with co po-18scheme
Ade manual with co po-18scheme
 
ELECTRICAL AND ELECTRONIC ENGINEERING SYLLABUS.pdf
ELECTRICAL AND ELECTRONIC ENGINEERING SYLLABUS.pdfELECTRICAL AND ELECTRONIC ENGINEERING SYLLABUS.pdf
ELECTRICAL AND ELECTRONIC ENGINEERING SYLLABUS.pdf
 
Presentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeoPresentation on po pshjhhjhekhhkkhkhjpeo
Presentation on po pshjhhjhekhhkkhkhjpeo
 
Car Price prediction final pdf1.docx
Car Price prediction final pdf1.docxCar Price prediction final pdf1.docx
Car Price prediction final pdf1.docx
 
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptx
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptxIntroductory PPT CSC202 SECURITY ARCHITECTURE.pptx
Introductory PPT CSC202 SECURITY ARCHITECTURE.pptx
 
Obe nba
Obe nbaObe nba
Obe nba
 
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdfSDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
SDL-LAB-MANUAL-CS606-common-for-all-the-faculties.pdf
 
OS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdfOS lab manual1234512345123451234512345.pdf
OS lab manual1234512345123451234512345.pdf
 
Dsp lab manual
Dsp lab manualDsp lab manual
Dsp lab manual
 
AI_LAB_Manual in c with all the programs
AI_LAB_Manual in c with all the programsAI_LAB_Manual in c with all the programs
AI_LAB_Manual in c with all the programs
 
M.Sc.Syllabus 17 Nov 2022 (1).pdf
M.Sc.Syllabus 17 Nov 2022 (1).pdfM.Sc.Syllabus 17 Nov 2022 (1).pdf
M.Sc.Syllabus 17 Nov 2022 (1).pdf
 
ds_mod1.pdf
ds_mod1.pdfds_mod1.pdf
ds_mod1.pdf
 
Computer science and information technology
Computer science and information technology Computer science and information technology
Computer science and information technology
 
Cs8383 oop lab manual-2019
Cs8383 oop lab manual-2019Cs8383 oop lab manual-2019
Cs8383 oop lab manual-2019
 
FdSc Mechanical Engineering
FdSc Mechanical EngineeringFdSc Mechanical Engineering
FdSc Mechanical Engineering
 
SE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdf
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded Systems
 
Materials Engineering Digital Notes.pdf
Materials Engineering Digital Notes.pdfMaterials Engineering Digital Notes.pdf
Materials Engineering Digital Notes.pdf
 

Recently uploaded

AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 

Recently uploaded (20)

AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 

PPS Manual_AY_2021-22 I & II Sem.pdf

  • 1. Programming for Problem Solving Lab Page 1 BVRIT HYDERABAD College of Engineering for Women BVRIT HYDERABAD College of Engineering for Women The Temple for Women Empowerment & Human Values Approved by AICTE & Affiliated to JNTUH, Hyderabad Nizampet Road, Bachupally, Hyderabad – 500 090, Telangana, India. Student Notebook Department Basic Science and Humanities Year / Semester I B.Tech / I & II Semester Subject Programming for Problem Solving Lab Academic Year(Regulation) 2021-22 (R18) Subject Code CS106ES / CS206ES Vision To emerge as the best among the institutes of technology and research in the country dedicated to the cause of promoting quality technical education. Mission At BVRITH, we Strive to  Achieve academic excellence through innovative learning practices.  Enhance intellectual ability and technical competency for a successful career.  Encourage research and innovation.  Nurture students towards holistic development with emphasis on leadership skills , Life skills and human values.
  • 2. Programming for Problem Solving Lab Page 2 BVRIT HYDERABAD College of Engineering for Women IT - DEPARTMENT VISION To emerge as a Center of excellence in Information Technology and to produce women technocrats, global leaders for better tomorrow. IT - DEPARTMENT MISSION M1: To impart quality education and inculcate problem solving skills using latest Technologies in the field of Information Technology. M2: To encourage multidisciplinary research and consultancy projects. M3: To promote industry academia linkage and also enhance entrepreneurship skills in women engineers. IT- Programme Educational Objectives (PEOs) After three to six years of graduation, the graduates of this program will be able to: PEO 1: Develop strong analytical skills using fundamental concepts of science & engineering subjects. PEO 2: Excel in programming and critical thinking by applying core technical knowledge PEO 3: Exhibit continuous learning related to evolving technologies in their professional career PEO 4: Demonstrate ethical behavior, team work & leadership qualities to solve problems in broader social context.
  • 3. Programming for Problem Solving Lab Page 3 BVRIT HYDERABAD College of Engineering for Women CSE – DEPARTMENT VISION Develop women as technocrats, researchers and entrepreneurs in the field of computer science and engineering. CSE - DEPARTMENT MISSION M1: To impart quality education in Computer Science and Engineering by means of learning techniques and value-added courses. M2: To inculcate professional excellence and research culture by encouraging projects in cutting- edge technologies through industry interactions. M3: To build leadership skills, ethical values and teamwork among the students. M4: To strengthen the collaboration of department and industry through internships, mentorships and professional body activities. CSE -Programme Educational Objectives (PEOs) After three to six years of graduation, the graduates of this program will be able to: PEO–1: Adapt emerging technologies to contribute to the technical innovations for the progressive development in their respective fields. PEO–2: Productively engage in multidisciplinary research areas by applying the basic principles of engineering sciences. PEO–3: Demonstrate strong technical skills to bring out novel designs/products to address the social & environmental issues. PEO–4: Exhibit professional attitude, teamwork and practice code of ethics.
  • 4. Programming for Problem Solving Lab Page 4 BVRIT HYDERABAD College of Engineering for Women ECE - DEPARTMENT VISION To emerge as a centre of academic and research excellence in Electronics and Communication Engineering and create globally competent women technocrats with a high degree of social consciousness in a holistic learning environment ECE - DEPARTMENT MISSION M1: To provide quality education to the students with emphasis on training related to latest technologies as per industrial needs M2: To impart research culture, professional ethics and moral values to the students by committed and competent faculty striving for excellence. M3: To inculcate a perceptive alacrity in students to identify real life problems, formulate strategies and evolve into contextually effective solutions. ECE- Programme Educational Objectives (PEOs) After three to six years of graduation, the graduates of this program will be able to: PEO-1: Excel in contemporary problem solving in Electronics and Communication Engineering and the allied fields through the knowledge-base provided by the programme. PEO-2: Demonstrate their technical, communication and leadership skills in professional environment or as entrepreneurs with social responsibility. PEO-3: Analyze the latest issues and technology growth in the field of Electronics and Communication Engineering and update their knowledge and skills accordingly through continuous learning. PEO-4: Demonstrate ethical and human values in multicultural and multidisciplinary environments
  • 5. Programming for Problem Solving Lab Page 5 BVRIT HYDERABAD College of Engineering for Women EEE - DEPARTMENT VISION To develop comprehensively trained and socially responsible women electrical and electronics engineers with competencies and capabilities to adapt to new challenges. EEE - DEPARTMENT MISSION M1: To empower the students adept at latest technologies by providing innovative learning environment. M2: To cultivate interdisciplinary research mindset and outlook to develop engineering solutions. M3: To inculcate ethical behavior and professional attitude in order to embrace holistic concept of living. EEE - Programme Educational Objectives (PEOs) After three to six years of graduation, the graduates of this program will be able to: PEO–1: Propose effective solutions for complex electrical and electronics engineering problems using modern techniques. PEO–2: Excel in their career and compete with their global peers in Techno-Scientific fields. PEO–3: Exhibit good communication skills, ethical behavior & social perception. PEO–4: Stimulate economic growth and job opportunities through entrepreneurship.
  • 6. Programming for Problem Solving Lab Page 6 BVRIT HYDERABAD College of Engineering for Women JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD PROGRAMMING FOR PROBLEM SOLVING LAB B.Tech I Year I/II Sem. Course Code: CS106ES/CS206ES L T P C 0 0 3 1 CONTENTS 1 Syllabus .………………..…………..……………... 9 2 Instructions to Students …………….……………………………... 14 3 Introduction to UNIX commands ...………………………….……… ……. 15 4 Introduction to C Concepts .…………………………………………... 18 5 Steps in program development ….………………….................................. 22 6 Lab Cycle-1 Algorithms …………………………………………… 25 7 Lab Cycle-2 Algorithms …………………………………………… 31 8 Lab Cycle-3 Algorithms …………………………………………… 39 9 Viva Questions with Solutions …………………………………………… 48 i. Introduction to C ….……………………….......................... 48 ii. Arrays & functions …………………………………………… 52 iii. Strings ………………………. ………………….. 56 iv. Structures ……...….………………………………… 57 v. Files …………………………………………... 58
  • 7. Programming for Problem Solving Lab Page 7 BVRIT HYDERABAD College of Engineering for Women PROGRAMMING FOR PROBLEM SOLVING LAB INTERNAL ASSESSMENT SHEET LIST OF EXPERIMENTS S.No Name of the Experiment Date of Exp done Lab [5M] Record [5M] Viva [5M] Total [15M] Remarks Signature of the Faculty
  • 8. Programming for Problem Solving Lab Page 8 BVRIT HYDERABAD College of Engineering for Women List of Experiments Department Computer Science & Engineering Information Technology Year / Semester I B. Tech (CSE, IT, ECE, EEE, AI&ML) – I & II Semester Subject Programming for Problem Solving Lab Academic Year (Regulation) 2021-22 (R18) Subject Code CS106ES/CS206ES Course Objectives: The students will learn the following: • To work with an IDE to create, edit, compile, run and debug programs • To analyze the various steps in program development. • To develop programs to solve basic problems by understanding basic concepts in C like operators, control statements etc. • To develop modular, reusable and readable C Programs using the concepts like functions, arrays etc. • To Write programs using the Dynamic Memory Allocation concept. • To create, read from and write to text and binary files Course Outcomes: The candidate is expected to be able to: • Design and test programs to solve mathematical and scientific problems. • Apply control structures and functions for structured programs. • Construct programs using the concept of array and pointer to solve the problems. • Build efficient Solution for complex problems by using various programming constructs
  • 9. Programming for Problem Solving Lab Page 9 BVRIT HYDERABAD College of Engineering for Women SYLLABUS CYCLES PROGRAMS CYCLE-1 Practice sessions: a. Write a simple program that prints the results of all the operators available in C (including pre/ post increment, bitwise and/or/not, etc.). Read required operand values from standard input. b. Write a simple program that converts one given data type to another using auto conversion and casting. Take the values form standard input. Simple numeric problems: a. Write a program to find the max and min from the three numbers. b. Write the program for the simple, compound interest. c. Write program that declares Class awarded for a given percentage of marks, where mark <40%= Failed, 40% to <60% = Second class, 60% to <70%=First class, >= 70% = Distinction. Read percentage from standard input. d. Write a program that prints a multiplication table for a given number and the number of rows in the table. For example, for a number 5 and rows = 3, the output should be: 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 e. Write a program that shows the binary equivalent of a given positive number between 0 to 255. Expression Evaluation: a. A building has 10 floors with a floor height of 3 meters each. A ball is dropped from the top of the building. Find the time taken by the ball to reach each floor. (Use the formula s = ut+(1/2)at^2 where u and a are the initial velocity in m/sec (= 0) and acceleration in m/sec^2 (= 9.8 m/s^2)).
  • 10. Programming for Problem Solving Lab Page 10 BVRIT HYDERABAD College of Engineering for Women b. Write a C program, which takes two integer operands and one operator from the user, performs the operation and then prints the result. (Consider the operators +,-,*, /, % and use Switch Statement) c. Write a program that finds if a given number is a prime number d. Write a C program to find the sum of individual digits of a positive integer and test given number is palindrome e. A Fibonacci sequence is defined as follows: the first and second terms in the sequence are 0 and 1. Subsequent terms are found by adding the preceding two terms in the sequence. Write a C program to generate the first n terms of the sequence. f. Write a C program to generate all the prime numbers between 1 and n, where n is a value supplied by the user. g. Write a C program to find the roots of a Quadratic equation. h. Write a C program to calculate the following, where x is a fractional value. 1-x/2 +x^2/4-x^3/6 i. Write a C program to read in two numbers, x and n, and then compute the sum of this geometric progression: 1+x+x^2+x^3+ ................+x^n. For example: if n is 3 and x is 5, then the program computes 1+5+25+125 CYCLE-2 Arrays and Pointers and Functions: a. Write a C program to find the minimum, maximum and average in an array of integers. b. Write a functions to compute mean, variance, Standard Deviation, sorting of n elements in single dimension array.
  • 11. Programming for Problem Solving Lab Page 11 BVRIT HYDERABAD College of Engineering for Women c. Write a C program that uses functions to perform the following: i) Addition of Two Matrices ii) Multiplication of Two Matrices iii) Transpose of a matrix with memory dynamically allocated for the new matrixas row and column counts may not be same. d. Write C programs that use both recursive and non-recursive functions i) To find the factorial of a given integer. ii) To find the GCD (greatest common divisor) of two given integers. iii)To find x^n e. Write a program for reading elements using pointer into array and display the values using array. f. Write a program for display values reverse order from array using pointer. g. Write a program through pointer variable to sum of n elements from array. Files: a. Write a C program to display the contents of a file to standard output device. b. Write a C program which copies one file to another, replacing all lowercase characters with their uppercase equivalents. c. Write a C program to count the number of times a character occurs in a text file. The file name and the character are supplied as command line arguments. d. Write a C program that does the following: It should first create a binary file and store 10 integers, where the file name and 10 values are given in the command line. (hint: convert the strings using atoi function) Now the program asks for an index and a value from the user and the value at that index should be changed to the new value in the file. (hint: use fseek function) The program should then read all 10 values and print them back. e. Write a C program to merge two files into a third file (i.e., the contents of the firs t file followed by those of the second are put in the third file).
  • 12. Programming for Problem Solving Lab Page 12 BVRIT HYDERABAD College of Engineering for Women CYCLE-3 Strings: a. Write a C program to convert a Roman numeral ranging from I to L to its decimal equivalent. b. Write a C program that converts a number ranging from 1 to 50 to Roman equivalent c. Write a C program that uses functions to perform the following operations: i) To insert a sub-string in to a given main string from a given position. ii) To delete n Characters from a given position in a given string. d. Write a C program to determine if the given string is a palindrome or not (Spelled same in both directions with or without a meaning like madam, civic, noon, abcba, etc.) e. Write a C program that displays the position of a character ch in the string S or – 1 if S doesn„t contain ch. f. Write a C program to count the lines, words and characters in a given text. Miscellaneous: a. Write a menu driven C program that allows a user to enter n numbers and then choose between finding the smallest, largest, sum, or average. The menu and all the choices are to be functions. Use a switch statement to determine what action to take. Display an error message if an invalid choice is entered. b. Write a C program to construct a pyramid of numbers as follows: 1 * 1 1 * 1 2 * * 2 3 2 2 * * 1 2 3 * * * 4 5 6 3 3 3 * * * 4 4 4 4 * * * Sorting and Searching: a. Write a C program that uses non recursive function to search for a Key value in a given list of integers using linear search method.
  • 13. Programming for Problem Solving Lab Page 13 BVRIT HYDERABAD College of Engineering for Women b .Write a C program that uses non recursive function to search for a Key value in a given sorted list of integers using binary search method. c. Write a C program that implements the Bubble sort method to sort a given list of integers in ascending order. d. Write a C program that sorts the given array of integers using selection sort in descending order e. Write a C program that sorts the given array of integers using insertion sort in ascending order f. Write a C program that sorts a given array of names Suggested Reference Books for solving the problems: i. Byron Gottfried, Schaum‟s Outline of Programming with C, McGraw-Hill ii. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage Learning, 3rd Edition) iii. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice iv. Hall of India v. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression) vi. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education. vii. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition
  • 14. Programming for Problem Solving Lab Page 14 BVRIT HYDERABAD College of Engineering for Women INSTRUCTIONS TO THE STUDENTS (1) On entering the lab you should make an entry in the log book available with thedetails regarding student name, roll no, system no and signature. (2) You must bring Observation notebook for every lab session. Observation book should be duly signed by your faculty, failing which your report will not be graded. You must complete all experimental programs allotted during the session. (3) You should shutdown the system properly and leave the lab neat and tidy.
  • 15. Programming for Problem Solving Lab Page 15 BVRIT HYDERABAD College of Engineering for Women INTRODUCTION TO ‘UNIX’ COMMANDS In order to create and run programs in UNIX environment the following are the some of the basic editors and commands used. Creating Directory: Directories are used to group files together in a hierarchical structure. mkdir dirname --- creates a new directory cd dirname --- to change to the specified directory cd.. --- will get you one level up from your current position(directory) rmdir dirname --- removes/deletes directory rm --- deletes files in directory Editors: Nano Editor: Basic editors used for creating the programs are nano, vim, emacs. GNU nano is a small and friendly text editor for beginners. Nano is installed by default in Ubuntu and many other editors. To run nano you can use the following syntax: nano path_filename.c Nano will follow the path and open that file if it exists. If it does not exist, it‟ll start a new buffer with that filename in that directory. It‟s a WYSIWYG editor; “what you say is what you get.” What you type directly goes into the text input, unless you modify it with a key like Control or Meta. Shortcuts: Ctrl+o --- to save the file contents Ctrl+x --- to Quit the editor. Nano will politely ask you if you want to save your buffer, and you can cancel this action as well. Ctrl+w --- to search for the text in the program Creating and Running Programs in Nano Editor: 1. To open the file ,at the command prompt type ------nano filename.c 2. Create the program and save the file---- ctrl+o , ctrl+s 3. Quit the editor----- ctrl+x 4. At the command prompt type gcc/c99 filename.c Above command is used to compile the program to generate object code. 5. To run the program type ./a.out(executable file)
  • 16. Programming for Problem Solving Lab Page 16 BVRIT HYDERABAD College of Engineering for Women Vim Editor: Vim is an advanced text editor that provides the power of the de-facto Unix editor 'Vi' with a more complete feature set. Vim is often called a "programmer's editor," and is so seful for programming that many consider it an entire IDE. It's not just for programmers, though. Vim is perfect for all kinds of text editing. Vim editor is best for program creation where the user will have the flexibility of differentiating the keywords and text what the user enters. To run vim you can use the followingsyntax: vim path_filename.c Shortcuts: Shift+:+w --- to save the file contents Shift+:+q --- to Quit the editor without saving the contents of file. Shift+:+wq --- to save contents and quit the editor Running Programs in vim Editor: 1. To open the file, at the command prompt type --- vim filename.c 2. Create the program and save the file and quit --- Shift+:+wq 3. At the command prompt type C99/gcc filename.c Above command is used to compile the program to generate object code. 4. To run the program type ./a.out(executable file) Configuration: vim is a highly configurable editor, and it is best to configure vim to your liking as vim by default has all the nice features turned off. A list of files and their locations are given below. ~/.vimrc is the vim configuration file which vim reads on startup ~/.vim/ is the directory in which the user can add utility plugins, syntax highlighting plugins, and indent plugins. Sample .vimrc file " Turn on line numbering. Turn it off with "set onu" set nu " Set syntax on syntax on " Indent automatically depending on filetype filetype indent on set auto indent
  • 17. Programming for Problem Solving Lab Page 17 BVRIT HYDERABAD College of Engineering for Women Basic UNIX Commands used: man command: man commandname --- shows you the manual page for the command ls command: ls --- lists your files in the directory ls-l --- lists our file in long format, it gives information about size of file, owner of file, rights for file and last modified time. Copy command: cp filename1 filename2 --- copies contents of file1 to file2, where both file1 and file2 will have same content. Move command: mv filename1 filename2 --- moves contents of file1 to file2 and file1 contents will be erased. Remove command: rm filename --- removes a file. It is wise to use the option rm -i, which will ask you for confirmation before actually deleting anything.
  • 18. Programming for Problem Solving Lab Page 18 BVRIT HYDERABAD College of Engineering for Women INTRODUCTION TO ‘C’ CONCEPTS Keywords in C: Auto Break Case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Standard Input / Output functions in C: SCANF - Read formatted data from stdin(standard input device) Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string. PRINTF - Print formatted data to stdout(standard output device) Writes to the standard output (stdout) a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format. printf ("Characters: %c %c n", 'a', 65); Common format specifiers in control string for printf and scanf functions are %d--- for reading integer data %f --- for reading float data %c--- for reading character data %s--- for reading strings %ld--- for reading double data CONTROL STATEMENTS IF Statement: The if statement controls conditional branching. The body of an if statement is executed if the value of the expression is nonzero. The syntax for the if statement has two forms. selection-statement: if ( expression ) statement
  • 19. Programming for Problem Solving Lab Page 19 BVRIT HYDERABAD College of Engineering for Women if ( expression ) statement else statement In both forms of the if statement, the expressions, which can have any value except a structure, are evaluated, including all side effects. In the first form of the syntax, if expression is true (nonzero), statement is executed. If expression is false, statement is ignored. In the second form of syntax, which uses else, the second statement is executed if expression is false. With both forms, control then passes from the if statement to the next statement in the program unless one of the statements contains a break, continue, or goto. FOR Statement: The for statement lets you repeat a statement or compound statement a specified number of times. The body of a for statement is executed zero or more times until an optional condition becomes false. You can use optional expressions within the for statement to initialize and change values during the for statement's execution. Syntax: iteration-statement: for ( init-expression opt ; cond-expression opt ; loop-expression opt )statement Execution of a for statement proceeds as follows: 1. The init-expression, if any, is evaluated. This specifies the initialization for the loop. There is no restriction on the type of init-expression. 2. The cond-expression, if any, is evaluated. This expression must have arithmetic or pointer type. It is evaluated before each iteration. Three results are possible: o If cond-expression is true (nonzero), statement is executed; then loop-expression, if any, is evaluated. The loop-expression is evaluated after each iteration. There is no restriction on its type. Side effects will execute in order. The process then begins again with the evaluation of cond-expression. o If cond-expression is omitted, cond-expression is considered true, and execution proceeds exactly as described in the previous paragraph. A for statement without a cond-expression argument terminates only when a break or return statement within the statement body is executed, or when a goto (to a labeled statement outside the for statement body) is executed. o If cond-expression is false (0), execution of the for statement terminates and control passes to the next statement in the program. A for statement also terminates when a break, goto, or return statement within the statement body is executed. A continue statement in a for loop causes loop-expression to be evaluated. When a break statement is executed inside a for loop, loop-expression is not evaluated or executed. WHILE Statement: The while statement lets you repeat a statement until a specified expression becomes false.
  • 20. Programming for Problem Solving Lab Page 20 BVRIT HYDERABAD College of Engineering for Women Syntax: iteration-statement: while ( expression ) statements The expression must have arithmetic or pointer type. Execution proceeds as follows: 1. The expression is evaluated. 2. If expression is initially false, the body of the while statement is never executed, and control passes from the while statement to the next statement in the program. 3. If expression is true (nonzero), the body of the statement is executed and the process is repeated beginning at step 1. The while statement can also terminate when a break, goto, or return within the statement body is executed. Use the continue statement to terminate an iteration without exiting the while loop. The continue statement passes control to the next iteration of the while statement. DO WHILE Statement: The do-while statement lets you repeat a statement or compound statement until a specified expression becomes false. Syntax: iteration-statement: do statements while ( expression ) ; The expression in a do-while statement is evaluated after the body of the loop is executed. Therefore, the body of the loop is always executed at least once.
  • 21. Programming for Problem Solving Lab Page 21 BVRIT HYDERABAD College of Engineering for Women The expression must have arithmetic or pointer type. Execution proceeds as follows: 1. The statement body is executed. 2. Next, expression is evaluated. If expression is false, the do-while statement terminates and control passes to the next statement in the program. If expression is true (nonzero), the process is repeated, beginning with step 1. The do-while statement can also terminate when a break, goto, or return statement is executed within the statement body.
  • 22. Programming for Problem Solving Lab Page 22 BVRIT HYDERABAD College of Engineering for Women STEPS IN PROGRAM DEVELOPMENT In today‟s world, a computer is used to solve various types of problems, because it takes very less time as compared to a human being. The following steps are performed while solving a problem: Define the problem Outline the solution Develop the outline into an algorithm Test the algorithm into a programming language Code the algorithm into a programming language. Run the program on computer Document and maintain the program
  • 23. Programming for Problem Solving Lab Page 23 BVRIT HYDERABAD College of Engineering for Women C Program Compilation Process
  • 24. Programming for Problem Solving Lab Page 24 BVRIT HYDERABAD College of Engineering for Women Descriptions of the steps follow below: Design and Code Involves designing a program to meet a specified requirement, and creating the programming language text files that will comprise the program source. Compile After checking for syntactical correctness, converts the programming language source files into machine readable instructions, where C variables are associated with memory addresses, and C statements are turned into a series of machine language instructions. The compiler can produce various forms of output, depending on the compiler options selected. Linkage Editor Links compiler output with external modules requested by the compiled program. C programs can use routines from C libraries or any object or archive file from the IBM XL family of languages. C programs can also use modules produced by the current or previous compilations. As well as linking the external modules, the linkage editor resolves addresses within the objectmodule. Run and Test This stage can be both the final step in program Development, or it can be an intermediate point in the program design and implementation process. A program‟s design commonly is further refined as a result of information gathered during testing.
  • 25. Programming for Problem Solving Lab Page 25 BVRIT HYDERABAD College of Engineering for Women a) Write a simple program that prints the result of all the operators available in c. (Including pre, post, increment, bitwise and, or, not etc.,). Read the requiredoperand values from standard input. b) Write a simple program that converts one given data type to another using auto conversion and casting. Take the value from standard input. a) Write a C program to find the max and min from three numbers LAB CYCLE-1 Practice Session Step 1: Start Step 2: Take two operands „A‟ and „B‟ from standard input. Step 3: Apply operators of c on „A‟ and „B‟. Step 4: Print output values using printf statement. Step 5: End. Step 1: Step 2:Declare a , b as integer and c,d as float Step 3: Read a and b Step 4: compute c=a/b /*auto conversion, as a/b is assigned to c where c is float so the final result will be in float */ Step 5:d can be assigned in following way d=(float)a/b; /*Type casting, here explicitly we are converting the type of a and b into float Simple Numeric Problems STEP 1: start Step 2:Read a,b &c Step 3:Calculate max using Ternary Operator max=(a>=b&&a>=c)?a:(b>=a&&b>=c)?b:c Claculate min using Ternary Operator min=(a<=b&&a<=c)?a:(b<=a&&b<=c)?b:c; Step 4: Print max and min STEP 5: End
  • 26. Programming for Problem Solving Lab Page 26 BVRIT HYDERABAD College of Engineering for Women Step 1:Input principle amount. Store it in some variable say principle. Step 2:Input time in some variable say time. Step 3: Input rate in some variable say rate. Step 4: Calculate compound interest using formula, CI = principle * pow((1 + rate / 100), time). Step 5: Finally, print the resultant value of CI. C Program to find the simple interest Step 1:Start Step 2:Read Principal Amount, Rate and Time Step 3:Calculate Interest using formula SI= ((amount*rate*time)/100) Step 4:Print Simple Interest Step 5:Stop C Program to find the compound interest Step 1: Start Step 2: Input percentage P from standard input Step 3: Initialize a switch case or if-else ladder to write below conditions i.e if P < 40 then „fail‟ else if P > 40 and P < 60 then „Second Class‟ else if P > 60 and P < 70 then „First Class‟ else „Distinction‟ Step 4: End c) Write program that declares class awarded for a given percentange of marks ,where marks < 40%=failed, 40% to 60% = second class, 60 to 70% first class, >= 70% = distinction. Read percentage from standard input. b) Write a C program to find the Simple and compound Interest
  • 27. Programming for Problem Solving Lab Page 27 BVRIT HYDERABAD College of Engineering for Women e) Write a program to show the binary equivalent of a given positive number between 0 to 255. Step 1: Start Step 2: Input a number N through standard input which is greater than 0 and less than 255. Step 2: Store the remainder when the number N is divided by 2 in an array. Step 3: Divide the number by 2. Step 4: Repeat the above two steps until the number is greater than zero. Step 5: Print the array in reverse order now. Step 6: End Step1:Start Step 2: Input number n and rows r from standard Input. Step 3:Intialize For loop I=1;I<=r;I++ Print n*I Step 4: End Expression Evaluation a) A building has 10 floors with a floor height of 3 meters each. A ball is dropped from thetop of the building. Find the time taken by the ball to reach each floor. (Use the formula s =ut+(1/2)at^2 where u and a are the initial velocity in m/sec (= 0) and acceleration in m/sec^2 (= 9.8 m/s^2)). Step 1:- start Step 2:- take u=0,a=9.8 Step 3:- Set s=3,t=0 Step 4:- for(i=1;i<=10l;i++,s+3) t=u+sqrt(u*u+2*a*s) print t ,s ,i Step 5:- stop d) Write a C program that prints a multiplication table for a given number andthe number of rows in the table. For e.g. For a number 5 and rows =3 ,the output should be : 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15
  • 28. Programming for Problem Solving Lab Page 28 BVRIT HYDERABAD College of Engineering for Women b) Write a ’C’ program which takes two integer operands and one operator from theuser, performs the operation and the prints the result.(consider the operators +,-,*,/,% and use switch statement). Algorithm Step 1:- start Step 2:- read a,b,ch Step 3:- switch(ch) (a) case 1 : c=a+b Print c break; (b)case 2 : c =a-b Print c break; (c)case 3 : c=a*b Print c break; (d) case 4 : c=a/b Print c break; (e)case 5: c=a%b Print c break; Step 4:- stop c) Write a ‘C’ program to find out given number is prime number or not. Algorithm Step 1: start Step 2: read num,flag=0 Step 3: (a)for(i=2;i<num/2;i++) (i)if(num%i==0) flag++ (b)if(flag==0) Print Prime Else Print NoPrime Step 4:- stop
  • 29. Programming for Problem Solving Lab Page 29 BVRIT HYDERABAD College of Engineering for Women d) Write a ‘C’ program to find the sum of individual digits of a positive integer and testgiven number is palindrome or not Algorithm Step 1: start Step 2: take sum=0,rev=0 Step 3: read n,num=n Step 4: while (n>0) (a) r=n%10 (b)Sum=sum+ r c)rev=rev+r*10 (d) n=n/10 Step 5: if(num==rev) Step 6: print palindrome Step 7: else Step 8: print Not Palindrome Step 6: stop e) A Fibonacci Sequence is defined as follows: the first and second terms in the sequence are0 and 1.Subsequent terms are found by adding the preceding two terms in the sequence .Write a ‘C’ program to generate the first n terms of the sequence. Algorithm Step 1: start Step 2: let a=0,b=1 Step 3: read n Step 4: print a,b Step 5: for(i=3;i<=n;i++) (a) c=a+b (b)print c (c)a=b d) b=c step 6: stop f) Write a ‘C’ program to generate all the prime numbers between 1 and n, where n is a value supplied by the user. Algorithm Step 1: start Step 2: read n Step 3: for(i=1;i<n;i++) (a)for(j=2;j<i;j++) (i)if(i%j==0) m++ (b)if(m==0) Print i (c) m=0 Step 4:- stop
  • 30. Programming for Problem Solving Lab Page 30 BVRIT HYDERABAD College of Engineering for Women g) Write a ‘C’ program to find the roots of a quadratic equation. Algorithm Step 1: start Step 2: read a,b,c Step 3: d=b*b-4*a*c Step 4: if(d>0) (i) (a) root1=(-b+sqrt(d))/(2*a) (b) root2=(-b-sqrt(d))/(2*a) (c)print root1,root2 (d)print roots are real Else if(d==0) (i) (a) root1=-b/(2*a) (b) root2=-b/(2*a) (c)print root1,root2 (d)print roots are equal Else (ii) print roots are imaginary Step 5: stop h) Write a ‘C’ program to calculate the following ,where x is fractionalvalue. sum=1-x/2+ x2/4-x3/6 Algorithm Step 1: start Step 2: take sum=1,k=1 Step 3: read x as real value Step 4: a)for(i=1 ,j=2;i<=3;i=i++,j+2) (b)sum=sum+pow(x,i)/j; Step 5: print sum Step 6: stop i) Write a ‘C’ program to read in two numbers, x and n, and then compute the sum ofthis geometric progression: 1+x+x2+x3+ ................+xn For example: if n is 3 and x is 5, then the program computes 1+5+25+125. Algorithm Step 1: Start Step 2: Sum=0 Step 3: Read x Step 4: Read n Step 5: Repeat step 6 to 7 until i>n Step 6: Sum =sum+(x)^i Step 7: i=i+1 Step 8: Print sum Step 9: Stop
  • 31. Programming for Problem Solving Lab Page 31 BVRIT HYDERABAD College of Engineering for Women LAB CYCLE - 2 Arrays and Pointers and Functions a. Write a C program to find the minimum, maximum and average in an array of integers. Algorithm Step 1: Start Step 2: Enter the array elements Step 3: Initialize Max= a[0] , Min =a[0],Sum=0; Step 4: Check each from first element whether they are greater than Max or not For (i=1;i<n;i++) { if(a[i]>Max) { Max=a[i] } Check each from first element whether they are less than Min or not For (i=1;i<n;i++) { if(a[i]<Min) { Min=a[i] } Step 5: Perform Summation for each arrayelements for(i=0;i<n;i++) { Sum=Sum+a[i]; } Step 6: Calculate average Avg= Sum/n Step 7:Print Max,Min,Sum,Avg b. Write a functions to compute mean, variance, Standard Deviation, sorting of n elementsin single dimension array. Algorithm Step 1: Initialize sum and sum 1 to 0 Step 2: Read array elements with all real numbers Step 3: Compute the sum of all elements for(i=0; i<n; i++){ sum = sum + x[i]; } Step 4: Find Mean
  • 32. Programming for Problem Solving Lab Page 32 BVRIT HYDERABAD College of Engineering for Women Step 6: Check each two adjust elements then swap with each other in ascending order Mean= sum /(float) n; Step 5: Compute variance var and standard deviation SD for(i=0; i<n; i++) { sum1 = sum1 + pow((x[i] - avrg),2); /* calculate the variance using general equation */ } var = sum1 / (float) n; SD = sqrt(var); /* calculating standard deviation */ for(i=1;i<=n-1;i++) { for(j=0;j<n-i;j++) { if(a[j]>a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } Step 7: Continue with all the passes until all the elements are sorted in the array step 8: print After sorting, the element are step 9: for(i=0;i<n;i++) print a[i] step10: end c. Write a C program that uses functions to perform the following: Addition of Two Matrices i. Addition of Two Matrices Algorithm Step 1: Start Step 2: Repeat step 3 for i=1 to 3 insteps of 1 Step 3: Repeat step 4 for j=1 to 3 insteps of 1 Step 4. Read A[i][j] Step 5: Repeat step 6 for i=1 to 3 insteps of 1 Step 6: Repeat step 7 for j=1 to 3 insteps of 1 Step 7: Read B[i][j] Step 8: Repeat step 9 for i=1 to 3 insteps of 1 Step 9: Repeat step 10 for j=1 to 3 insteps of 1 Step 10: Read C[i][j] = A[i][j] + B[i][j] Step 11: Print C[i][j] Step 12: Stop
  • 33. Programming for Problem Solving Lab Page 33 BVRIT HYDERABAD College of Engineering for Women ii. Multiplication of Two Matrices Algorithm Step 1: Start Step 2: Repeat step 3 for i=1 to 3 insteps of 1 Step 3: Repeat step 4 for j=1 to 3 insteps of 1 Step 4: Read A[i][j] Step 5: Repeat step 6 for i=1 to 3 insteps of 1 Step 6: Repeat step 7 for j=1 to 3 insteps of 1 Step 7: Read B[i][j] Step 8: Repeat step 9 for i=1 to 3 insteps of 1 Step 9: Repeat step 10 to 13 for j=1 to 3 insteps of 1 Step 10: C[i][j]=0 Step 11: Repeat step12 for k=1 to 3 insteps of 1 Step 12: C[i][j]= C[i][j]+ A[i][k]* B[k][j] Step 13: Print C[i][j] Step 14: stop iii. Transpose of a matrix with memory dynamically allocated for the new matrix as rowand column counts may not be same. Algorithm: Step 1: start Step 2: read matrix size m,n Step 3: read matrix elements for(i=0;i<m;i++) for(j=0;j<n;j++) read a[i][j] Step 4: print The Matrix is for(i=0;i<m;i++) { for(j=0;j<n;j++) print a[i][j] print "n" } Step 5: for(i=0;i<m;i++) { for(j=i+1;j<n;j++) { temp = a[i][j]; a[i][j] = a[j][i]; a[j][i] = temp; } } Step 6: print The Matrix after transpose,is for(i=0;i<n;i++) { for(j=0;j<m;j++) print a[i][j]
  • 34. Programming for Problem Solving Lab Page 34 BVRIT HYDERABAD College of Engineering for Women print "n" } Step 7: end d. Write C programs that use both recursive and non-recursivefunctions i)To find the factorial of a given integer. Algorithm without recursion Algorithm with recursion 1. Start 1. start 2. Read n 2. read n 3. f=1 3. if(n>0) 4. for i=1 repeat step 5 until i>n 4. fact=fact(n) 5. f=f*I 5. read i=1,fact=1 6. print „factorial is‟,f 6. if(i<=n) 7. stop 7. fact=fact*i 8. i=i+1 9. display fact ii) To find the GCD (greatest common divisor) of two given integers. Algorithm with recursion Algorithm without recursion 1. GCD( int small , int large) 1. Read a,b { 2. function call gcd(a,b) 2. While(( large % small )!=0) 3. function called gcd(m,n) { 4. if(m<n) 3. Int tmp = large % small; 5. return gcd(n,m) 4. large=small 6. if(n==0) 5. Small=tmp; 7. return m } 8. return gcd(n,m%n) Return small; }
  • 35. Programming for Problem Solving Lab Page 35 BVRIT HYDERABAD College of Engineering for Women iii ) To find x^n Algorithm with recursion def power(x, n): if n == 0: return 1 else if n == 1: return x else if n % 2 == 0: return power(x*x, n / 2) else: return x*power(x*x, (n-1) /2) Algorithm without recursion Step 1: Start Step 2: Read base and exponent Step 3: Initialize result=1 Step 4: while (exponent > 0) perform step 5 to step 8 Step 5: while ((exponent & 1) == 0) perform step 6 Step 6: exponent =exponent/2 base=base*base Step 7: Perform exponent - - Step 8: Result=result*base Step 9: Print result Step 10: End e) Write a program for reading elements using pointer into array and display the values using array. Step 1: Start Step 2: Read elements for(i = 0; i < n; ++i) { scanf("%d", data + i); } Step 3: Print elements for(i = 0; i < 5; ++i) { printf("%dn", *(data + i)); } f) Write a program for display values reverse order from array using pointer. Algorithm Step 1: Start Step 2: Assign address of first element to pointer variable ptr = &arr[0]; Step 3: Enter the size of array and array elements for (i = 0; i < size; i++) {
  • 36. Programming for Problem Solving Lab Page 36 BVRIT HYDERABAD College of Engineering for Women scanf("%d", ptr); ptr++; } Step 4: Assign last element address to pointer to access the array in reverse order ptr = &arr[size - 1]; Step 5: Print Elements of array in reverse order for (i = size - 1; i >= 0; i--) { printf("nElement%d is %d : ", i, *ptr); ptr--; } Step 6: End g)Write a program through pointer variable to sum of n elements fromarray. Algorithm Step 1: Start Step 2: Initialize sum = 0; Step 3: Read Array elements Step 4: Assign ptr to base address ptr = numArray; /* a=&a[0] */ Step 5: Perform addition for array elements using pointer for (i = 0; i < 10; i++) { sum = sum + *ptr; ptr++; } Step 6: Print sum Step 7:End Files a) Write a C program to display the contents of a file to standard output device. Algorithm Step 1: Start Step 2: Open file f1 in read mode with file pointer fp Step 3: While not end of file f1 do the steps 5 to 6 Step 4: putchar(fp,stdout) Step 5: Close the files f1 Step 6: Stop b. Write a C program which copies one file to another, replacing all lowercase characters with their uppercase equivalents Algorithm Step 1: Start Step 2: Open file f1 in read mode Step 3: Open file f2 in write mode Step 4: While not end of file f1 do the steps 5 to 6: Step 5: ch = read a char from f1
  • 37. Programming for Problem Solving Lab Page 37 BVRIT HYDERABAD College of Engineering for Women Step 6: if (islower(ch)) ch=ch-32 Step 7: Copy ch into file f2 Step 8: Close the files f1,f2 Step 9 :Stop c. Write a C program to count the number of times a character occurs in a text file. The file name and the character are supplied as command-line arguments. Algorithm Step1: Start Step2: argv[0] is filename argv[1] is character to search Step3: count=0 Step4: Open the file in read mode Step5: c= argv[1][0] Step6: while(ch=fgetc(fp) && ch !=EOF&& ch== c) Step7: Count ++ Step8: Close the file Step9: Display count d) Write a C program for the following. It should first create a binary file and store 10 integer values ,where file name and 10 values are given in the command line .Now program ask for the index and value from the user and value at that index should be changed to the new value in the file .The program should read all 10 values and print them back. Algorithm: Step1: Start Step2: argv[0] is filename argv[1] to argv[10] are 10 values. Step3: read character in to ch Step4: open the file with file pointer fp in w+ mode Step5:read n (n is index value) Step6: move to nth character using fseek( fp, n, SEEK_SET ); Step7: replace the character using fputc(ch, fp); Step8:Adust cursor to last position of file using seek(p,0,SEEK_END) Step9: Read and display contents of file using fgetc() Step10:Stop. e. Write a C program to merge two files into a third file (i.e., the contents of the firs t file followed by those of the second are put in the third file). Algorithm Step 1: Start Step 2: Read file pointers fs,ft Step 3: Open a file in read mode with file pointer fs Step 4: Open a file in write mode with file pointer ft Step 5: Check file pointer with arguments passed till null Step 6: If NULL display file cannot be opened,close fs
  • 38. Programming for Problem Solving Lab Page 38 BVRIT HYDERABAD College of Engineering for Women Step 7: Check the condition with argv[1](file name) then do steps 8 to 10 Step 8: Read charecters of file fs to ft Step 9: If EOF,break Step 10: Display contents ( copied content) Step 11: Close two files Step 12: Stop
  • 39. Programming for Problem Solving Lab Page 39 BVRIT HYDERABAD College of Engineering for Women LAB CYCLE - 3 Strings a) Write a C program to convert a Roman numeral to its decimal equivalent. Algorithm: Step 1: Start Step 2: read the roman numerical as string Step 3: find length of roman numerical Step 4: for each charcter in the string i) if(char = I) then decimal = 1 ii) if(char = V) then decimal = 5 iii) if(char = X) then decimal = 10 iv) if(char = L) then decimal = 50 v) if(char = C) then decimal = 100 vi) if(char = D) then decimal = 500 vii) if(char = M) then decimal = 1000 viii) otherwise invalid character Step 5: repeat step 4 until the length of the string Step 6: k = char[length - 1] Step 7: for each character of decimal string i) if(decimal[i] > dec[i - 1]) then k = k - decimal[i - 1] ii) else if(decimal[i] = decimal[i - 1 or decimal[i] < decimal[i - 1) then k = k + decimall[i - 1] Step 8: repate step 7 until the length of decimal string Step 9: print decimal value Step 10: Stop b. Write a C Program to convert number ranging from 1 to 50 to roman equivalent. Algorithm Step 1: Start Step 2: Read input value between 1 to 50 from user. Step 3: ten = ((input/10)%10)*10; Step 4: one = ((input/1)%10)*1; //checking for tens Step 5: if(ten==10) Step6: print("X"); Step 7: else if(ten==20) Step 8: print("XX"); Step 9: else if(ten==30) Step 10: print("XXX"); Step 11: else if(ten==40) Step 12: print("XL"); Step 13: else if(ten==50) Step 14: print("L"); Step 15: else if(ten==60) Step 16: print("LX"); Step 17: else if(ten==70) Step 18: print("LXX");
  • 40. Programming for Problem Solving Lab Page 40 BVRIT HYDERABAD College of Engineering for Women Step 19: else if(ten==80) Step 20: print("LXXX"); Step 21: else if(ten==90) Step 22: print("XC"); Step 23: if(one==1) Step 24: print("I"); Step 25: else if(one==2) Step 26: print("II"); Step 27: else if(one==3) Step 28: print("III"); Step 29: else if(one==4) Step 30: print("IV"); Step31: else if(one==5) Step32: print("V"); Step 33: else if(one==6) Step34: print("VI"); Step 35: else if(one==7) Step 36: print("VII"); Step 37: else if(one==8) Step 38: print("VIII"); Step 39: else if(one==9) Step 40: print("IX"); Step 41: Stop c. Write a C program that uses functions to perform the following operations: 1. to insert a sub-string into a given main string from a given position. 2. to delete n characters from a given position in a given string. 1) To insert a sub string into a given main string from a given position Algorithm Step 1. start Step 2. read str1,str2,str3,position Step 3. strncpy of str3,str1,position Step 4. strcat of str3,str2 Step 5. strcpy of str3,str1+position Step 7. print str3 Step 8. stop
  • 41. Programming for Problem Solving Lab Page 41 BVRIT HYDERABAD College of Engineering for Women 2) Delete n characters from string Algorithm Step 1. start Step 2. read str1,pos,n,m Step 3. calculate m=strlen(str1) Step 4. if pos > m Step 5. print deletion not possible Step 6. else j=pos; Step 7. for(i=pos+n; i<=m; i++){ Step 8. str1[j]=str1[i]; Step 9. j++;} Step 10. print str1 Step 11. Stop d) Write a C program to determine if the given string is a palindrome or not. Algorithm Step 1. start Step 2. read s1 Step 3. i=0 Step 4. repeat step 5 to 6 until s1[i]==‟0‟ Step 5. s2[i]=s1[i] Step 6. i=i+1 Step 7. length=I Step 8. repeat step 9 from j=0 to i Step 9. if s1[j]<>s2[j] Step 10. print „string is not palindrome‟ Step 11. else print „string is palindrome‟ Step 12. Stop e) Write a C program that displays the position of character ch in the string S , or – 1 if S doesn’t contain ch. Algorithm Step 1: Start Step 2: read the string and then displayed Step 3: read the character „ch‟ to be searched and then displayed Step 4: searching the string ch in string S and then perform the following steps i. found = strstr(S, ch) ii. if found print the position of character , If not goto step5 Step 5: print the -1 Step 6: Stop
  • 42. Programming for Problem Solving Lab Page 42 BVRIT HYDERABAD College of Engineering for Women f) Write a C program to count the lines, words and characters in a given text. Alogrithm Step 1: Start Step 2: Read the text until an empty line Step 3: Compare each character with newline char „n‟ to count no of lines Step 4: Compare each character with tab char „t‟ or space char „ „ to count no of words Step 5: Compare first character with NULL char „0‟ to find the end of text Step 6: No of characters = length of each line of text Step 7: Print no of lines, no of words, no of chars Step 8: Stop Miscellaneous a. Write a menu driven C program that allows a user to enter n numbers and then choose between finding the smallest, largest, sum, or average. The menu and all the choices are to be functions. Use a switch statement to determine what action to take. Display an error message if an invalid choice is entered. Algorithm Step1. Start Step 2. read n Step 3. read the values in to the array a Step 4. read the choice if it is valid goto step 5 otherwise goto step 11 Step 5. use switch case to select the the menu 1. smallest 2. largest 3. sum 4.average Step 6.smallest() s=a[i] for(i=1;i<n;i++){ if(a[i]<s) s=a[i] } return(s) Step 7. largest() l=a[i] for(i=1;i<n;i++){ if(a[i]>l) l=a[i] } return(l) Step 8. sum() s=0 for(i=0;i<n;i++){ s+=a[i] } return(s)
  • 43. Programming for Problem Solving Lab Page 43 BVRIT HYDERABAD College of Engineering for Women Step 9.average() s=a[i] for(i=0;i<n;i++){ s+=a[i] } return(s/n) Step 10. goto step 4 Step 11. display invalid choice Step 12. stop a) Write a C program to construct a pyramid of numbers as follows: 1 1 2 1 2 3 Algorithm: step1: Start step2: Read rows step3: initialize i=1 step4: Repeat step 4 through 10 until i<=rows step5: initialize j=1 step6: Repeat step 6 through 8 until j<=i step7: print j step8: end of inner loop step9: go to next line step10: end of outer loop step11: stop. * * * * * * Algorithm: step1: Start step2: Read number num step3: [initialize] r=1 step4: Repeat step 4 through 10 until num>=r step5: [initialize] c=1 step6: Repeat step 6 through 8 until c<=r step7: print * step8: c=c+1 [end of loop step6] step9: go to next line step10: r=r+1
  • 44. Programming for Problem Solving Lab Page 44 BVRIT HYDERABAD College of Engineering for Women [end of loop step4] step11: stop 1 2 3 4 5 6 Algorithm: step1: Start step2: Read rows, initialize num=1 step3: [initialize] i=1 step4: Repeat step 4 through 10 i<=rows step5: [initialize] j=1 step6: Repeat step 6 through 8 until j<=i step7: print num step8: increment num [end of inner loop] step9: go to next line step10: end of outer loop step11: stop. 1 2 2 3 3 3 Algorithm: step1: Start step2: Read rows step3: initialize i=1 step4: Repeat step 4 through 10 until i<=rows step5: initialize j=1 step6: Repeat step 6 through 8 until j<=i step7: print i step8: end of inner loop step9: go to next line step10: end of outer loop step11: stop. * * * * * * * * *
  • 45. Programming for Problem Solving Lab Page 45 BVRIT HYDERABAD College of Engineering for Women Algorithm: Step1: Input number of columns to print from user. Store it in a variable say N. Step2:Declare a variable as loop counter for each column, say columns = 1. Step3: To iterate through rows, run an outer loop from 1 to N * 2 - 1. The loop structure should look like for(i=1; i<N*2; i++). Step4: To iterate through columns, run an inner loop from 1 to columns. The loop structure should look like for(j=1; j<=columns; j++). Inside this loop print star. Step5: After printing all columns of a row, move to next line. Step6: After inner loop check if(i <= N) then increment columns otherwise decrement by 1. Sorting and Searching: a. Write a C program that uses non recursive function to search for a Key value in a given list of integers using linear search method. Algorithm: step1: Start step2: declare integer array step3: Read number of elements step4: input elements in to the array step5: input key value to be searched step6: compare key value with every element in the array if found print the element step7: if search reaches last element and key value not found print not found step8: stop b .Write a C program that uses non recursive function to search for a Key value in a given sorted list of integers using binary search method. Algorithm: Step1: Find the middle element of the list Step2: Compare the middle element with the given element. Step3: If both are equal, return the index of the middle element. Step4: If they are not equal, then if given element is smaller than middle element, then we must search for given element in upper half of the list otherwise, we must search in the lower half. Step5: Now in the smaller list, find the middle element and repeat the process. c. Write a C program that implements the Bubble sort method to sort a given list of integersin ascending order. Algorithm: void bubblesort(int numbers[],int array_size) { int I,j,temp; for(i=(array_size‐1);i.=0;i‐‐) { for(j=1;j<=I;j++) if(numbers[j‐1]>numbers[j])
  • 46. Programming for Problem Solving Lab Page 46 BVRIT HYDERABAD College of Engineering for Women { temp=numbers[j‐1]; numbers[j‐1]=numbers[j]; numbers[j]=temp;}}} d. Write a C program that sorts the given array of integers using selection sort in descending order Algorithm: Step1: start Step2: enter the number elements to be sorted Step3: read elements in to the array Step4: traverse through the array from lower bound and compare adjacent elements. Step5: if element in lower bound is less than its adjacent then perform swap Step6: repeat until lower bound is compared with all the elements in the array to get the maximum element is in the lower bound. Step7: repeat step 5 &6 until all the elements are in descending order Step8: print the sorted array Step9: stop e. Write a C program that sorts the given array of integers using insertion sort in ascending order Algorithm: 1. Start with the result as the first element of the input. 2. Loop over the input until it is empty, "removing" the first remaining (leftmost) element. 3. Compare the removed element against the current result, starting from the highest(rightmost) element, and working left towards the lowest element. 4. If the removed input element is lower than the current result element, copy that value into the following element to make room for the new element below, and repeat with the next lowest result element. 5. Otherwise, the new element is in the correct location; save it in the cell left by copying the last examined result up, and start again from (2) with the next input element. f. Write a C program that sorts a given array of names . Algorithm: Step1: Start Step2: Read n Step3: Read the names into character array name[15][30] Step4: Declare char temp[30] Step5: Sort the names using for (i = 0; i < n - 1 ; i++){ for (j = i + 1; j < n; j++){ if (strcmp(name[i], name[j]) > 0){ strcpy(temp, name[i]); strcpy(name[i], name[j]);
  • 47. Programming for Problem Solving Lab Page 47 BVRIT HYDERABAD College of Engineering for Women strcpy(name[j], temp); } }} Step6: Display the contents of name Step7: Stop
  • 48. Programming for Problem Solving Lab Page 48 BVRIT HYDERABAD College of Engineering for Women VIVA QUESTIONS INTRODUCTION TO C 1) What is an algorithm? 2) What is a flowchart? 3) What are the characteristics of an algorithm? 4) What is a procedural oriented language? 5) How can u say C is a middle-level language? 6) What are the steps required to develop a C program? 7) What are the characteristics of C language? 8) What is difference between compiler and interpreter? 9) What is preprocessor directive? 10) When preprocessing is done? 11) Name some of the activities done at the time of preprocessing? SOLUTIONS: 1. An algorithm is a step by step procedure for calculations, data processing and automated reasoning. 2. A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. 3. There are five characteristics as Finiteness, Definiteness, Input, Output , Effectiveness. 4. A language based on functions rather than objects. You code to perform a series of tasks usually sequentially to achieve an objective, rather than code objects that relate to each other. Generally less flexible and harder to maintain. 5. C is often called a middle-level computer language as it combines the elements of high- level languages with the functionalism of assembly language. 6. Edit, Debug, Pre processor, Compiler, Linker. 7. Modularity, Portability, Extendibility, Speed, Flexibility. 8. A compiler translates code from a source language (e.g. C, C++, Java) to a target language, which can then be executed by a (virtual or physical) machine. And An interpreter reads code in an interpreted language (e.g. PHP, Perl, JavaScript) and directly executes the contained instructions. 9. Preprocessor directives, such as #define and #ifdef, are typically used to makesource programs easy to change and easy to compile in different executionenvironments. 10. Processing done depends on the nature of the preprocessor; some preprocessors are only capable of performing relatively simple textual substitutions and macro expansions, while others have the power of full-fledged programming languages. 11. Inclusion of header files, Macro expansion, Conditional compilation, Line control.
  • 49. Programming for Problem Solving Lab Page 49 BVRIT HYDERABAD College of Engineering for Women DATA TYPES AND OPERATORS 1) What is a C token? 2) What is a key word? List different keywords in C language? 3) What is a data type? Give different data types in C. 4) What is the use of typedef? 5) How to declare a constant in C? 6) What is the difference between a constant and a variable? 7) Give some examples of header files in C? 8) Why we include header files in a C program? 9) What are the different types of binary operators in C? 10)List different arithmetic operators and what is their precedence? 11)List different relational operators in C. 12)List different logical operators in C and give their precedence. 13)What is conditional operator? Write the syntax. 14)List different unary operators in C. 15)What is the associativity of assignment operator? 16)What is the use of sizeof operator? 17)What are shorthand assignment operators? 18)What is type casting? 19)List different bit-wise operators. What is the use of bit-wise operators? SOLUTIONS: 1. In a C source program, the basic element recognized by the compiler is the "token." A token is source-program text that the compiler does not break down into component elements as keywords, identifiers, constants, string literals, and operators. 2. A keyword is a reserved word which identifies a syntactic form. Words used in control flow constructs, such as if, then, and else are keywords. In these languages, keywords cannot also be used as the names of variables or functions. 3. compound types. Few Basic data types in C are char, int, float, double. 4. The purpose of typedef is to assign alternative names to existing types, most often those whose standard declaration is cumbersome, potentially confusing, or likely to vary from one implementation to another. 5. When you declare a constant it is a bit like a variable declaration except the value cannot be changed. 6. A constant remains fixed with any kind if change in variation or the quantity where as variables vary with certain quantities a variable is al location in a memory which holds a piece of data ,it can be represented by anything apart from numbers. where as a constant can be any numbers or characters. 7. #include<stdio.h>, #include<string.h>, #include<conio.h>,#define<typedef>. 8. A header file is a file with extension .h which contains C function declarations and macro definitions and to be shared between several source files. 9. Multiplicative operators, Additive operators, Shift operator, Relative operator, Equality operator, Bitwise operator, Logical operator. 10. Addition, Subtraction, Division, Multiplication, Module. Data types refer to an extensive system for declaring variables of different types. The language itself provides basic arithmetic types and syntax to build array and
  • 50. Programming for Problem Solving Lab Page 50 BVRIT HYDERABAD College of Engineering for Women 11. Equal to, Greater than equal to, Less than equal to, Equal. 12. Logical AND &&, Logical OR ||. 13. Expr1 expr2, lvalue1=expr1, expr1?expr2:expr3, expr1|| expr2,expr1 && expr2. 14. Unary plus +a, Unary minus –a. 15. Right to Left 16. The sizeof operator gives the amount of storage, in bytes, required to store anobject of the type of the operand. This operator allows you to avoid specifying machine- dependent data sizes in your programs. 17. V= expr, v op=expr, v=v op (expr), x+= y+1, x = x + (y+1). 18. Typecasting is a way to make a variable of one type, such as an int, act like another type, such as a char, for one single operation. 19. Four commonly used "bitwise operators" in C are: "~", "&", "|", and "^". These operators are used to manipulate the value of individual bits (1 or 0). There are also two 'shift' operators that it's important to understand: "<<" and ">>". The latter are used to 'shift' the position of a bit (or a set of bits) to another location in a multi-bit value CONTROL STRUCTURES 1) What are the different branch control statements in C language? 2) Is C a block structured language? 3) What is the meaning of block structured language? 4) What are the different loop control statements in C language? 5) What is the difference between while loop and do-while loop? 6) How to swap two variables? 7) How to swap two variables without using a temporary variable? 8) What is a compound statement? Give an example. 9) Write the syntax of for loop. 10)How a for loop executes? 11)How a nested for loop executes? 12)Differentiate between a for loop and a while loop? 13)What is the purpose of break statement in a loop? 14)What is the purpose of continue statement in a loop? 15)Write the syntax of switch statement. SOLUTIONS: . 1. If statements, if else statement, nested if statements 2. Yes C is a structured language. 3. In computer programming, a conceptual tool used to group sequences of statements into single compound statements and to allow the programmer explicit control over the scope of the program variables. 4. While, Do While, For Loop, Switch, Break.
  • 51. Programming for Problem Solving Lab Page 51 BVRIT HYDERABAD College of Engineering for Women 5. Initialization, Condition, Update Initialization, Condition, Update Statements are to be written Separately Statements are to be written Separately Syntax : Syntax : while(condition){ do{ statement... statement... statement... statement... } } while(condition); 6. C program to swap numbers we will use a temp variable to swap two numbers. Swapping is used in sorting that is when we wish to arrange numbers in a particular order either in ascending order or in descending order. 7. The best way to swap two variables is to use a temporary variable. As int a,b,t; t=a;a=b;b = t; 8. A compound statement (also called a "block") typically appears as the body of another statement, such as the if statement, for statement, while statement, etc 9. for (Start value; end condition; increase value)statement; 10. The “for loop” loops from one number to another number and increases by aspecified value each time. 11. Break breaks out of one loop, but you can add a check to the outer loop which breaks when the inner breaks as bool do break= false; for(..; ! do break &&..;..){ for(….){ if(…){ do break=true; break;}}} 12. In C 'for' and 'while' can be easily replaced by each other: while(exp)stmt for(;exp;)stmt for(exp1;exp2;exp3)stmt exp1; while(exp2){stmt;exp3}} 13. Objective of the C provides the break statement which breaks out of the current loop and resumes execution at the code directly after the loop. 14. The continue is another jump statement like the break statement as both the statements skip over a part of code . But continue statement is somewhat different from break. Instead of forcing termination, it forces the next iteration of loop to take place, skipping any code in between. A continue statement will just abandon the current iteration and let the loop start the next iteration. 15. The switch statement provides a multiway selection control structure to execute a selected section of code determined by the run-time value of an expression. The condition is an expression which evaluates to an integer value, which include signed, unsigned, char, enum, and even Boolean values. While Loop Do...While Loop Entry-Controlled Loop Exit-Controlled Loop
  • 52. Programming for Problem Solving Lab Page 52 BVRIT HYDERABAD College of Engineering for Women ARRAYS 1) What is an array? 2) What is the difference between an array and an ordinary variable? 3) What are the properties of array elements? 4) How to initialize one dimensional array? 5) How to initialize two dimensional array? 6) How a one dimensional array stored in memory? 7) How a two dimensional array stored in memory? 8) How can you increase the size of a dynamically allocated array? 9) How can you increase the size of a statically allocatedarray? 10)What is meant by static memory allocation? SOLUTIONS : 1. An array is a collection of one or more repeated instances of an object, referred to in a special way, that allows them all to have the same name, as a collection, but to be individually numbered. 2. The difference between the definition of array and ordinary variable is the, array is always declared, initialized, and accessed using subscript whereas ordinary variable do not have any subscript. 3. In C and C++ you add "1" to age (that is, the address of age) to access the second element, add "2" to age to access the third element, etc. If you hadn't seen the fancy image showing that each element of age (each short variable) had 2 bytes, then you might have said "1" and gotten the correct answer. 4. Static int number[3]={5,7,2}; 5. Static int months_days [2] [12]= {31,30,28,31};{31,30,30,31,28}; 6. The array which is used to represent and store data in a linear form is called as 'single or one dimensional array.' As syntax: <data-type> <array_name> [size]; Example: int a[3]= {2,3,4}; Char ch[20]=”techno exam”; Float stax[3]={5003.23,1940.32,123.20}; Total size in bytes: total size- length of array * size of data type; 7. The following syntax is used to represent two dimensional array. Syntax: <data-type> <array_nm> [row_subscript] [column- subscript]; Example: int a[3] [3]; 8. Example: * Allocate space for an array with ten elements of type int. */ int *ptr malloc(10 * sizeof (int)); if (ptr == NULL) { /* Memory could not be allocated, the program should handle the error here as appropriate. */ 9. int arr[10]; When an array is declared as above, memory is allocated for the elements of the array when the program starts, and this memory remains allocated during the lifetime of the program. This is known as static array allocation. Hence we cannot increase size of statically allocated array. 10. Allocation memory at compile time is called as static memory allocation.
  • 53. Programming for Problem Solving Lab Page 53 BVRIT HYDERABAD College of Engineering for Women FUNCTIONS 1) Define function in C? 2) What are the advantages of functions? 3) What are the different types of functions? 4) Give examples of user defined and pre-defined functions. 5) What is function prototype? 6) What is the difference between actual arguments and formal arguments? 7) What is scope and extent of a variable? 8) What is the scope of a global variable? 9) What are different types of storage classes in C? 10)What are register variables? 11)What are the different parameter passing mechanisms in C? 12)What is the difference between call by value and call by reference? 13)Define Recursion? SOLUTIONS: 1. The function is a self contained block of statements which performs a coherent task of a same kind. C program does not execute the functions directly. It is required to invoke or call that functions. When a function is called in a program then program control goes to the function body. Then, it executes the statements which are involved in a function body. Therefore, it is possible to call function whenever we want to process that functions statements. 2. Program testing made easy, program development made easy, code re usability increases, function facilitates the procedural abstraction. 3. There are five types of functions and they are: 1. Functions with no arguments and no return values. 2. Functions with arguments and no return values. 3. Functions with arguments and return values. 4. Functions that return multiple values. 5. Functions with no arguments and return values. 4. Function definition or task will be implemented by user are know as user defined function. And pre defined functions are already in built in function such as printf( ) and scanf( ). 5. All identifiers in C need to be declared before they are used. This is true for functions as well as variables. For functions the declaration needs to be before the first call of the function. A full declaration includes the return type and the number and type of the arguments. This is also called the function prototype. 6. Actual arguments:
  • 54. Programming for Problem Solving Lab Page 54 BVRIT HYDERABAD College of Engineering for Women The arguments that are passed in a function call are called actual arguments.These arguments are defined in the calling function. Formal arguments: The formal arguments are the parameters/arguments in a function declaration. The scope of formal arguments is local to the function definition in which they are used. Formal arguments belong to the called function. Formal arguments are a copy of the actual arguments. A change in formal arguments would not be reflected in the actual arguments 7. The scope of a declaration is the region of C program text over which that declaration is active.Top-level identifiers – Extends from declaration point to end of file and The extent of an object is the period of time that its storage is allocated. An object is said to have static extent when it is allocated storage at or before the beginning of program execution and the storage remains allocated until program termination. All functions have static extent, as do all variables declared in top-level declarations and variables declared with the static qualifier. 8. The C language does not have a global keyword. However, variables declared outside a function implicitly have a scope covering everything in the .c file or compilation unit containing its declaration. In a small program contained in a single file, such variables effectively have global scope. 9. Generally four types of storage classes are there in c. 1.Auto 2.Register 3.Static 4.Extern or Global 10. Register variables are a special case of automatic variables. Automatic variables are allocated storage in the memory of the computer; however, for most computers, accessing data in memory is considerably slower than processing in the CPU. These computers often have small amounts of storage within the CPU itself where data can be stored and accessed quickly. These storage cells are called registers. 11. A parameter passing mechanism is a mechanism or facility which is provided by a programming language to pass data (i.e. parameters) between a caller and a callee. reach out and touch call by value call by result or call by return(?) call by value result or call by value return call by reference call by name 12. Call By Value: Creates a new memory location for use within the subroutine. The memory is freed once it leaves the subroutine. Changes made to the variable are not affected outside the subroutine. Call By Reference: Passes a pointer to the
  • 55. Programming for Problem Solving Lab Page 55 BVRIT HYDERABAD College of Engineering for Women memory location .Changes made to the variable within the subroutine affects the variable outside the subroutine. 13. The function which calls the same function, is known as recursive function. Ex: recursionfunction(){ recursionfunction();//calling self function }
  • 56. Programming for Problem Solving Lab Page 56 BVRIT HYDERABAD College of Engineering for Women STRINGS 1) What is a string? 2) What is the difference between Strings and Arrays? 3) How to initialize a string? 4) How to read a line of text? 5) List predefined string handling functions in C. 6) Explain strcmp() function. 7) How to process array of strings? SOLUTIONS: 1. A string is a collection of characters. Strings are always enclosed in double quotes as "string_ constant". 2. A data item (or variable) is described as a "string" type when it contains some number of characters. Those characters can usually be anything in the system's accepted list of codes. Most systems use ASCII, so a string can include the letters a-z, A-Z, numbers 0-9, and special characters like ~!@#$%^&*()_+-=[]{}|:";'<>?,/. A string is treated as a single object, although most programming languages have methods to break strings apart (called sub-stringing). In the Perl language, strings are named $something. An array is a collection of individual data items, sort of like a list. Each element in an array can be referred to in a program by its position in the list. In the Perl language, an array would be named @SOMETHING. The first element in the array would be named $SOMETHING[0], the second $SOMETHING[1], and so on. Each element can be a string, or some other data type. 3. The string is created and initialized at the same time. For example: char string[] = "Hello there, Nerdly."; 4. In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines. 5. Any set or sequence of characters defined within double quotation symbols is a constant string.In c it is required to do some meaningful operations on the strings are str len( ), str cmp( ), str cpy( ), str cmpi( ),str lwr( ), str rev( ). 6. Strcmp will test two strings for equallity. Returns : < 0 if s1 is less than s2 0 if s1 == s2 > 0 if s1 is greater than s2 This function probably provides too much information by indicating which string is lexicographically greater. The net result means that the strcmp return code is logically incorrect because it returns a FALSE value when the strings match. 7. char * [100] var ; // declaration or char ** var; char *[] var= {"one","two","three"}; // initialize directly use loop either for or while for(int i = 0 ;i < no_of_string;i++) printf("%s",var[i]);
  • 57. Programming for Problem Solving Lab Page 57 BVRIT HYDERABAD College of Engineering for Women STRUCTURES 1. Define structure. which keyword is used to declare structure 2. What is the array of structure. why it is used 3. How memory is allocated for structure. what is the size of structure 4. What is the difference between structure and union 5. What is the structure within structure SOLUTIONS: 1. A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. Structures help to organize complicated data, particularly in large programs, because they permit a group of related variables to be treated as a unit instead of as separate entities. keyword is used to declare structure is STRUCT 2. Block of structures is referred as array of structures. It is used to hold data of different structures 3. Memory is allocated when a structure variable is created and size of structure is sum sizes of all the fields in a structure. 4. Structure and union use same prototype for declarationbut keywords used are struct and union. size of structure is sum sizes of all the fields in a structure where as size of union is size of the highest data field in structure memory is allocated to all field variable where as in union all variable share the highest data field‟s memory 5.Strucure with in the structure is called as nested structure .If a structure is having another structure as its member field then it is called as nested structure
  • 58. Programming for Problem Solving Lab Page 58 BVRIT HYDERABAD College of Engineering for Women FILES 1) What is the use of files? 2) What is the difference between text and binary files? 3) What are the operations that can be performed on files? 4) What are the different modes applied on files? 5) Explain about REWIND() function. SOLUTIONS: 1.A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. File is used to store data permanently. 2. A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time. A binary file is no different to a text file. It is a collection of bytes. r. Hence a binary file is also referred to as a character stream, but there are two essential differences. a.No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed. b. C Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer. c. Binary files can be either processed sequentially or, depending on the needs of the application, they can be processed using random access techniques 3. The operations that can be performed on files are: Reading (r): When an r is used, the file is opened for reading, a w is used to indicate a file to be used for writing, and an a indicates that you desire to append additional data to the data already in an existing file. Writing (w): When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to be a text file. Appending (a): When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of the present data so that any new data will be added to any data that already exists in the file. Using the a indicates that the file is assumed to be a text file. 4. The allowed modes for fopen are as follows: r - open for reading w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists)
  • 59. Programming for Problem Solving Lab Page 59 BVRIT HYDERABAD College of Engineering for Women 5. The rewind function sets the file position to the beginning of the file for the stream pointed to by stream. It also clears the error and end-of-file indicators for stream. Q: Explain Sieve of Eratosthenes algorithm with Example. Given a number n, print all primes smaller than or equal to n. It is also given that n is a small Number. For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”. The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n. Following is the algorithm to find all the prime numbers less than or equal to a given integer n by Eratosthenes‟ method: 1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n). 2. Initially, let p equal 2, the first prime number. 3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These numbers will be 2p, 3p, 4p, etc.; note that some of them may have already been marked. 4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3. When the algorithm terminates, all the numbers in the list that are not marked are prime.