KEMBAR78
Introduction To C Prog - Lab Manual 2022 Scheme | PDF | Computer Program | Programming
0% found this document useful (0 votes)
65 views44 pages

Introduction To C Prog - Lab Manual 2022 Scheme

The document is a lab manual for the course 'Introduction to C Programming' at The Oxford College of Engineering, detailing course objectives, teaching methods, and assessment criteria. It outlines the course structure, including modules on C programming concepts, and provides a list of lab assignments and suggested learning resources. The manual also specifies the evaluation methods for Continuous Internal Evaluation (CIE) and Semester End Examination (SEE), along with passing standards.

Uploaded by

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

Introduction To C Prog - Lab Manual 2022 Scheme

The document is a lab manual for the course 'Introduction to C Programming' at The Oxford College of Engineering, detailing course objectives, teaching methods, and assessment criteria. It outlines the course structure, including modules on C programming concepts, and provides a list of lab assignments and suggested learning resources. The manual also specifies the evaluation methods for Continuous Internal Evaluation (CIE) and Semester End Examination (SEE), along with passing standards.

Uploaded by

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

Administrative Office: 1st Phase J P Nagar, Bengaluru 560078 :080-3041 0501-502

(Recognized by the Govt. of Karnataka, Affiliated to Visvesvaraya Technological University, &


Approved by A.I.C.T.E. Accredited by NBA, NAAC with ‘A’ Grade. Recognized by UGC under section 2(f))
Bommanahalli, Hosur Road, Bengaluru –560068.
: 080 -61754 601/602/604/736E-mail: engprincipal@theoxford.edu/ email.. Web: www.theoxfordengg.org

Course Title: Introduction to C Programming

Course Code: BESCK104E/204E

2022 SCHEME

LAB MANUAL

Prepared by
Ms. J Jesy Janet Kumari,
Assistant Professor,
Dept of CSE, TOCE
16-2-2023

Course Title Introduction to C Programming


Course Code: BESCK104E/204E CIE Marks 50
Integrated SEE Marks 50
Course Type (Theory/Practical /Integrated )
Total Marks 100
Teaching Hours/Week (L:T:P: S) 2:0:2:0 Exam Hours 03
Total Hours of Pedagogy 40 hours Credits 03
CourseObjectives:

CLO 1. Elucidate the basic architecture and functionalities of a Computer


CLO 2. Apply programming constructs of C language to solve the real-world problems
CLO 3.Explore user-defined data structures like arrays, structures and pointers in implementing solutions to
problems
CLO 4. Design and Develop Solutions to problems using modular programming constructs such as
functions and procedures

Teaching-LearningProcess(GeneralInstructions)

ThesearesampleStrategies,whichteacherscanusetoacceleratetheattainmentofthevariouscourseoutcomes.
1. Lecturer method (L) need not to be only traditional lecture method, but alternative effective
teaching methods could be adopted to attain the outcomes.
2. Use of Video/Animation to explain functioning of various concepts.
3. Encourage collaborative (Group Learning)Learning in the class.
4. Ask atleast three HOT(Higher order Thinking) questions in the class,which promotes critical
thinking.
5. Adopt Problem Based Learning (PBL),which fosters students’ Analytical skills, develop design
thinking skills such as the ability to design, evaluate, generalize, and analyze information rather than
simply recall it.
6. Introduce Topics in manifold representations.
7. Show the different ways to solve the same problem and encourage the students to come up with
their own creative ways to solve them.
8. Discuss how every concept can be applied to the real world-and when that's possible, it helps to
improve the students' understanding.
9. Use https://pythontutor.com/visualize.html#mode=edit in order to visualize the operations of C Programs
Module-1 (6 Hours of Pedagogy)

Introduction to C: Introduction to computers, input and output devices, designing efficient programs.
Introduction to C, Structure of C program, Files used in a C program, Compilers, Compiling and executing C
programs, variables, constants, Input/output statements in C,
Textbook: Chapter 1.1-1.9, 2.1-2.2, 8.1 – 8.6, 9.1-9.14
Teaching-LearningProcess Chalkandtalkmethod/PowerPointPresentation

Module-2 (6 Hours of Pedagogy)

Operators in C, Type conversion and typecasting.

Decision control and Looping statements: Introduction to decision control, Conditional branching statements,
iterative statements, nested loops, break and continue statements, goto statement.
Textbook: Chapter 9.15-9.16, 10.1-10.6
Teaching-LearningProcess Chalkandtalkmethod/PowerPointPresentation

Module-3 (6 Hours of Pedagogy)

Functions: Introduction using functions, Function definition, function declaration, function call, return statement,
passing parameters to functions, scope of variables, storage classes, recursive functions.
Arrays: Declaration of arrays, accessing the elements of an array, storing values in arrays, Operations on arrays,
16-2-2023

Passing arrays to functions,


Textbook: Chapter 11.1-11.13, 12.1-12.6
Teaching-LearningProcess Chalkandtalkmethod/PowerPointPresentation
Module-4 (6 Hours of Pedagogy)

Two dimensional arrays, operations on two-dimensional arrays, two-dimensional arrays to functions, multidimensional
arrays.
Applications of arrays and introduction to strings:Applications of arrays, case study with sorting techinques.
Introduction to strings: Reading strings, writing strings, summary of functions used to read and write characters.
Suppressing input using a Scanset.
Textbook: Chapter 12.7-12.12
Teaching-LearningProcess Chalkandtalkmethod/PowerPointPresentation
Module-5 (6 Hours of Pedagogy)
Strings: String taxonomy, operations on strings, Miscellaneous string and character functions, arrays of strings.
Pointers: Understanding the Computers Memory,Introduction to Pointers, Declaring Pointer Variables
Structures: Introduction to structures

Textbook: Chapter 13.1-13.6, 14.1-14.3,15.1


Teaching-LearningProcess Chalkandtalkmethod/PowerPointPresentation
CourseOutcomes(CourseSkillSet)
Attheendofthecoursethestudentwillbeableto:
CO1. Elucidate the basic architecture and functionalities of a computer and also recognize
the hardware parts.
CO 2. Apply programming constructs of C language to solve the real world problem
CO 3.Explore user-defined data structures like arrays in implementing solutions to
problems like searching and sorting
CO 4.Explore user-defined data structures like structures, unions and pointers in
implementing solutions
CO5.Design and Develop Solutions to problems using modular programming constructs
using functions

Assessment Details (both CIE and SEE)


The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%. The
minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50). The minimum passing mark
for the SEE is 35% of the maximum marks (18 marks out of 50). A student shall be deemed to have satisfied the
academic requirements and earned the credits allotted to each subject/ course if the student secures not less than 35%
(18 Marks out of 50) in the semester-end examination(SEE), and a minimum of 40% (40 marks out of 100) in the sum
total of the CIE (Continuous Internal Evaluation) and SEE (Semester End Examination) taken together.
Continuous Internal Evaluation (CIE):
The CIE marks for the theory component of the IC shall be 30 marks and for the laboratory component 20
Marks.
CIE for the theory component of the IC
16-2-2023

 Three Tests each of 20 Marks; after the completion of the syllabus of 35-40%, 65-70%, and 90-
100% respectively.
 Two Assignments/two quizzes/ seminars/one field survey and report presentation/one-course
project totaling 20 marks.
Total Marks scored (test + assignments) out of 80 shall be scaled down to 30 marks
CIE for the practical component of the IC

 On completion of every experiment/program in the laboratory, the students shall be evaluated


and marks shall be awarded on the same day. The 15 marks are for conducting the experiment
and preparation of the laboratory record, the other 05 marks shall be for the test conducted at
the end of the semester.
 The CIE marks awarded in the case of the Practical component shall be based on the continuous
evaluation of the laboratory report. Each experiment report can be evaluated for 10 marks.
Marks of all experiments’ write-ups are added and scaled down to 15 marks.

 The laboratory test (duration 03 hours) at the end of the 15th week of the semester /after
completion of all the experiments (whichever is early) shall be conducted for 50 marks and
scaled down to 05 marks.

Scaled-down marks of write-up evaluations and tests added will be CIE marks for the laboratory component of
IC/IPCC for 20 marks.
 The minimum marks to be secured in CIE to appear for SEE shall be 12 (40% of maximum
marks) in the theory component and 08 (40% of maximum marks) in the practical component.
The laboratory component of the IC/IPCC shall be for CIE only. However, in SEE, the questions
from the laboratory component shall be included. The maximum of 05 questions is to be set
from the practical component of IC/IPCC, the total marks of all questions should not be more
than 25 marks.
The theory component of the IC shall be for both CIE and SEE.

Semester End Examination (SEE):


SEE for IC
Theory SEE will be conducted by University as per the scheduled time table, with common question papers for
the course (duration 03 hours)

1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a module (with a maximum of
3 sub-questions), should have a mix of topics under that module.
3. The students have to answer 5 full questions, selecting one full question from each module.
The theory portion of the Integrated Course shall be for both CIE and SEE, whereas the practical portion
16-2-2023

will have a CIE component only. Questions mentioned in the SEE paper shall include questions from the
practical component).

Passing standard:

 The minimum marks to be secured in CIE to appear for SEE shall be 12 (40% of maximum marks-30) in
the theory component and 08 (40% of maximum marks -20) in the practical component. The laboratory
component of the IPCC shall be for CIE only. However, in SEE, the questions from the laboratory
component shall be included. The maximum of 04/05 questions to be set from the practical component of
IPCC, the total marks of all questions should not be more than 30 marks.
 SEE will be conducted for 100 marks and students shall secure 35% of the maximum marks to qualify for
the SEE. Marks secured will be scaled down to 50.

Suggested Learning Resources:

Textbooks
1. Computer fundamentals and programming in c, “Reema Thareja”, Oxford University, Second edition, 2017.
Reference Books:
1. E. Balaguruswamy, Programming in ANSI C, 7th Edition, Tata McGraw-Hill.
2. Brian W. Kernighan and Dennis M. Ritchie, The ‘C’ Programming Language, Prentice Hall of India.

Web links and Video Lectures (e-Resources):


1. elearning.vtu.ac.in/econtent/courses/video/BS/15PCD23.html
2. https://nptel.ac.in/courses/106/105/106105171/ MOOC courses can be adopted for more clarity in
understanding the topics and verities of problem solving methods.

Activity Based Learning (Suggested Activities in Class)/ Practical Based learning


 Quizzes
 Assignments
 Seminars
Lab Assignments

1 C Program to find Mechanical Energy of a particle using E = mgh+1/2 mv2.


2 C Program to convert Kilometers into Meters and Centimeters.

3 C Program To Check the Given Character is Lowercase or Uppercase or Special Character.

4 Program to balance the given Chemical Equation values x, y, p, q of a simple chemical equation of the
type: The task is to find the values of constants b1, b2, b3 such that the equation is balanced on both
sides and it must be the reduced form.

5 ImplementMatrixmultiplicationandvalidatetherulesofmultiplication.
Computesin(x)/cos(x)usingTaylorseriesapproximation.Compareyou result withthebuilt-
6
inlibraryfunction.Printboththeresultswithappropriateinferences.
16-2-2023

7 SortthegivensetofNnumbersusingBubblesort.
Writefunctionstoimplementstringoperationssuchascompare,concatenate,stringlength.Convinceth
8
eparameterpassingtechniques.
Implementstructurestoread,writeandcomputeaverage-
9
marksandthestudentsscoringaboveandbelowtheaveragemarksforaclassofN students.
Developaprogramusingpointerstocomputethesum,meanandstandarddeviationofallelementsstored
10
inanarrayofNrealnumbers.
INTRODUCTION TO C Programming LAB
Steps involved in program development:-
To develop the program in high level language and translate it into
machine level language following steps have to be practiced.
1. Writing and editing the program.
2. Linking the program with the required library modules.
3. Compiling the program.
4. Executing the program.
Algorithm:-

It is a method of representing the step by step process for solving a


problem. Each step is called an instruction.
Characteristics of algorithm are:

• Finiteness:- It terminates with finite number of steps.

• Definiteness:- Each step of algorithm is exactly defined.


• Effectiveness:- All the operations used in the algorithm can be
performed exactly in a fixed duration of time.

• Input:- An algorithm must have an input before the execution of


program begins.
• Output:- An algorithm has one or more outputs after the execution
of the program.

Example of algorithm to find sum of two numbers:

Step1: BEGIN
Step2: READ a, b
Step3: ADD a and b and store in variable c
Step4: DISPLAY c
Step5: STOP

ABOUT C LANGUAGE

C is a programming language developed by Dennis Ritchie at AT&T‟s


BELL Laboratory of USA in 1972. Because of its reliability, C is very
popular. C is highly portable & it is well suited for structured
programming. C program consists of collection of functions.
HISTORY OF C

The milestones in C's development as a language are listed below:

1. BCPL - a user friendly OS providing powerful development tools


developed from BCPL c. 1967. Assembler was tedious, long and error
prone.
2. A new language “B” was attempted c. 1970 by Ken Thompson at Bell Labs.
3. UNIX was developed c. 1970 using “B” - DEC PDP-7 Assembly Language.
4. A totally new language “C”, a successor to “B” was developed c. 1971.
5. By 1973, UNIX OS was almost totally written in “C”.

Hardware Requirement: Desktop Computer / laptop computer.

Software Requirement: Linux Operating System with GCC / TURBO


C in WINDOWS OS / TURBO C++ in WINDOWS OS.

GCC

GCC is a Linux-based C compiler released by the Free Software


Foundation which is usually operated via the command line. It often
comes distributed freely with a Linux installation, so if you are running
UNIX or a Linux variant you will probably have it on your system. You
can invoke GCC on a source code file simply by typing:-
gcc filename
The default executable output of GCC is "a.out", which can be run by
typing “./a.out”. It is also possible to specify a name for the executable
file at the command line by using the syntax “ -o outputfile” , as shown
in the following example : -
gcc filename -o outputfile
Again, you can run your program with "./outputfile". (The ./ is there to
ensure you run the program for the current working directory.)
Note: If you need to use functions from the math library (generally
functions from “math.h” such as sin or sqrt), then you need to explicitly
ask it to link with that library with the “ –l ” flag and the library “m”:
gcc filename -o outputfile -lm
Turbo C/C++

Open Turbo C/C++ from your Desktop or Programs menu. Select “File”
from Menu bar and select option “New” and Save C program with
filename „.C‟ extension.
To do compiling – Select -> Compile from menu and click-> compile.
If the compilation is successful – you will see a “success” message. Else
you will see the number of errors.
To RUN the program – you may select ->Run from menu and click -> Run
Now you will see the output screen.

STRUCTURE OF “C‟ PROGRAM :

C program is a collection of several instructions where each instruction is


written as a separate statement. The C program starts with a main function
followed by the opening braces which indicates the start of the function.
Then follows the variable and constant declarations which are followed by
the statements that include input and output statements.
C program may contain one or more sections as shown below:
DOCUMENTATION SECTION
LINK SECTION
DEFINITION SECTION
GLOBAL DECLARATION SECTION
Main() Function section
{
Declaration part Executable part

}
SUBPROGRAM SECTION
User defined functions
Keywords

C has 32 keywords (reserved words with special meaning):

1. auto,
2. break,
3. case,
4. char,
5. const,
6. continue,
7. default,
8. do,
9. double,
10. else,
11. enum,
12. extern,
13. float,
14. for,
15. goto,
16. if,
17. int,
18. long,
19. register,
20. return,
21. short,
22. signed,
23. sizeof,
24. static,
25. struct,
26. switch,
27. typedef,
28. union,
29. unsigned,
30. void,
31. volatile, and
32. while.
Operators

C supports a rich set of operators, which are symbols used within an


expression to specify the manipulations to be performed while
evaluating that expression. C has the following operators:
arithmetic: +, -, *, /, %
assignment: =
augmented assignment: +=, - =, *=, /=, %=, &=, |=, ^=, <<=, >>=
bitwise logic: ~, &, |, ^
bitwise shifts: <<, >>
boolean logic: !, &&, ||
conditional evaluation: ? :
equality testing: = =, !=
calling functions: ( )
increment and decrement: ++ and - -
member selection: ., ->
object size: sizeof
order relations: <, <=, >, >=
reference and dereference: &, *, [ ]
sequencing: ,
subexpression grouping: ( )
type conversion: (typename)

SALIENT FEATURES OF C
C language has some characteristics that define the language and also have
led to its popularity as a programming language.
• Small size.
• Extensive use of function calls.
• Structured language.
• Low level (Bitwise) programming readily available.
Pointer implementation - extensive use of pointers for memory,
array, structures and functions.
• It has high-level constructs.
• It can handle low-level activities.
• It produces efficient programs.
• It can be compiled on a variety of computers.
LAB EXERCISE #1
Objective(s):
To be familiar with syntax and structure of C- programming. To learn
problem solving techniques using C

Program: Write a Program to calculate and display the volume of a


CUBE having its height (h=10cm), width (w=12cm) and
depth (8cm).

Algorithm:
1. Start
2. Define variables: h(int), w(int), d(int), vol(int)
3. Assign value to variables: h = 10, w=12, d=8
4. Calculate the volume as: vol = h*w*d
5. Display the volume (vol)
6. Stop

Flowchart:
Code: (Use comments wherever applicable)
//Following code is written and compiled in GCC

#include<stdio.h> void
main()
{
//start the program
int h,w,d,vol; //variables declaration h=10;w=12;d=8;
//assign value to variables
vol=h*w*d; //calculation using mathematical formula printf("The
Volume of the cube is: %d",vol); //display the volume
getch();
//end the main program
}
Output :
The Volume of the cube is: 960

SAMPLE PROGRAMS

Instructions

• Write comment to make your programs readable.


• Use descriptive variables in your programs(Name of the variables
should show their purposes)

Programs List
1. Write a C program to display “This is my first C Program”.
2. Write a C program to add two numbers (2 and 6) and display its sum.
3. Write a C program to multiply two numbers (4 and 5) and display its
product.
4. Write a C program to calculate area and circumference of a circle.
5. Write a C program to perform addition, subtraction, division
and multiplication of two numbers.
6. Write C program to evaluate each of the following equations.
(i) V = u + at. (ii) S = ut+1/2a (iii) T=2*a+√b+9c (iv) H = √ +
LAB EXERCISE #2

Objective(s):
To be familiar with different data types, Operators and Expressions in C.
Program: Write a program to take input of name, rollno and marks
obtained by a student in 4 subjects of 100 marks each and display the name,
rollno with percentage score secured.
Algorithm:
1. Start
2. Define variables: name, rollno, sub1, sub2, sub3, sub4, sum, score
3. Take input from keyboard for all the input variables
4. Calculate the sum of marks of 4 subjects and also calculate the
percentage score as:
sum = sub1 + sub2 + sub3 + sub4;
score = (sum/400) * 100
5. Display the name, roll number and percentage score.
6. Stop

Flowchart:
Code: (Use comments wherever applicable)
//Following code is written and compiled in TURBO C++

#include<stdio.h>
#include<conio.h>
void main()
{
char name[20]; int
rollno;
float sub1, sub2, sub3, sub4, , sum, score;
printf("Enter name of student: ");
scanf(“%s”,&name[]);
printf ("\n Enter Roll Number: "); scanf("%d",
&rollno);
printf ("\n Enter Marks in 4 Subjects:\n"); scanf("%f%f%f%f", &sub1,
&sub2, &sub3, &sub4); sum=sub1+sub2+sub3+sub4;
score = (sum/500)*100;
printf("\n Name of student: %s", name[]); printf("\n
Roll Number: %d", rollno);
printf ("\nPercentage score secured: %2.2f%c", score,'%'); getch();
}

Output:
Enter name of student: Ajit Singh
Roll Number: 25
Enter Marks in 4
Subjects: 50
75
85
62
Name of student: Ajit Singh
Roll Number: 25
Percentage score secured: 68.00%
1.C Program to find Mechanical Energy of a particle using E = mgh+1/2 mv2.
Program:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
const double ACCL_GRAV = 9.806;
int main()
{
double dMass, dHeight, dVelocity;
double dPotEng, dKinEng, dEng;
printf("\n*************************************************************");
printf("\n*\tProgram to find Mechanical Energy of a body\t *\n");
printf("*************************************************************");
printf("\nEnter the mass (in kg) of the body: "); scanf("%lf", &dMass);
printf("\nEnter the height (in metres) of the body: "); scanf("%lf", &dHeight);
printf("\nEnter the velocity (in meters per second) of the body: "); scanf("%lf", &dVelocity);
dPotEng = dMass * ACCL_GRAV * dHeight;
dKinEng = dMass * dVelocity * dVelocity/ 2;
dEng = dPotEng + dKinEng;
printf("\nPotential energy associated with the body is %0.3lf Joules\n", dPotEng);
printf("\nKinetic energy associated with the body is %0.3lf Joules\n", dKinEng);
printf("\nTotal energy associated with the body is %0.3lf Joules\n", dEng);
return 0;
}
Output:
*************************************************************
* Program to find Mechanical Energy of a body *
*************************************************************
Enter the mass (in kg) of the body: 80
Enter the height (in metres) of the body: 10
Enter the velocity (in meters per second) of the body: 10
Potential energy associated with the body is 7844.800 Joules
Kinetic energy associated with the body is 4000.000 Joules
Total energy associated with the body is 11844.800 Joules

2. Distance Conversion
Develop a C Program to convert Kilometers into Meters and Centimeters.
Program:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void)
{
double dDistKm, dDistMtr, dDistCm;
printf("\n*************************************************************");
printf("\n*\tProgram to convert Kilometers into Meters and Centimeters\t *\n");
printf("*************************************************************");
printf("\nEnter the distance in kilometers : "); scanf("%lf",&dDistKm);
dDistMtr = dDistKm * 1000;
dDistCm = dDistMtr * 100;
printf("\nThe distance entered in kilometers is : %0.3lf \n", dDistKm);
printf("\nEquivalent distance in meters is : %0.3lf \n", dDistMtr);
printf("\nEquivalent distance in centimeters is : %0.3lf \n", dDistCm);
return 0;
}
Output
***********************************************************************
* Program to convert Kilometers into Meters and Centimeters *
***********************************************************************
Enter the distance in kilometers : 63
The distance entered in kilometers is : 63.000
Equivalent distance in meters is : 63000.000
Equivalent distance in centimeters is : 6300000.000
***********************************************************************
Check Character case
3. Write a C program To Check the Given Character is Lowercase or Uppercase or Special
Character.
Program:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char cChar;
printf("\nEnter a character to be checked : "); scanf("%c", &cChar);
if(cChar >= 'a' && cChar <= 'z')
{
printf("\nThe character entered is a lower case character\n");
}
else if(cChar >= 'A' && cChar <= 'Z')
{
printf("\nThe character entered is a upper case character\n");
}
else if(cChar >= '0' && cChar <= '9')
{
printf("\nThe character entered is a digit\n");
}
else
{
printf("\nThe character entered is a special character\n");
}
return 0;
}
Output
***************************************
Enter a character to be checked : 1
The character entered is a digit
Enter a character to be checked : #
The character entered is a special character
Enter a character to be checked : s
The character entered is a lower case character
Enter a character to be checked : S
The character entered is a upper case character
***************************************

Balancing Chemical Equation


4. Write a C program to balance the given Chemical Equation values x, y, p, q of a simple chemical
equation of the type: The task is to find the values of constants b1, b2, b3 such that the equation
is balanced on both sides and it must be the reduced form.
Generic Chemical Equation Form b1 ∗ Ax + b2 ∗ By ⇒ b3 (Ap Bq)
Program:
#include<stdio.h>
#include<stdlib.h>
int fnGCD(int, int );
int main(void)
{
int x, y, p, q;
int b1, b2, b3;
int iCommDivisor;
printf("Enter the atomocity(x) of Element1 : "); scanf("%d", &x);
printf("Enter the atomocity(y) of Element2 : "); scanf("%d", &y);
printf("Enter the atomocity(p) of Element1 in the compound : "); scanf("%d", &p);

printf("Enter the atomocity(q) of Element2 in the compound : "); scanf("%d", &q);

b1 = p * y;
b2 = q * x;
b3 = x * y;
//if b1, b2 and b3 together have a greatest common divisor divide each one by that greatest
common divisor
iCommDivisor = fnGCD(b1,b2);
iCommDivisor = fnGCD(b3, iCommDivisor);
b1 = b1 / iCommDivisor;
b2 = b2 / iCommDivisor;
b3 = b3 / iCommDivisor;
printf("\nx = %d\ty = %d\tp = %d\tq = %d\n", x, y, p, q);
printf("\nb1 = %d\tb2 = %d\tb3 = %d\n", b1, b2,b3);
printf("\nBalanced Equation is now :\n\t%d*%d + %d*%d ==> %d(%d,%d)\n",
b1,x,b2,y,b3,p,q);
return 0;
}
/***************************************************************************
*Function : fnGCD
*Description : function to calculate GCD of two numbers
*Input parameters : iVal1 - non-negative integer, iVal2 - non-negative integer
*RETURNS : greatest common divisor of iVal1 and iVal2
***************************************************************************/
int fnGCD(int iVal1, int iVal2)
{
if (0 == iVal2)
return iVal1;
return fnGCD(iVal2, iVal1 % iVal2);
}
Output
***************************************
Enter the atomocity(x) of Element1 : 2
Enter the atomocity(y) of Element2 : 2
Enter the atomocity(p) of Element1 in the compound : 2
Enter the atomocity(q) of Element2 in the compound : 1
x=2 y=2 p=2 q=1
b1 = 2 b2 = 1 b3 = 2
Balanced Equation is now :
2*2 + 1*2 ==> 2(2,1)
Enter the atomocity(x) of Element1 : 2
Enter the atomocity(y) of Element2 : 3
Enter the atomocity(p) of Element1 in the compound : 4
Enter the atomocity(q) of Element2 in the compound : 5
x=2 y=3 p=4 q=5
b1 = 6 b2 = 5 b3 = 3
Balanced Equation is now :
6*2 + 5*3 ==> 3(4,5)
***************************************
Matrix Multiplication
5. Write a C program to implement Matrix multiplication and validate the rules of
multiplication.
Program
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int iM, iN, iP, iQ, i, j, k, iaMat1[10][10], iaMat2[10][10];
int iaProd[10][10] = {0};
printf("\n*********************************************************");
printf("\n*\tPROGRAM TO IMPLEMENT MATRIX MULIPLICATION\t*\n");
printf("*********************************************************");
printf("\nEnter the order of Matrix1\n");
scanf("%d%d",&iM,&iN);
printf("\nEnter the order of Matrix2\n");
scanf("%d%d",&iP,&iQ);
if( iN != iP)
{
printf("\nMatrix Multiplication not possible\n");
exit(0);
}
printf("\nEnter the elements of Matrix 1\n");
for(i=0;i<iM;i++)
for(j=0;j<iN;j++)
scanf("%d",&iaMat1[i][j]);
printf("\nEnter the elements of Matrix 2\n");
for(i=0;i<iP;i++)
for(j=0;j<iQ;j++)
scanf("%d",&iaMat2[i][j]);
for(i=0;i<iM;i++)
{
for(j=0;j<iQ;j++)
{
for(k=0;k<iN;k++)
{
iaProd[i][j] += iaMat1[i][k] * iaMat2[k][j];
}
}
}

/*********************************************************************************
*****************
|*| |*|
a00 a01 a02|*|b00 b01 b02|*|
|*| |*|
a10 a11 a12|*|b10 b11 b12|*|
|*| |*|
a20 a21 a22|*|b20 b21 b22|*|
|*| |*|

(a00*b00+a01*b10+a02*b20) (a00*b01+a01*b11+a02*b21) (a00*b02+a01*b12+a02*b22)


(a10*b00+a11*b10+a12*b20) (a10*b01+a11*b11+a12*b21) (a10*b02+a11*b12+a12*b22)
(a20*b00+a21*b10+a22*b20) (a20*b01+a21*b11+a22*b21) (a20*b02+a21*b12+a22*b22)
**********************************************************************************
****************/
printf("\nMatrix 1\n");
for(i=0;i<iM;i++)
{
for(j=0;j<iN;j++)
{
printf("%d\t",iaMat1[i][j]);
}
printf("\n");
}
printf("\n");

printf("\nMatrix 2\n");
for(i=0;i<iP;i++)
{
for(j=0;j<iQ;j++)
{
printf("%d\t",iaMat2[i][j]);
}
printf("\n");
}
printf("\n");
printf("\nThe Product matrix is is \n");
for(i=0;i<iM;i++)
{
for(j=0;j<iQ;j++)
{
printf("%d\t",iaProd[i][j]);
}
printf("\n");
}
printf("\n");
return 0;
}
Output
*********************************************************
* PROGRAM TO IMPLEMENT MATRIX MULIPLICATION *
*********************************************************
Enter the order of Matrix1
23
Enter the order of Matrix2
45
Matrix Multiplication not possible
*********************************************************
* PROGRAM TO IMPLEMENT MATRIX MULIPLICATION *
*********************************************************
Enter the order of Matrix1
23
Enter the order of Matrix2
32
Enter the elements of Matrix 1
123
456
Enter the elements of Matrix 2
12
34
56
Matrix 1
1 2 3
4 5 6
Matrix 2
1 2
3 4
5 6
The Product matrix is is
22 28
49 64
*********************************************************
* PROGRAM TO IMPLEMENT MATRIX MULIPLICATION *
*********************************************************
Enter the order of Matrix1
22
Enter the order of Matrix2
22
Enter the elements of Matrix 1
12
34
Enter the elements of Matrix 2
10
01
Matrix 1
1 2
3 4
Matrix 2
1 0
0 1
The Product matrix is is
1 2
3 4
***************************************
Compute Sine and Cosine of an Angle
6. Write a C program to compute sin(x)/cos(x) using Taylor series approximation. Compare
your result with the built-in library function. Print both the results with appropriate inferences.
Program
#include<stdio.h>
#include<stdlib.h>
#include <math.h>
int main()
{
float fAngD, fAngR;
float fTerm, fNum, fDen, fSVal,fCVal;
int i,iNum;
printf("\nEnter the Angle : "); scanf("%f",&fAngD);
printf("\nEnter the Number of terms : "); scanf("%d",&iNum);
printf("\nInput Angle = %g\n",fAngD);
printf("No of terms = %d\n",iNum);
fAngR= (fAngD*M_PI)/180 ;
//Calculation of Sine of an angle using Taylor's series
fNum=fAngR;
fDen=1.0;
fSVal =0.0;
fTerm=fNum/fDen;
for(i=1;i<=iNum;i++)
{
fSVal = fSVal + fTerm;
fNum = -fNum * fAngR * fAngR ;
fDen = fDen * (2*i) * (2*i+1);
fTerm = fNum/fDen;
}
//Calculation of Cosine of an angle using Taylor's series
fNum=1.0;
fDen=1.0;
fCVal =0.0;
fTerm=1.0;
for(i=1;i<=iNum;i++)
{
fCVal = fCVal + fTerm;
fNum = -fNum * fAngR * fAngR ;
fDen = fDen * (2*i) * (2*i-1);
fTerm = fNum/fDen;
}
printf("\nCalculated value is :\nSin(%g)/Cos(%g) = %g\n",fAngD, fAngD, fSVal/fCVal);
printf("\nBuilt In function value is :\nSin(%g)/Cos(%g) = %g\n", fAngD, fAngD,
sin(fAngR)/cos(fAngR));
return 0;
}
Output
***************************************
Enter the Angle : 60
Enter the Number of terms : 12
Input Angle = 60 No of terms = 12
Calculated value is : Sin(60)/Cos(60) = 1.73205
Built In function value is : Sin(60)/Cos(60) = 1.73205
=========================================
Enter the Angle : 30
Enter the Number of terms : 3
Input Angle = 30 No of terms = 3
Calculated value is :
Sin(30)/Cos(30) = 0.577334
Built In function value is :
Sin(30)/Cos(30) = 0.57735
=========================================
Enter the Angle : 45
Enter the Number of terms : 11
Input Angle = 45 No of terms = 11
Calculated value is :
Sin(45)/Cos(45) = 1
Built In function value is :
Sin(45)/Cos(45) = 1
****************************************************************************
Bubble Sort
7. Write a C program to sort the given set of N numbers using Bubble sort.
Program
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int iNum, i, j, iaArr[10], iTemp;
printf("\n*************************************************");
printf("\n*\tPROGRAM TO IMPLEMENT BUBBLE SORT\t*\n");
printf("*************************************************");
printf("\nEnter no of elements\n");
scanf("%d",&iNum);
printf("\nEnter the elements\n");
for(i=0;i<iNum;i++)
scanf("%d",&iaArr[i]);
for(i=0;i<iNum;i++)
{
for(j=0;j<iNum-i-1;j++)
{
if(iaArr[j] > iaArr[j+1])
{
iTemp = iaArr[j];
iaArr[j] = iaArr[j+1];
iaArr[j+1] = iTemp;
}
/*Code to show the program trace*/
/* printf("\nIteration i=%d, j=%d\n",i,j);*/
/* for(k=0;k<iNum;k++)*/
/* printf("%d\t",iaArr[k]);*/
}

printf("\nThe Sorted array is \n");


for(i=0;i<iNum;i++)
printf("%d\t",iaArr[i]);
printf("\n");
return 0;
}
Output
**********************************************************************************
* PROGRAM TO IMPLEMENT BUBBLE SORT *
**********************************************************************************
Enter no of elements
5
Enter the elements
21657
The Sorted array is
1 2 5 6 7
**********************************************************************************
* PROGRAM TO IMPLEMENT BUBBLE SORT *
**********************************************************************************
Enter no of elements
6
Enter the elements
975310
The Sorted array is
0 1 3 5 7 9
**********************************************************************************
String Operations
8. Write functions to implement string operations such as compare, concatenate, string length.
Convince the parameter passing techniques.
Program
#include<stdio.h>
#include<stdlib.h>
int fnMyStrCmp(const char*, const char*);
void fnMyStrCat(char*, const char*);
int fnMyStrLen(const char*);
int main()
{
int iChoice;
char acStr1[30], acStr2[30];
int iLen;
printf("\n=====================\n");
printf("STRING OPERATIONS");
printf("\n=====================\n");
for(;;)
{
printf("\nEnter two strings\n");
printf("\nString 1 : "); scanf("%s", acStr1);
printf("\nString 2 : "); scanf("%s", acStr2);
printf("\n1.String Compare\n2.String Concatenate\n3.String Length");
printf("\nEnter your choice : "); scanf("%d", &iChoice);
switch(iChoice)
{
case 1: if(fnMyStrCmp(acStr1, acStr2) == 0)
printf("\nTwo strings are equal");
else if(fnMyStrCmp(acStr1, acStr2) > 0)
printf("\nString %s is greater than String %s",
acStr1, acStr2);
else
printf("\nString %s is greater than String %s",
acStr2, acStr1);
break;

case 2: fnMyStrCat(acStr1, acStr2);


printf("\nConcatenated String is\n%s", acStr1);
break;
case 3: iLen = fnMyStrLen(acStr1);
printf("\nLength of String %s is %d\n", acStr1, iLen);
iLen = fnMyStrLen(acStr2);
printf("\nLength of String %s is %d\n", acStr2, iLen);
break;

}
printf("\nPress 1 to continue and 0 to quit : ");
scanf("%d", &iChoice);
if(0==iChoice)
{
break;
}
}
return 0;
}

/***************************************************************************
*Function : fnMyStrCmp
*Description : Function that compares the two strings s1 and s2.
*Input parameters : const char *s1, const char *s2 - two strings to be compared
*RETURNS
* 1 if s1 is greater than s2.
* 0 if s1 matches s2.
* -1 if s1 is less than s2.
***************************************************************************/
int fnMyStrCmp(const char *s1, const char *s2)
{
int k;
for(k=0; s1[k] == s2[k] && s1[k]!='\0'&& s2[k]!='\0'; k++);
if( k==(fnMyStrLen(s1)) && k==(fnMyStrLen(s2)) )
{
return 0;
}
else if(s1[k] > s2[k])
{
return 1;
}
else
{
return -1;
}
}
/***************************************************************************
*Function : fnMyStrCat
*Description : function that appends the src string to the dest string
*Input parameters :
* char *dest - first string
* const char *src - second string
*RETURNS : nothing
***************************************************************************/
void fnMyStrCat(char *dest, const char *src)
{
int dest_len, i;
dest_len = fnMyStrLen(dest);
for (i = 0 ; src[i] != '\0' ; i++)
dest[dest_len + i] = src[i];
dest[dest_len + i] = '\0';
}
/***************************************************************************
*Function : fnMyStrLen
*Description : function that calculates the length of a string
*Input parameters : const char *str - string whose length needs to be found
*RETURNS :
* integer which is the length of the string
***************************************************************************/
int fnMyStrLen(const char *str)
{
int iLen;
for(iLen=0; str[iLen] != '\0'; iLen++);
return iLen;
}
Output
*****************************************************************************
=====================
STRING OPERATIONS
=====================
Enter two strings
String 1 : Good
String 2 : Day
1.String Compare
2.String Concatenate
3.String Length
Enter your choice : 2
Concatenated String is
GoodDay
Press 1 to continue and 0 to quit : 1
Enter two strings
String 1 : ramesh
String 2 : sumesh
1.String Compare
2.String Concatenate
3.String Length
Enter your choice : 1
String sumesh is greater than String ramesh
Press 1 to continue and 0 to quit : 1
Enter two strings
String 1 : sam
String 2 : samantha
1.String Compare
2.String Concatenate
3.String Length
Enter your choice : 3
Length of String sam is 3
Length of String samantha is 8
Press 1 to continue and 0 to quit : 0
******************************************************************************
Question 9
C Structures
9. Write a C program to implement structures to read, write and compute average marks and
the students scoring above and below the average marks for a class of N students.
Program
#include<stdio.h>
#include<stdlib.h>
#define STRSIZE 30
typedef struct
{
char cName[STRSIZE];
char cUSN[11];
int iMarks;
}STUDENT_TYPE;
int main(void)
{
STUDENT_TYPE students[100];
int iNum, i;
double dAvg = 0.0;
printf("\nEnter the number of students : ");
scanf("%d", &iNum);
printf("\nEnter the Student details\n");
for(i=0;i<iNum;i++)
{
printf("\n###############################");
printf("\nName : "); scanf("%s", students[i].cName);
printf("\nUSN : "); scanf("%s", students[i].cUSN);
printf("\nMarks : "); scanf("%d", &students[i].iMarks);
dAvg += students[i].iMarks;
}
dAvg /= iNum;
printf("\nThe average marks for the class is : %g\n", dAvg);
for(i=0;i<iNum;i++)
{
printf("\n###############################");
printf("\nName\t: %s", students[i].cName);
printf("\nUSN\t: %s", students[i].cUSN);
printf("\nMarks\t: %d", students[i].iMarks);
if(students[i].iMarks < dAvg)
printf("\nThe student has scored below average\n");
else
printf("\nThe student has scored above average\n");
}

return 0;
}
Output
*********************************************************************************
Enter the number of students : 4
Enter the Student details
=========================================
Name : Raju
USN : 1SI17CS036
Marks : 67
=========================================
Name : Michael
USN : 1SI17CS045
Marks : 87
=========================================
Name : Sahana
USN : 1SI17CS405
Marks : 77
=========================================
Name : Jonathan
USN : 1SI17CS025
Marks : 83
The average marks for the class is : 78.5
=========================================
Name : Raju
USN : 1SI17CS036
Marks : 67
The student has scored below average
=========================================
Name : Michael
USN : 1SI17CS045
Marks : 87
The student has scored above average
=========================================
Name : Sahana
USN : 1SI17CS405
Marks : 77
The student has scored below average
=========================================
Name : Jonathan
USN : 1SI17CS025
Marks : 83
The student has scored above average
***************************************
Question 10
Pointers and Arrays
10. Develop a C program using pointers to compute the sum,mean and standard deviation of all
elements stored in an array of N real numbers.
Program
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void)
{
int i,iNum;
float fMean = 0.0f, fVariance = 0.0f, fSd = 0.0f,faArray[100],fSum=0.0f;
float *fptr;
printf("\nEnter the number of Values : ");
scanf("%d",&iNum);
fptr = faArray;
/* fptr = (float*)malloc(iNum*sizeof(float));*/
printf("\nEnter %d values\n", iNum);
for(i=0; i<iNum; i++)
{
scanf("%f",fptr+i);
fSum += *(fptr+i); //fSum += fptr[i]; this is also valid
}
fMean = fSum/iNum;
for(i=0; i<iNum; i++)
{
fVariance += (fptr[i] - fMean)*(fptr[i] - fMean);
//fVariance += (*(fptr+i) - fMean)*(*(fptr+i) - fMean);
}
fVariance /= iNum;
fSd = sqrt(fVariance);
printf("\nThe values entered are");
for(i=0; i<iNum; i++)
{
printf("\t%g",fptr[i]); //printf("\n\t%f",*(fptr+i));
}
printf("\n");
printf("\n**************************************\n");
printf("\tSum\t = \t%g\n\tMean\t = \t%g\n\tVariance = \t%g\nStandard Deviation =
\t%g",fSum,fMean,fVariance,fSd);
printf("\n**************************************\n");
return 0;
}
Output
***************************************
Enter the number of Values : 4
Enter 4 values
1.1 2.2 3.3 4.4
The values entered are 1.1 2.2 3.3 4.4
**************************************
Sum = 11
Mean = 2.75
Variance = 1.5125
Standard Deviation = 1.22984
**************************************
============================================================
Enter the number of Values : 5
Enter 5 values
5.345 6.765 7.234 8.675 9.765
The values entered are 5.345 6.765 7.234 8.675 9.765
**************************************
Sum = 37.784
Mean = 7.5568
Variance = 2.34995
Standard Deviation = 1.53295
**************************************
C Programming Viva Questions Answers

1. What is Compiler?

Compiler is a program that converts human readable code (source code) into
machine readable code, this process is called compilation.

2. What is Interpreter?

Interpreter converts human readable code (source code) into intermediate code
and then this intermediate code is executed line by line.

3. What is Assembler?

Assembler is a program that converts assembly level language (low level


language) into machine level language.

4. What is Protocol?

Protocol is nothing but a set of rules to be followed by a programmer.

5. What is IDE in C?

IDE is nothing but integrated development environment. IDE is a tool that


provides user to create, compile and execute C program. For example: Turbo
C++, DevC++. These provide integrated development environment.

6. What are Instructions?

In C instructions are the statements which tells computer to perform the specific
task.

7. What is C Programming Language?

C is a high level programming language. It is used to develop system software


and application software.

8. C language has been developed in which language?


C language has been developed using assembly language.

9. What is the difference between Text Files and Binary Files?

Text file contain data that can be easily understood by human. It includes letters,
numbers and other characters. On the other hand, binary files contain 1s and 0s
that only computers can interpret.

10. Is C a Structured Programming Language?

Yes, C language is structured language.

11. C is successor of which programming language?

12. What is Algorithm?

An algorithm refers to the step by step instructions written to solve any problem.

13. What is Flowchart?

A flowchart is a diagrammatic or symbolic representation of an algorithm. It uses


various symbols to represent the operations to be performed.

14. What are Library Functions?

Library functions are predefined functions and stored in .lib files.

15. What is a Program?

A computer program is a collection of the instructions necessary to solve a


specific problem.

16. What is Object Code?

Compilation process translates source code into binary language. This binary
language code is known as object code.

17. What is Executable Code?

This code contains object code and definition of predefined function from library.
This code is written in binary language.

18. What is void in C language?

Void is an empty data type that has no value. We use void data type in functions
when we don’t want to return any value to the calling functions.

19. What is the meaning of Header File? Name some Header Files.

Header files contain declaration of predefined functions. We can use any number
of header files in our program as per the requirement of predefined functions.
Some header files are: stdio.h, conio.h, math.h, stdlib.h, string.h, graphics.h

20. Can I create a customized Header File in C language?

It is possible to create a new header file. Create a file with function prototypes
that need to be used in the program. Include the file in the ‘#include’ section in
its name.

21. Explain the use of comma operator (,).

Comma operator can be used to separate two or more expression.

22. What is the use of printf() function?

The printf() function is used to print the integer, character, float and string values
on to the screen or console. It is a predefined function.

23. What is the use of scanf() function?

The scanf() function is used to take input from the user or read some values from
screen (or console). It is a predefined function.

24. What is Console?

Console is known as output screen through which user interacts with the source
code.

25. What is #include?

It is a pre-processor directive. It is used to include any header file in our program.

You might also like