0% found this document useful (0 votes)
51 views84 pages

Programming in C Lab Manual

The document outlines the curriculum for the Programming in C course (CS1003) at RV University for the academic year 2024-2025, detailing the vision, mission, program educational objectives, and course outcomes. It includes a comprehensive list of programming assignments and evaluation criteria for mid-term and semester-end assessments. The course aims to equip students with fundamental programming skills and problem-solving abilities in C programming.

Uploaded by

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

Programming in C Lab Manual

The document outlines the curriculum for the Programming in C course (CS1003) at RV University for the academic year 2024-2025, detailing the vision, mission, program educational objectives, and course outcomes. It includes a comprehensive list of programming assignments and evaluation criteria for mid-term and semester-end assessments. The course aims to equip students with fundamental programming skills and problem-solving abilities in C programming.

Uploaded by

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

Design and Analysis of Algorithms 2023-2024

Rashtreeya Sikshana Samithi Trust


RV UNIVERSITY
School of Computer Science and Engineering
Bengaluru – 560059

PROGRAMMING IN C
COURSE CODE: CS1003
I SEMESTER B.Tech (Hons.)

LABORATORY RECORD 2024-2025

Dept. of CSE, RV College of Engineering®, Bengaluru i


RV UNIVERSITY
School of Computer Science and Engineering
Bengaluru – 560 059

LABORATORY CERTIFICATE

This is to certify that Mr./Ms. has


satisfactorily completed the course of experiments in Practical Programming in C
(CS1003) prescribed by the School of Computer Science and Engineering during the
year 2024-25.

Name of the Candidate:

USN: Semester:

Marks

Maximum Obtained

25

Signature of Faculty In-charge Program Director

Date:
CS1003 : Programming in C (2024–2025)

Vision and Mission of the School of Computer Science and


Engineering

Vision
To be a pioneering school of Computer Science and Engineering committed to fostering
liberal education and empowering the next generation of technologists to make a positive
global socio-economic impact.

Mission

 To be a pioneer in computer science education and benchmark ourselves with the


world's top computer science and engineering institutions.

 To provide state-of-the-art facilities that enable exemplary pedagogy, advanced


research, innovation and entrepreneurship in emerging technologies of computer
science.

 To promote a culture of cooperation and inclusiveness among students and faculty


from diverse communities enabling them to take part in interdisciplinary and
multidisciplinary research, contributing to institution-building.

 To foster excellence through national and international academic, industry


collaborations, bringing in diverse perspectives to drive innovation.

 To nurture a talented pool of ethical, self-driven and empathetic problem solvers to


achieve sustainable development goals.

SoCSE, RV University, Bengaluru iv


CS1003 : Programming in C (2024–2025)

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


PEO1: Graduates will be able to demonstrate excellence in the field of Computer Science and
Engineering through advanced research and entrepreneurship.

PEO2: Graduates will be able to achieve excellence in innovation through national and international
academic and industry collaborations.

PEO3: Graduates will be able to actively engage in cutting-edge interdisciplinary and multidisciplinary
research.

PEO4: Graduates will be able to function effectively as talented pool of ethical, sustainable, self-driven
and life-long empathetic problem solvers.

PROGRAM OUTCOMES (POs)

Engineering Graduates will be able to:

PO1: Engineering Knowledge. Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.

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

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

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

PO5: Modern Tool Usage. Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities
with an understanding of the limitations.

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

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

PO8: Individual and Teamwork. Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.

PO9: Ethics. Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
SoCSE, RV University, Bengaluru v
CS1003 : Programming in C (2024–2025)

PO10: Communication. Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

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

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

SoCSE, RV University, Bengaluru vi


CS1003 : Programming in C (2024–2025)

Course Outcomes: After completing the course, the students will be able to:

CO1 Understand and analyze the concepts of number system, memory, fundamental concepts in
C programming language.

CO2 Demonstrate fundamental data types, operators and console I/O functions in C.

CO3 Implement programs using decision control statements, control flow statements, arrays,
strings, functions, and pointers to solve mathematical problems.

CO4 Analyze and evaluate the programming concepts based on user defined data types and file
handling in C language.

CO5 Design and implement appropriate concepts of C to solve real-world problems.

SoCSE, RV University, Bengaluru vii


CS1003 : Programming in C (2024–2025)

LIST OF PROGRAMS

PART – A
S. No. Program
1.  Write a program using function-like macros to add two numbers.
 Write a program to find the area of a circle using macros.
2.  Write a program to swap two numbers with and without using a third variable.
 Write a program to compute and display area/perimeter and surface area/volume
of different 2D/3D shapes respectively
 Write a program to print a grocery bill.
3.  Write a program to find the roots of the quadratic equation ax^2+bx+c=0.
 Write a program to create a menu-driven basic arithmetic calculator.
 Write a program to print an electricity bill.
 Write a program to print the marksheet of a student.
4.  Write a program to print the number of digits in an integer and their sum.
 Write a program to print different patterns on the screen.
 Write a program to print a Fibonacci series up to a given number of terms.
 Write a program to compute GCD of two numbers.
 Write a program to find Armstrong numbers in the given range of numbers.
5.  Write a program to obtain prime factors of a given number using function.
 Write a program to find factorial of a number using function.
 Write a program to print nth term of a Fibonacci series using function.
 Write a program to compute GCD of two numbers using function.
 Write a program to swap two numbers using function.
6.  Write a program to find factorial of a number using recursion.
 Write a program to print a Fibonacci series using recursion.
 Write a program to compute GCD of two numbers using recursion.
 Write a program to print the number of digits in an integer and their sum using
recursion.
7.  Write a menu driven program to demonstrate the following array operations
using functions: Insert, Delete, Update element at index i, Swap elements at two
indices, Linear search, Search all the occurrences, Search the first occurrence,
Search the last occurrence, Find duplicates, Remove duplicates, Find minimum,
and Find maximum.
8.  Write a program to implement Bubble and Insertion sort using functions.
 Write a program to implement binary search using function.
 Write a program to print matrix multiplication using function.
 Write a program to traverse a two-dimensional array in spiral order using
function.
9.  Write a program to implement different string operations using functions.
10.  Write a program using pointer to structures to read, write and compute average-
marks of a student. Take student name, USN, and marks in 5 subjects as input.
Use functions.
 Write a program using structures to read, write and compute average-marks of n
students. Take student name, USN, and marks in 5 subjects as input. Pass
structure by reference to a function to update marks in one of the five subjects as
given by user for a particular student. Finally display the new average for that
student.
11. Write a program to demonstrate different file operations in C.
SoCSE, RV University, Bengaluru viii
CS1003 : Programming in C (2024–2025)

PART – B
Mid-Term Evaluation (8 Marks):
A problem will be given to each student from a pool of problems. The problem pool is prepared based on
the topics covered till the middle of the semester. The solution has to be produced within the allotted time
frame. Tentative syllabus will include all the topics till functions and recursion.

Semester-End Evaluation (10 marks):


Students have to work either alone or in a group (consisting of two students at the maximum). Firstly,
students have to choose an application that can be developed using the C programming language
concepts covered in the course. Each student or group should discuss the opted topic with the
corresponding lab or lecture faculty to get it finalized. This whole process has to be completed by the
middle of the semester.

After the finalization of the topic, the student or group works on the problem and design its solution.
During this phase students and lab or lecture faculty may get involved in several discussion sessions.
Simultaneously, students have to proceed with the implementation of the proposed solution. The
submission will be done at the end of the semester (before semester end examination) by means of the
following artefacts prepared by the students:

 Project report. The soft copy template of the project report will be shared with the students.
 Complete implementation of the solution to the chosen problem.
 Demonstration of the working implementation.

*
Note: 7 marks will be given by lab faculty based the performance of a student in labs throughout the semester.
SoCSE, RV University, Bengaluru ix
CS1003 : Programming in C (2024–2025)

INDEX

Marks Signature
Faculty
S. No. Program Name Record Viva-voce In-charge
(6M) (4M) with date
1. 1a. Write a program using function-like macros to add two
numbers.
1b. Write a program to find the area of a circle using macros.

2. 2a. Write a program to swap two numbers with and without


using a third variable.
2b. Write a program to compute and display area/perimeter and
surface area/volume of different 2D/3D shapes respectively
2c. Write a program to print a grocery bill.

3. 3a. Write a program to find the roots of the quadratic equation


ax^2+bx+c=0.
3b. Write a program to create a menu-driven basic arithmetic
calculator.
3c. Write a program to print an electricity bill.

3d. Write a program to print the marksheet of a student.

4. 4a. Write a program to print the number of digits in an integer


and their sum.
4b. Write a program to print different patterns on the screen.

4c. Write a program to print a Fibonacci series up to a given


number of terms.
4d. Write a program to compute GCD of two numbers.

4e. Write a program to find Armstrong numbers in the given


range of numbers.
5. 5a. Write a program to obtain prime factors of a given number
using function.
5b. Write a program to find factorial of a number using
function.
5c. Write a program to print nth term of a Fibonacci series
using function.

SoCSE, RV University, Bengaluru x


CS1003 : Programming in C (2024–2025)

Marks Signature
S. No. Program Name Faculty
Record Viva-voce
In-charge
(6M) (4M) with date
5d. Write a program to compute GCD of two numbers using
function.
5e. Write a program to swap two numbers using function.

6. 6a. Write a program to find factorial of a number using


recursion.
6b. Write a program to print a Fibonacci series using
recursion.
6c. Write a program to compute GCD of two numbers using
recursion.
6d. Write a program to print the number of digits in a number
and their sum using recursion.
7. 7a. Write a menu driven program to demonstrate the
following array operations using functions: Insert, Delete,
Update element at index i, Swap elements at two indices,
Linear search, Search all the occurrences, Search the first
occurrence, Search the last occurrence, Find duplicates,
Remove duplicates, Find minimum, and Find maximum.
8. 8a. Write a program to implement Bubble and Insertion sort
using functions.
8b. Write a program to implement binary search using
function.
8c. Write a program to print matrix multiplication using
function.
8d. Write a program to traverse a two-dimensional array in
spiral order using function.
9. 9a. Write a program to implement different string operations
using functions.
10. 10a. Write a program using pointer to structures to read, write
and compute average-marks of a student. Take student
name, USN, and marks in 5 subjects as input. Use
functions.
10b. Write a program using structures to read, write and
compute average-marks of n students. Take student name,
USN, and marks in 5 subjects as input. Pass structure by
reference to a function to update marks in one of the five
subjects as given by user for a particular student. Finally
display the new average for that student.

SoCSE, RV University, Bengaluru xi


CS1003 : Programming in C (2024–2025)

Marks Signature
S. No. Program Name Faculty
Record Viva-voce
In-charge
(6M) (4M) with date
11. 11a. Write a program to demonstrate different file operations
in C.

Total

*To be filled in by Faculty In-charge on or after the last lab of the semester

Number of Number of labs Attendance Record Viva-voce Record + Viva-voce


labs conducted attended (2 Marks) (66 Marks) (44 Marks) (110 Marks) (5 Marks)

Record + Viva-voce
Total = Attendance +=
(7 Marks) (2 Marks) (5 Marks)

Signature with date


(Faculty In-charge)

SoCSE, RV University, Bengaluru xii


Programming in C 2024- 2025

PART – B

Write-up, execution, and viva-voce rubrics for Mid-term evaluation (Max: 8 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(1 Marks) related concepts. concepts (0.25 M or 0 M)
(1 M) (0.75 M or 0.5 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(1 Marks) (1 M) solving. (0.25 M or 0 M)
(0.75 M or 0.5 M)

Total
Signature with date:
(Faculty In-charge)

SoCSE, RV University, Bengaluru xiii


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for Semester-end evaluation (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Overall effectiveness of Project Report The purpose and focus of the The purpose and focus of the The purpose and focus of the
communication writing are clear, organized well, writing are sufficient enough to writing are not communicated
(2 Mark) and the content presented communicate clearly and clearly.
achieves the purpose well. effectively. (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

2 Flow and division of Project Report Information is presented in a Information is presented in a Information presented is difficult
information logical way within appropriate logical way sometimes within to follow.
(2 Mark) sections which is easy to follow. inappropriate sections. Bit (0.5 M or 0 M)
(2 M) difficult to follow.
(1.5 M or 1 M)

3 Project Demonstration Implementation All modules are working properly All modules are working Modules are not working
(2 Mark) and demonstrated well. All properly in isoltaion and properly that leads to the failure
modules are integrated properly demonstrated well. All modules of the overall system.
and project is working accurately. are not integrated properly and (0.5 M or 0 M)
(2 M) project is not working very
satisfactorily.
(1.5 M or 1 M)

4 Project Technicalities Implementation Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
(2 Marks) and the approach used along with and the approach with related and approach.
related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Signature with date: Total


(Faculty In-charge)
SoCSE, RV University, Bengaluru xiv
Programming in C 2024- 2025

*To be filled in by Faculty In-charge on or after the last lab of the semester
Recor Mid- End-
Total Total
d+ term term Final
Part Part
Viva- Evalu Evalu Total
Attendance A B
voce ation ation (25
(2 Marks) (7 (18
(5 (8 (10 Mark
Mark Mark
Mark Mark Mark s)
s) s)
s) s) s)

Signature with date


(Faculty In-charge)

SoCSE, RV University, Bengaluru


xv
Programming in C 2024- 2025

PART – A
PROGRAM – 1
Pre-requisites:

 Data-types with their sizes, ranges, and format specifiers

Data Type Size (bytes) Range Format Specifier


short int 2 -32,768 to 32,767 %hd
unsigned short int 2 0 to 65,535 %hu
unsigned int 4 0 to 4,294,967,295 %u
Int 4 -2,147,483,648 to 2,147,483,647 %d
long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long int 4 0 to 4,294,967,295 %lu
long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 1.2E-38 to 3.4E+38 %f
double 8 1.7E-308 to 1.7E+308 %lf
long double 16 3.4E-4932 to 1.1E+4932 %Lf

 sizeof operator
Queries size of the object or type. Used when actual size of the object must be known.

Syntax:
1. sizeof(type) – Returns the size, in bytes, of the object representation of type.
2. sizeof(type) – Returns the size, in bytes, of the object representation of the type of expression. No
implicit conversions are applied to expression.

Example: Sample output corresponds to a platform with 64-bit pointers and 32-bit int.
#include <stdio.h>
int main(void)
{ printf("sizeof(float) = %zu\n", sizeof(float));
printf("sizeof &main = %zu\n", sizeof &main);
}

Possible output:
sizeof(float) =4
sizeof &main =8

School of CSE, RV University, Bengaluru 16


Programming in C 2024- 2025

 Escape sequences

Escape
Character represented
sequence
\a Alert (Beep, Bell)
\b Backspace
\f Formfeed Page Break
\n Newline (Line Feed)
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
\\ Backslash
\' Apostrophe or single quotation mark
\" Double quotation mark
\? Question mark (used to avoid trigraphs)

 Macros
A macro is a fragment of code which has been given a name. Whenever the name is used, it
is replaced by the contents of the macro. There are two kinds of macros. They differ mostly
in what they look like when they are used. Object-like macros resemble data objects when
used, function-like macros resemble function calls.
By convention, macro names are written in upper case. The macro's body ends at the end of
the `#define' line. You may continue the definition onto multiple lines, if necessary,

using backslash-newline. There is no restriction on what can go in a macro body


provided it decomposes into valid preprocessing tokens. The C preprocessor scans
your program sequentially. Macro definitions take effect at the place you write
them. Therefore, the following input to the C preprocessor
foo = X;
#define X 4 foo = X;
produces bar = 4;
bar = X;

Below is a macro that computes the minimum of two numeric values


#define min(X, Y) ((X) < (Y) ? (X) : (Y))
x = min(a, b); ==> x = ((a) < (b) ? (a) : (b));
y = min(1, 2); ==> y = ((1) < (2) ? (1) : (2));

School of CSE, RV University, Bengaluru 17


Programming in C 2024- 2025

School of CSE, RV University, Bengaluru 18


Programming in C 2024- 2025

List of Programs for Lab 1

1a. Write a program using function-like macros to add two numbers.


Syntax:
#define MACRO_NAME(params) MACRO_BODY
where MACRO_NAME is name of the macro. params is parameters passed to macro.
MACRO_BODY is the body which will have actual logic of macro.

Pseudocode:
User input: num 1, num 2
Output: ∑ ¿
1. Define a macro named ADD(x, y) that computes the sum of x and y .
2. Set ∑ ¿ 0.
3. Call the ADD macro with num 1 and num 2 as arguments and store the result in ∑ ¿.
4. Display the result: "The sum of" num 1 " and " num 2 " is " ∑ ¿.

1b. Write a program to find the area of a circle using macros.


Syntax:
#define MACRO_NAME(params) MACRO_BODY
where MACRO_NAME is name of the macro. params is parameters passed to macro.
MACRO_BODY is the body which will have actual logic of macro.

Pseudocode:
User input: r , i.e. radius of the circle.
Output: sum
1. Define a macro for the value of π (pi). Let PI =3.1416.
2. Define another macro for calculating the area. Let AREA (radius)=PI∗radius∗radius.
3. Call the AREA macro with r as argument and store the result in area .
4. Display the result: "Area of the circle with radius as " r "is " area .

School of CSE, RV University, Bengaluru 19


Programming in C 2024- 2025

Stick Data sheets of Program-1 here:

School of CSE, RV University, Bengaluru 20


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 21


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 22


Programming in C 2024- 2025

PROGRAM – 2
Pre-requisites:

 Arithmetic Operators.

Operato Operator Exampl


Result
r name e
+ addition a+b the addition of a and b
- subtraction a-b the subtraction of b from a
* product a*b the product of a and b
/ division a/b the division of a by b
% remainder a%b the remainder of a divided by b

 Relational or Comparison Operators.

Operator name Syntax Result


Equal to a == b Returns true if a is equal to b, false otherwise.
Not equal to a != b Returns true if a is not equal to b, false otherwise.
Less than a < b Returns true if a is less than b, false otherwise.
Greater than a > b Returns true if a is greater than b, false otherwise.
Less than or equal to a <= b Returns true if a is less than or equal to b, false otherwise.
Greater than or equal to a >= b Returns true if a is greater than or equal to b, false otherwise.

 Logical Operators.

Operato
Operator name Example Result
r
! logical NOT !a the logical negation of a
&& logical AND a && b the logical AND of a and b
|| logical OR a || b the logical OR of a and b

 Conditional/Ternary Operator.

Operator name Syntax


conditional operator a ? b : c

 Increment and Decrement Operators.

Operator name Syntax Operator name Syntax


pre-increment ++a post-increment a++
pre-decrement --a post-decrement a--

School of CSE, RV University, Bengaluru 23


Programming in C 2024- 2025

 Bit-wise Operators.

Operato Exampl
Operator name Result
r e
~ bitwise NOT ~a the bitwise NOT of a
& bitwise AND a&b the bitwise AND of a and b
| bitwise OR a|b the bitwise OR of a and b
^ bitwise XOR a^b the bitwise XOR of a and b
<< bitwise left shift a << b a left shifted by b
bitwise right
>> a >> b a right shifted by b
shift

 Compound Assignment Operators.

Operator name Syntax


addition assignment a += b
subtraction assignment a -= b
multiplication assignment a *= b
division assignment a /= b
remainder assignment a %= b
bitwise AND assignment a &= b
bitwise OR assignment a |= b
bitwise XOR assignment a ^= b
bitwise left shift assignment a <<= b
bitwise right shift assignment a >>= b

 Type Conversion and Type Casting


Type conversion is the process of converting one data type to another only if the conversion
is possible. There are two types of conversion:
o Implicit/Automatic Type Conversion – It is automatically done by the compiler without
any external trigger from the user. In the presence of more than one data type in an
expression type conversion (type promotion) takes place to avoid any loss of data.
Though loss of information is possible sometimes, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long is implicitly
converted to float). Data type of the variables gets upgraded to the data type of the
variable with the largest data type. Here is the sequence from smallest to the largest data
type:
bool -> char -> short int -> int -> unsigned int -> long ->
School of CSE, RV University, Bengaluru 24
Programming in C 2024- 2025

unsigned -> long long -> float -> double -> long double
Example:
#include <stdio.h>
int main()
{ int x = 10; Output:
char y = 'a'; x = 107, z = 108.000000
x = x + y;
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
}

o Explicit Type Conversion/Type casting – It is user-defined, i.e. the user can typecast
the result to make it of a particular data type. Syntax: (type) expression, where type
indicates the data type to which the final result is converted.
Example:
#include <stdio.h>
int main()
{ Output:
float a = 1.5; a = 1.500000
int b = (int)a; b=1
printf("a = %f\n", a);
printf("b = %d\n", b);
}

 2D Shapes – Area and Perimeter Formulas


Shape Area Perimeter Terms
Circle A = π × r2
Circumference = 2 × π × r r = radius of the circle
b = base, h = height
Triangle A=½×b×h S=a+b+c
a, b and c are the sides of the triangle
Square A=a×a P=4×a a = length of side
Rectangle A=l×w P = 2 × (l + w) l = length, w = width
Parallelogram A = b × h P = 2 × (a+b) a = side, b=base, h=vertical height

 3D Shapes – Area and Perimeter Formulas


Name Perimeter Total / Curved / Lateral Surface Area Volume
Cuboid 4 × (l + b + h) Total = 2 × (l × b + b × h + h × l) l×b×h
Curved / Lateral = 2 × h × (l + b)
l = length, b = breadth, h = height
Cube 6×a Total = 6 × a × a a×a×a
Curved / Lateral = 4 × a × a
a = side of a cuboid
Cylinder - Total = 2 × π × r × (r + h) π×r×r×h
Curved / Lateral = 2 × π × r × h
r = radius, h = height
Cone - Total = π × r × (r + l) (1/3) × π × r × r × h
Curved / Lateral = π × r × l
School of CSE, RV University, Bengaluru 25
Programming in C 2024- 2025

Name Perimeter Total / Curved / Lateral Surface Area Volume


r = radius, h = height, l = slant height
Sphere - Total = 4 × π × r × r (4/3) × π × r × r × r
Curved / Lateral = 4 × π × r × r
r = radius
Hemisphere - Total = 3 × π × r × r (2/3) × π × r × r × r
Curved / Lateral = 2 × π × r × r
r = radius

List of Programs for Lab 2

2a. Write a program to swap two numbers with and without using a third variable.
Pseudocode (with a third variable):
User input: num 1, num 2
Output: ∑ ¿
1. Declare a variable, say temp .
2. Assign num 1 to temp .
3. Assign num 2 to num 1.
4. Assign temp to num 2.
5. Display the result:
"Value of num1 = " num 1
"Value of num2 = " num 2

Pseudocode (without a third variable):


https://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/

2b. Write a program to compute and display area/perimeter and surface area/volume of different
2D/3D shapes respectively.
Pseudocode (area and perimeter of a rectangle):
User input: length , breadth
Output: area , perimeter
1. Declare a variable, say area .
2. Calculate area=length× breadth.
3. Display "The area of a rectangle with length = " length " and breadth = " breadth " is " area .
4. Declare a variable, say perimeter .
5. Calculate perimeter=2 ×(length+breadth).
6. Display "The perimeter of a rectangle with length = " length " and breadth = " breadth " is "
perimeter .
Pseudocode (surface area and volume of a cuboid):
School of CSE, RV University, Bengaluru 26
Programming in C 2024- 2025

User input: length , breadth , height


Output: surfaceArea, volume
1. Declare a variable, say surfaceArea.
2. Calculate surfaceArea=2×(length × breadth+breadth × height +height ×length).
3. Display "The total surface area of a cuboid with length = " length ", breadth = " breadth "
and height = " height " is " surfaceArea.
4. Declare a variable, say volume.
5. Calculate volume=lenght × breadth ×height .
6. Display "The volume of a cuboid with length = " length ", breadth = " breadth " and height
= " height " is " volume.

2c. Write a program to print a grocery bill.


Pseudocode:
// Let there are 5 grocery items.
1. Declare variables, say totalItem 1, pricePerItem 1 , …totalItem 5, pricePerItem 5.
2. Declare variables itemBill 1, itemBill 2, itemBill 3, itemBill 4 , and itemBill 5.
3. Calculate itemBill 1=totalItem 1× pricePerItem 1.
4. Similarly calculate itemBill 2, itemBill 3, itemBill 4 , and itemBill 5.
5. Declare a variable totalBill .
6. Calculate totalBill=itemBill 1+itemBill 2+itemBill 3+itemBill 4+itemBill 5
7. Declare a variable, say tax . Calculate tax=totalBill× 0.05.
8. Declare a variable, say gst . Calculate gst=totalBill +tax .
9. Display the bill:
Item1 totalItem 1 pricePerItem 1itemBill 1
Item2 totalItem 2 pricePerItem 2itemBill 2
Item3 totalItem 3 pricePerItem 3 itemBill 3
Item4 totalItem 4 pricePerItem 4 itemBill 4
Item5 totalItem 5 pricePerItem 5 itemBill 5
Total totalBill
Tax tax
Total Amount gst

School of CSE, RV University, Bengaluru 27


Programming in C 2024- 2025

Stick Data sheets of Program-2 here:

School of CSE, RV University, Bengaluru 28


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 29


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 30


Programming in C 2024- 2025

PROGRAM – 3
Pre-requisites:

Media Source:
https://media.geeksforgeeks.org/wp-content/uploads/20230424101456
/Conditional-Statements-in-c.webp

 Roots of a Quadratic Equation

−b ± √ b2−4 ac
The roots of a quadratic equation, a x 2 +bx +c are given by the quadratic formula: x= .
2a

List of Programs for Lab 3

3a. Write a program to find the roots of the quadratic equation ax^2+bx+c=0.
Pseudocode:
User input: coefficients of the equation, i.e. a , b , c
1. Declare a variable discriminant . Calculate discriminant =( b ×b )−(4 × a ×c ).
2. Declare two variables, root 1 and root 2.
3. If discriminant > 0
4. Calculate root 1=(−b+ √ (discriminant ))/(2× a).
5. Calculate root 2=(−b−√ ( discriminant))/(2 × a) .
6. Display "Two real and different roots are" root 1 and root 2.
7. Else if discriminant =0
School of CSE, RV University, Bengaluru 31
Programming in C 2024- 2025

8. Calculate root 1=−b/(2× a).


9. Display "Two real and equal roots are" root 1 and root 1.
10. Else
11. Declare two variables real and imaginary .
12. Calculate real=−b /(2 × a).
13. Calculate imaginary=√ (−discriminant)/(2× a).
14. Display "Two imaginary roots are" real +iimaginary " and " real−i imaginary .

3b. Write a program to create a menu-driven basic arithmetic calculator.

Pseudocode:
User input: num 1, num 2 and choice of operation, choice .
1. Display the menu with choices for operations – addition, subtraction, multiplication and
division.
2. Read the user’s choice .
3. Execute the block of code corresponding to choice and display the result.
Note: The program should handle division by ZERO.

3c. Write a program to print an electricity bill.


 First 50 units – Rs. 4/unit
 For next 100 units – Rs. 6/unit
 For next 100 units – Rs. 7/unit
 Above 250 units – Rs. 8/unit
 Add 20% additional surge charge to the bill amount

Pseudocode:
User input: numberOfUnits .
1. Declare a variable, totalBill .
2. If numberOfUnits ≤50 , then calculate totalBill=4 × numberOfUnits.
3. Else if numberOfUnits ≤150 , then calculate totalBill=4 ×50+ ( numberOfUnits−50 ) ×6 .
4. Else if numberOfUnits ≤250 , then calculate
totalBill=4 ×50+ 100× 6+ ( numberOfUnits −150 ) × 7.
5. Else calculate totalBill=4 ×50+ 100× 6+100 ×7+ ( numberOfUnits−250 ) × 8.
6. Calculate totalBill=totalBill ×1.2.
7. Display the result, i.e. totalBill .

3d. Write a program to print the marksheet of a student.


School of CSE, RV University, Bengaluru 32
Programming in C 2024- 2025

 Percentage of marks >= 80 – Grade A.


 Percentage of marks >= 70 and < 80 – Grade B.
 Percentage of marks >= 60 and < 70 – Grade C.
 Percentage of marks >= 50 and < 60 – Grade D.
 Percentage of marks < 50 – Fail.

Pseudocode:
// Let there are 5 subjects. Maximum marks in a subject is 100.
1. Declare five variables, marks 1, marks 2, marks 3 , marks 4 , and marks 5 .
2. Read marks in five subjects, i.e. marks 1, marks 2, marks 3 , marks 4 , and marks 5 .
3. Calculate totalMarks and percentage.
4. Calculate grade as per the given conditions.
5. Display the complete marksheet, i.e. marks in five subjects, total, percentage, and grade.

School of CSE, RV University, Bengaluru 33


Programming in C 2024- 2025

Stick Data sheets of Program-3 here:

School of CSE, RV University, Bengaluru 34


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 35


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 36


Programming in C 2024- 2025

PROGRAM – 4
Pre-requisites:

Media Source: https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191128194516/Cpp-loops.png

 Break and Continue


Break statement: This statement terminates the smallest enclosing loop. Syntax: break;
Continue statement: This statement skips the rest of the loop statement and starts the next iteration of
the loop. Syntax: continue;

 Factorial of a Number
The factorial of a number, i.e. n !, is the product of all positive integers less than or equal to n . For
example, the factorial of 4 , i.e. 4 !=4 ×3 × 2× 1=24 . 0 ! is defined as 1.

 Fibonacci Series/Sequence/Numbers
It is defined as the sequence of numbers in which each number in the sequence is equal to the sum of
two numbers before it. The Fibonacci Sequence is given as: 0 , 1 ,1 , 2 ,3 , 5 , 8 ,13 ,21 , …. The next
number in sequence is obtained by adding the previous two terms, i.e., 13+21=34.

 Greatest Common Divisor (GCD) / Highest Common Factor (HCF) of two Numbers
It is the greatest common factor that divides the two numbers perfectly.
Euclid’s division algorithm:
It is stated only for positive integers. Let the positive integers be a and b , assuming a> b.
 Apply Euclid’s division lemma to a and b and get two whole numbers q and r such that, a=bq+ r ;
0< r <b.
 If r =0, then b is the HCF of a and b . If r ≠ 0, then apply Euclid’s division lemma to b and r .
 Continue the process until the remainder is zero.
 When the remainder is zero, the divisor at that stage is the GCD or HCF of the given numbers.
School of CSE, RV University, Bengaluru 37
Programming in C 2024- 2025

 Armstrong / Narcissistic Number


An Armstrong number is a number that is equal to the sum of its digits each raised to the power of the
number of digits. Let ABC…N be a number with ‘n’ digits, where A, B, C, …, N are the digits of the
number. Then, ABC … N = An + Bn +C n +…+ N n.
Example: 153=13+5 3+ 33=1+125+27=153

List of Programs for Lab 4

4a. Write a program to print the number of digits in an integer and their sum.
Pseudocode:
User input: num
1. Declare and initialize variables, ∑ ¿ 0 and count=0.
2. Repeat (3) to (5) till num ≠0 .
3. Increase count by 1.
4. Get the rightmost digit of num using the remainder operator, i.e. num % 10, and add it to
∑ ¿.
5. Remove the rightmost digit of num using the division operator, i.e. num=num/10 .
6. Print the result:
'The number of digits in ' num ' is ' count '. The sum of the digits in ' num ' is ' ∑ ¿.

4b. Write a program to print different patterns on the screen.


https://www.geeksforgeeks.org/pattern-programs-in-c/

4c. Write a program to print a Fibonacci series up to a given number of terms.


Pseudocode:
User input: A positive integer, n.
- Declare and initialize two variables, a=0 and b=1.
- Declare a variable, c .
- Print the values of a and b .
- For each iteration from 3 to n .
a. Compute the next Fibonacci number, i.e. c=a+b .
b. Update a to the value of b .
c. Update b to the value of c .
d. Print the values of c .

School of CSE, RV University, Bengaluru 38


Programming in C 2024- 2025

4d. Write a program to compute GCD of two numbers.


Pseudocode:
User input: The two numbers, num 1 and num 2.
1. Declare and initialize a variable, a=maximum of num 1∧num 2.
2. Declare and initialize a variable, b=minimum of num1∧num2.
3. Declare and initialize a variable, R=0.
4. Repeat (5) to (7) until R becomes ZERO.
5. Update R to the value of a % b.
6. Update a to the value of b .
7. Update b to the value of R .
8. Print the result:
'GCD of ' num 1 ' and ' num 2 ' is ' a .

4e. Write a program to find Armstrong numbers in the given range of numbers.
Pseudocode:
User input: num
1. Declare and initialize variables, ∑ ¿ num and count=0.
2. Repeat (3) and (4) till ∑ ≠ 0 .
3. Increase count by 1.
4. Remove the rightmost digit of ∑ ¿ using the division operator, i.e. ∑ ¿ ∑ ¿10 .
5. Declare and initialize a variable, numTemp=num and count=0.
6. Repeat (6) to (8) till num ≠0 .
7. Remove the rightmost digit of num using the division operator and store it in a variable temp
, i.e. temp=num % 10.
8. Update ∑ ¿ ∑ + tempcount .
9. Remove the rightmost digit of num using the division operator, i.e. num=num/10 .
10. If the numTemp is equal to ∑ ¿, then return true, else false.

School of CSE, RV University, Bengaluru 39


Programming in C 2024- 2025

Stick Data sheets of Program-4 here:

School of CSE, RV University, Bengaluru 40


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 41


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 42


Programming in C 2024- 2025

PROGRAM – 5
Pre-requisites:

 Local and Global Variables


Local Global
Scope Declared within a specific block of code, Declared outside of any function or block
such as a function or loop. They are only of code, usually at the top of a program or
accessible within the block in which they in a separate file. They are accessible from
are declared. any part of the program.
Lifetime Exists only while the block is executing. Retain their value throughout the lifetime
Once the block of code in which they are of the program unless explicitly modified
declared exits, their memory is released, or reset. They persist throughout the entire
and they are no longer accessible. execution.
Name Can have the same name as variables in Should be used carefully to avoid
Conflicts other blocks without conflict. unintended side effects, as they are
accessible from anywhere.
Usage Used for temporary storage or data Used for values that need to be accessed
relevant only within a specific context and modified by multiple parts of the
program.

 Pointer
A derived data type that can store the address of other variables or a memory location. One can access
and manipulate the data stored in that memory location using pointers. The size of pointers only
depends on the system architecture and is independent of the type of data they are pointing to.
Pointers should always be initialized to some value before their first usage. Otherwise, it may lead to
number of errors.
- Pointer Declaration: Declare the pointer using dereference operator, i.e. *, before its name. Such an
uninitialized pointer will point to some random memory address and is known as wild pointer.
- Pointer Initialization: Assign some initial value to the pointer variable, i.e. the memory address of a
variable using the addressof (i.e., &) operator.
Example:
int var = 10;
int * ptr; // Pointer declaration
ptr = &var; // Pointer initialization
// int *ptr = // Pointer definition: Declare and initialize the pointer in a single step.
&var;
- Pointer Dereferencing: Accessing the value stored in the memory address specified in the pointer
using the dereferencing operator, i.e. *.
Following are the valid pointer arithmetic operations: Increment, Decrement, Addition or Subtraction
of integer to a pointer, Subtraction or Comparison or Assignment of pointers of the same type.

School of CSE, RV University, Bengaluru 43


Programming in C 2024- 2025

 Functions
The construct function associates the function body with the function name. C program begins
execution from the main function, which either terminates, or invokes other, user-defined or library
functions.
// Definition of a function with the name "sum" and with the body "{ return x + y; }"
int sum(int x, int y)
{
return x + y;
}

A function declaration or a function definition introduces a function. Functions may accept zero or
more parameters, which are initialized from the arguments during a function call, and may return a
value to its caller by means of the return statement.
int n = sum(1, 2); // parameters x and y are initialized with the arguments 1 and 2

There are no nested functions. Each function definition must appear at file scope, and functions have
no access to the local variables from the caller.
int sum(int, int); // function declaration
int main(void) // the main function definition
{ int x = 1; // local variable in main
sum(1, 2); // function call
}
int sum(int a, int b) // function definition
{
//return x + a + b; //error: main's x is not available
within sum
return a + b;
}
The data passed when the function is being invoked is known as the Actual parameters. In the above
program, 1 and 2 are known as actual parameters. Formal Parameters are the variable and the data
type as mentioned in the function declaration. In the above program, a and b are known as formal
parameters. One can pass arguments in two ways:
- Pass by Value: Values are copied from actual parameters into formal function parameters. As a
result, any changes made inside the functions do not reflect in the caller’s parameters.
- Pass by Reference: The caller’s actual parameters and the function’s formal parameters refer to
the same memory locations, so any changes made inside the function are reflected in the caller’s
actual parameters.

School of CSE, RV University, Bengaluru 44


Programming in C 2024- 2025

List of Programs for Lab 5

5a. Write a program to obtain prime factors of a given number using function.
Approach:
User input: num
1. While num is divisible by 2, print 2 and divide num by 2.
2. After (1), num must be odd.
3. Start a loop from i=3 to the square root of num.
a. While i divides num, print i, and divide num by i .
b. After i fails to divide num, increment i by 2 and continue.
4. Print num if it is greater than 2.

5b. Write a program to find factorial of a number using function.


Pseudocode:
User input: num
1. Declare and initialize two variables, ¿!1 and i=1.
2. Repeat until i≤num
a. Update ¿!¿!i
b. Increment i by one.
3. Print the result:
'Factorial of ' num 1 ' is ' ¿!.

5c. Write a program to print nth term of a Fibonacci series using function.
Pseudocode:
User input: A positive integer, n.
1. Declare and initialize two variables, a=0 and b=1.
2. Declare a variable, c .
3. If n=1, then print the value of a .
4. If n=2, then print the value of b .
5. For each iteration from 3 to n .
a. Compute the next Fibonacci number, i.e. c=a+b .
b. Update a to the value of b .
c. Update b to the value of c .
6. Print the result:
n 'th Fibonacci term is ' c .

School of CSE, RV University, Bengaluru 45


Programming in C 2024- 2025

5d. Write a program to compute GCD of two numbers using function.


Refer pseudocode for Lab Program 4d.

5e. Write a program to swap two numbers using function.


Refer pseudocode for Lab Program 2a.

School of CSE, RV University, Bengaluru 46


Programming in C 2024- 2025

Stick Data sheets of Program-5 here:

School of CSE, RV University, Bengaluru 47


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 48


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 49


Programming in C 2024- 2025

PROGRAM – 6
Pre-requisites:

 Recursion
It is the process of a function calling itself repeatedly till the given condition is satisfied. A function
that calls itself directly or indirectly is called a recursive function and such kind of function calls are
called recursive calls. The basic syntax structure of the recursive functions is as follows:
function_return_type function_name (function_input_args) {
// function statements
// base condition
// recursion case (recursive call)
}
Example:

int printSum(int n)
{ if(n == 0)
return 0;
else
return n + printSum(n-1);
}
int main()
{ printf("%d\n",printSum(5));
}

List of Programs for Lab 6

6a. Write a program to find factorial of a number using recursion.


Base Case: n !=1 if n=0 or n=1
Recursive Formula: n !=n∗( n – 1 ) !

6b. Write a program to print a Fibonacci series using recursion.


Base Case: F 0=0 and F 1=0
Recursive Formula: F n=F n−1+ F n−2

6c. Write a program to compute GCD of two numbers using recursion.


Pseudocode:
User input: num 1 and num 2
Function Name: GCD(x , y)
1. Base Case : If y=0 then return x .
2. Recursive Formula: Else call GCD( y , x % y )

School of CSE, RV University, Bengaluru 50


Programming in C 2024- 2025

6d. Write a program to print the number of digits in an integer and their sum using recursion.
Pseudocode:
User input: num 1
Function Name: countAndSumDigits (num1)
1. Declare and initialize a static int variable, i=0 .
2. Base Case : If num1=0
a. Print the 'Count of digits is ' i.
b. return 0 .
3. Recursive Formula: Else
a. Increase the value of i by 1.
b. return n % 10 + call countAndSumDigits (num1 /10)

School of CSE, RV University, Bengaluru 51


Programming in C 2024- 2025

Stick Data sheets of Program-6 here:

School of CSE, RV University, Bengaluru 52


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 53


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 54


Programming in C 2024- 2025

PROGRAM – 7
Pre-requisites:

 Array Declaration
1D Array: datatype arrayName [size];
2D Array: datatype arrayName [size1] [size2];
3D Array: datatype arrayName [size1] [size2] [size3];
n D Array: datatype arrayName [size1] [size2] ... [sizen];

 Array Initialization
- datatype arrayName [size] = {value1, value2, ... value N };
- datatype arrayName [] = {value1, value2, ... value N };
- Initialize array after declaration by individually assigning values to each element using loops.

 Array and Pointers


The array name is a constant pointer to the first element of the array and the array decomposes to the
pointers when passed to the function. One can return an array from a function using a pointer to the
first element of that array.

List of Programs for Lab 7

7a. Write a menu driven program to demonstrate the following array operations using functions:
Insert, Delete, Update element at index i, Swap elements at two indices, Linear search, Search
all the occurrences, Search the first occurrence, Search the last occurrence, Find duplicates,
Remove duplicates, Find minimum, and Find maximum.

Let A [MAX ] be an array having N elements.

- Pseudocode: INSERT
User input: A new value to be inserted, say num 1 at index, say index .
Function Name: insert (A , N , MAX , num1 , index)
1. If N=MAX then return.
2. Else
a. N=N + 1
b. For all elements from A [index] to A [N ] move to next adjacent location.
c. A [ index ] =num 1

- Pseudocode: DELETE
School of CSE, RV University, Bengaluru 55
Programming in C 2024- 2025

User input: An index, say index , whose value has to be deleted.


Function Name: delete ( A , N ,index)
1. If N=0then return .
2. Else
a. For all elements from A [index+1] to A [N ] move to previous adjacent location.
b. N=N −1

- Pseudocode: UPDATE ELEMENT AT INDEX i


User input: A new value to be updated, say num 1 at index, say index .
Function Name: update( A , N , num1 , index)
1. If N=0then return .
2. Else A [ index ] =num 1

- Pseudocode: SWAP ELEMENTS AT TWO INDICES


User input: Two indices whose values to be swapped, say i n dex 1 and index 2.
Function Name: swap( A , N ,index 1 , index 2)
1. If N=0then return .
2. Else A [ index 1 ] ↔ A [index 2] // Swap values at indices index 1 and index 2.

- Pseudocode: LINEAR SEARCH or SEARCH THE FIRST OCCURRENCE //Unsorted array


User input: A value to be searched, say n um.
Function Name: linearSearch( A , N , n um)
1. If N=0then return .
2. Else
a. For each index , 0 to N−1 , in an array A
i. If A [ index ] =n um then return the index .
b. Return −1.

- Pseudocode: SEARCH ALL THE OCCURRENCES // Unsorted array


User input: A value to be searched, say num.
Function Name: search AllOccurrences(A , N ,num)
1. Declare and initialize a variable, say flag=0 .
2. If N=0then return .
3. Else
a. For each index , 0 to N−1 , in an array A
i. If A [ index ] =n um then print the index .
ii. flag=1
b. If flag=0 then print num ' is not present'.

- Pseudocode: SEARCH THE LAST OCCURRENCE // Unsorted array


School of CSE, RV University, Bengaluru 56
Programming in C 2024- 2025

User input: A value to be searched, say num.


Function Name: search Last Occurrences (A , N ,num)
1. Declare and initialize a variable, say flag=−1.
2. If N=0then return .
3. Else
a. For each index , 0 to N−1 , in an array A
i. If A [ index ] =n um then flag=index .
b. return flag.

- Pseudocode: FIND DUPLICATES // Unsorted array


Function Name: findDuplicate s ( A , N )
1. Declare and initialize a variable, say flag=0 .
2. If N=0then return .
3. Else
a. For each index , 0 to N−1 , in an array A
i. flag=0 .
ii. For each i, index+1 to N−1 , in an array A
o If A [ index ] = A [i] then flag++¿.
iii. If flag≠ 0 then print A [index] .

- Pseudocode: REMOVE DUPLICATES // Unsorted array


Function Name: remove Duplicates( A , N )
1. If N=0then return .
2. Else
a. For each index , 0 to N−1 , in an array A
i. For each i, index+1 to N−1 , in an array A
o If A [ index ] = A [i] then call delete ( A , N ,i).

- Pseudocode: FIND MINIMUM // Unsorted array


Function Name: findMinimum( A , N )
1. Declare and initialize a variable, say min Index=0.
2. If N=0then return .
3. Else
a. For each index , 1 to N−1 , in an array A
i. If A [ index ] < A[m in Index] then min Index=i ndex .
b. Return min Index .

- Pseudocode: FIND MAXIMUM // Unsorted array


Function Name: findM ax imum( A , N )
School of CSE, RV University, Bengaluru 57
Programming in C 2024- 2025

1. Declare and initialize a variable, say m ax Index=0.


2. If N=0then return .
3. Else
a. For each index , 1 to N−1 , in an array A
i. If A [ index ] > A[m axIndex] then m ax Index=index .
b. Return m ax Index .

School of CSE, RV University, Bengaluru 58


Programming in C 2024- 2025

Stick Data sheets of Program-7 here:

School of CSE, RV University, Bengaluru 59


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 60


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 61


Programming in C 2024- 2025

PROGRAM – 8
 Selection Sort
Pseudocode:
Function Name: s electionSort (∫ Arr [n ])
1. For i=0 to n−2
2. m∈¿ i
3. For j=i+1 to n−1
4. If ( Arr [ min ] > Arr [ j ] )
5. m∈¿ j
6. If (i≠ min)
7. Arr [i]↔ Arr [min ]

List of Programs for Lab 8

8a. Write a program to implement Bubble and Insertion sort using functions.
Pseudocode:
Function Name: b ubble Sort (∫ Arr [n])
1. For i=1 to n−1
2. flag=0
3. For j=1 to n−i
4. If ( Arr [ j−1 ] > Arr [ j ] )
5. Arr [ j−1]↔ Arr [ j]
6. flag=1
7. If (flag)
8. continue
Pseudocode:
Function Name: i nsertion Sort (∫ Arr [n])
1. For i=1 to n−1
2. key =Arr [ i ]
3. j=i−1
4. While j> 0 and Arr [ j ] > key
5. Arr [ j+1 ] =Arr [ j ]
6. j−−¿
7. A [ j+1 ] =key
School of CSE, RV University, Bengaluru 62
Programming in C 2024- 2025

8b. Write a program to implement binary search using function.


Pseudocode:
Function Name: binary S earch(∫ Arr [ n ] ,∫ num)
1. ¿ 0, ¿=n−1
2. While ¿ ¿
3. mid=(¿¿)/2
4. If ( Arr [ mid ]=num ) then return mid
5. Else if Arr [ mid ] <num then ¿ mid +1
6. Else ¿=mid−1
7. Return −1

8c. Write a program to print matrix multiplication using function.


Pseudocode:
Function Name: matrixMultiplication (∫ A [ n ] [m], ∫ B[m][ p ])

1. ∫ C [ n ] [ p]
2. For i from 0 to n−1
3. For j from 0 to p−1
4. C [ i ] [ j]=0
5. For k from 0 to m−1
6. C [ i ][ j ]=C [ i ][ j ] + A [ i ] [ k ] × B [ k ] [ j]

8d. Write a program to traverse a two-dimensional array in spiral order using function.
Pseudocode:
Function Name: spiralTraversal(∫ A [ n ] [m])
1. rowStart =0 , rowEnd=n−1
2. col Start=0 , col End=m−1
3. While rowStart ≤ rowEnd and colStart ≤ colEnd
4. For col from colStart to colEnd Print A [ rowStart ] [col]
5. For row from row Start + 1 to row End Print A [ row ] [col End ]
6. If rowStart <rowEnd
7. For col from col End−1 to col Start Print A [ row End ] [col]
8. If c o l Start < c o l End
9. For row from row End−1 to row Start + 1 Print A [ row ] [col Start ]
10. rowStart ++¿, row End−−¿
School of CSE, RV University, Bengaluru 63
Programming in C 2024- 2025

11. col Start ++¿, colEnd −−¿

Stick Data sheets of Program-8 here:

School of CSE, RV University, Bengaluru 64


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 65


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 66


Programming in C 2024- 2025

PROGRAM – 9
 Strings in C
A String is a sequence of characters terminated with a null character ‘\0’. It is stored as an array of characters.
Syntax
Declaration char str[size]; // size is some integer.
Initialization char str[] = "ProgrammingInC";
char str[20] = "ProgrammingInC";
char str[12] =
{'P','r','o','g','r','a','m','m','i','n','g','\0'};
char str[] = {'P','r','o','g','r','a','m','m','i','n','g','\
0'};
Print on screen printf("%s",str); OR puts(str)
Read from user scanf("%s",str); // till the whitespace is encountered.
fgets(str,#numberOfCharacters,stdin) // to read a line of
string.

gets(str) // to read a line of characters from the standard


input.
scanf("%[^\n]s", str); // to read a line of string.

 string.h Header File


This header file defines several functions to manipulate C strings and arrays.
memcpy Copy block of memory
void * memcpy (void * destination, const void * source, size_t
num);
memmov Move block of memory
e void * memmove (void * destination, const void * source,
size_t num);
strcpy Copy string
char * strcpy (char * destination, const char * source);
strncpy Copy characters from string
char * strncpy (char * destination, const char * source,
size_t num);

School of CSE, RV University, Bengaluru 67


Programming in C 2024- 2025

strcat Concatenate strings


char * strcat (char * destination, const char * source);
strncat Append characters from string
char * strncat (char * destination, const char * source,
size_t num);
memcmp Compare two blocks of memory
int memcmp (const void * ptr1, const void * ptr2, size_t num);
strcmp Compare two strings
int strcmp (const char * str1, const char * str2);
strncmp Compare characters of two strings
int strncmp (const char * str1, const char * str2, size_t
num);
memchr Locate character in block of memory
const void * memchr (const void * ptr, int value, size_t num);
strchr Locate first occurrence of character in string
const char * strchr (const char * str, int character);
strcspn Get span until character in string
size_t strcspn (const char * str1, const char * str2);
strpbrk Locate characters in string
const char * strpbrk (const char * str1, const char * str2);
strrchr Locate last occurrence of character in string
const char * strrchr (const char * str, int character);
strspn Get span of character set in string
size_t strspn (const char * str1, const char * str2);
strstr Locate substring
const char * strstr (const char * str1, const char * str2);
strtok Split string into tokens
char * strtok (char * str, const char * delimiters);
memset Fill block of memory
void * memset (void * ptr, int value, size_t num);
strerror Get pointer to error message string
char * strerror (int errnum);
strlen Get string length
School of CSE, RV University, Bengaluru 68
Programming in C 2024- 2025

size_t strlen (const char * str);

List of Programs for Lab 9

9a. Write a program to implement different string operations using functions.


Pseudocode:
Function Name: stringLength(char str [n])
1. Declare and initialize a variable, length=0
2. While str [length] is not ' ¿ '
3. length++¿
4. Return length

Pseudocode:
Function Name: subS tring Matching (char str 1 [ n ] , char str 2[m])
1. Declare and initialize two variables, temp=0 and flog=0
2. For i=0 and str 1[i]≠ ' ¿ '
3. flag=1
4. For j=0 and str 2[ j]≠ ' ¿ '
5. If (str 1[i+ j]≠ str 2 [ j])
6. flag=0
7. Break
8. If flag=1 then temp++ ¿
9. Return temp , i.e. the number of matches.

Pseudocode:
Function Name: reverse String (char str [ n ] )
1. For i=0 , j=strlen ( str )−1 ; i≤ j ; i++ , j−−¿
2. str [i]↔ str [ j]

Pseudocode:
Function Name: s tringCopy (char str 1 [ n ] , char str 2[m])
1. For i=0 and str 1[i]≠ ' ¿ '
2. str 2[i]=str 1[i]

Pseudocode:
Function Name: stringCo mpare (char str 1 [ n ] , char str 2[m])
School of CSE, RV University, Bengaluru 69
Programming in C 2024- 2025

1. For i=0 and str 1 [ i ] =str 2 [ i ] ∧¿ str 1 [ i ] =' ¿ '


2. If (str 1 [ i ] < str 2 [ i ] ) then print 'str1 is less than str2'.
3. If (str 1 [ i ] > str 2 [ i ] ) then print 'str2 is less than str1'.
4. Else print 'str1 is equals to str2'.

School of CSE, RV University, Bengaluru 70


Programming in C 2024- 2025

Stick Data sheets of Program-9 here:

School of CSE, RV University, Bengaluru 71


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 72


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 73


Programming in C 2024- 2025

PROGRAM – 10
 Structures
It is a user-defined data type used to group items of different types into a single type.
Syntax
Declaration struct structureName {
dataType memberName1;
(no memory is allocated)
dataType memberName2;
....
};
Defining an instance struct structureName {
dataType memberName1;
(creating variables of
dataType memberName2;
structure type)
....
} variable1, varaible2, ...;
// structure declared beforehand
struct structureName variable1, variable2, .......;
Accessing members // structure declared beforehand
struct structureName variable1, variable2, .......;
variable1.memberName1;
variable1.memberName2;
variable2.memberName1;
.......;
// structure declared beforehand
struct structureName variable1, *variable2, .......;
*variable2 = &variable1;
variable2->memberName1;
variable2->memberName2;
variable1.memberName1;
.......;
Initializing members // structure declared beforehand
struct structureName variable1;
variable1.memberName1 = value1;
variable1.memberName2 = value2;
.......;
// structure declared beforehand
struct structureName variable1 = {value1,
value2, .......;
typedef typedef struct structureName {
dataType memberName1;
(defining an alias for
dataType memberName2;
existing structure)
....
}strctNm;
// structure declared beforehand
typedef struct structureName strctNm;
School of CSE, RV University, Bengaluru 74
Programming in C 2024- 2025

 Nested Structures
Nested structures means inserting one structure into another as a member.
Syntax
Declaration struct parentStructure {
dataType member1;
(no memory is allocated)
struct childStructure{
dataType childMember1;
dataType childMember2;
...
} chdStrct;

};
struct childStructure{
dataType childMember1;
dataType childMember2;
...
};
struct parentStructure {
dataType member1;
struct childStructure chdStrct;
...
};
Accessing members // structure declared beforehand
struct parentStructure variable1,
variable2, .......;
variable1.member1;
variable1.chdStrct.childMember1;
variable2.member1;
variable2.chdStrct.childMember2;
.......;

 Self-Referential Structures
Structures containing references to the same type as themselves, i.e. one of the members is a pointer pointing to
the same structure type.
Syntax:
struct structureName {
dataType memberName1;
dataType memberName2;
struct structureName *memberName3;
....
};

School of CSE, RV University, Bengaluru 75


Programming in C 2024- 2025

List of Programs for Lab 10

10a. Write a program using pointer to structures to read, write and compute average-marks of a
student. Take student name, USN, and marks in 5 subjects as input. Use functions.

10b. Write a program using structures to read, write and compute average-marks of n students.
Take student name, USN, and marks in 5 subjects as input. Pass structure by reference to a
function to update marks in one of the five subjects as given by user for a particular student.
Finally display the new average for that student.

School of CSE, RV University, Bengaluru 76


Programming in C 2024- 2025

Stick Data sheets of Program-10 here:

School of CSE, RV University, Bengaluru 77


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 78


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 79


Programming in C 2024- 2025

PROGRAM – 11
 File Handling in C
It helps to create, open, read, write, and close files. A file can be a text file (i.e. '.txt' files that contains data in the
form of ASCII characters) or a binary file (i.e. '.bin' files that contains binary data in the form of 0's and 1's).
 File Operations
- FILE* pointerName;
Declares a file pointer which is a reference to a particular position in the opened file. The FILE macro is
defined inside <stdio.h> header file.

- FILE *fopen( const char *filename, const char *mode );


Opens a file indicated by filename and returns a pointer to the file stream associated with that file. mode
is used to determine the file access mode. If successful, returns a pointer to the new file stream. On error,
returns a null pointer.

File access mode string – Meaning


Action if file already exists Action if file does not exist
(Explanation)
"r" – read
read from start failure to open
(Open a file for reading)
"w" – write
destroy contents create new
(Create a file for writing)
"a" – append
write to end create new
(Append to a file)
"r+" – read extended
read from start error
(Open a file for read/write)
"w+" – write extended
destroy contents create new
(Create a file for read/write)
"a+" – append extended
write to end create new
(Open a file for read/write)
Note:
* File access mode flag "b" can optionally be specified to open a file in binary mode.
On the append file access modes, data is written to the end of the file regardless of
the current position of the file position indicator.
* File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This
flag forces the function to fail if the file exists, instead of overwriting it.
* When using fopen_s or freopen_s, file access permissions for any file created with
"w" or "a" prevents other users from accessing it. File access mode flag "u" can
optionally be prepended to any specifier that begins with "w" or "a", to enable the
default fopen permissions.

- int fclose( FILE *stream );


Closes the given file stream. Returns 0 on success, EOF otherwise.

School of CSE, RV University, Bengaluru 80


Programming in C 2024- 2025

- char* fgets( char* str, int count, FILE* stream );


Reads at most count - 1 characters from the given file stream and stores them in the character array
pointed to by str. Parsing stops if a newline character is found (in which case str will contain that newline
character) or if end-of-file occurs. If bytes are read and no errors occur, writes a null character at the position
immediately after the last character written to str. Returns str on success, null pointer on failure. Other
functions to read from file are fscanf(), fgetc(), fgetw(), and fread().

- int fprintf( FILE* stream, const char* format, ... );


Writes the results to the output stream stream. Other functions to write to a file are fputs(), fputc(),
fputw(), and fwrite().

- size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE


*file_pointer);
Writes data to a binary file. Here, ptr is pointer to the block of memory to be written; size is size of each
element to be written (in bytes); nmemb is number of elements; and file_pointer is FILE pointer to the output
file stream. Returns number of objects written.

- size_t fread(void *ptr, size_t size, size_t nmemb, FILE


*file_pointer);
Reads data from a binary file. Here, ptr is pointer to the block of memory to read; size is size of each element
to read (in bytes); nmemb is number of elements; and file_pointer is FILE pointer to the input file stream.
Returns number of objects read.

- int fseek( FILE* stream, long offset, int origin );


Seeks the cursor to the given record in the file. Here, stream is file stream to modify; offset is number
of characters to shift the position relative to origin; and origin is position to which offset is added.
origin can have one of the following values: SEEK_SET, SEEK_CUR, SEEK_END.

- rewind (file_pointer);
Used to bring the file pointer to the beginning of the file.

List of Programs for Lab 10

11a. Write a program to demonstrate different file operations in C.

School of CSE, RV University, Bengaluru 81


Programming in C 2024- 2025

Stick Data sheets of Program-11 here:

School of CSE, RV University, Bengaluru 82


Programming in C 2024- 2025

OUTPUT:

School of CSE, RV University, Bengaluru 83


Programming in C 2024- 2025

Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)

S. No Criteria Measuring Methods Excellent Good Poor Marks


1 Understanding of the Problem explanation by the Student exhibits thorough Student has sufficient Student does not have a clear
problem statement student. understanding of the problem understanding of the problem understanding of the problem
(1 Mark) statement. statement. statement.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

2 Execution and passing Number of test cases passed Student demonstrates the Student demonstrates the Student implemented but has not
the test cases execution of the program with execution of the program without executed the program. None of
(4 Marks) optimized code. optimized code and passing only the test cases passed. (<= 1.5 M
Appropriate validations passing a few of the test cases. and >= 0 M)
all the test cases. (<= 3.5 M and >= 2 M)
(4 M)

3 Documentation Program write up in the lab Documentation with appropriate Documentation with only few Documentation with no
(1 Mark) record book. comments and output is covered comments and few outputs are comments and no output cases is
in manual. covered in manual. covered in manual.
(1 M) (0.75 M or 0.5 M) (0.25 M or 0 M)

4 Conceptual Viva Voce Explains thoroughly the solution Adequately explains the solution Unable to explain the solution
Understanding and the approach used along with and the approach with related and approach.
(2 Marks) related concepts. concepts (0.5 M or 0 M)
(2 M) (1.5 M or 1 M)

5 Communication of Viva Voce Communicates the concept used Sufficiently communicates the Unable to communicate the
Concepts in problem solving well. concepts used in problem concepts used in problem.
(2 Marks) (2 M) solving. (0.5 M or 0 M)
(1.5 M or 1 M)

Total
Signature with date:
(Faculty In-charge)

School of CSE, RV University, Bengaluru 84


Programming in C 2024- 2025

APPENDIX
 C Operator Precedence

Precedenc
Operator Description Associativity
e
1 ++ -- Suffix/postfix increment and decrement Left-to-right
() Function call
[] Array subscripting
. Structure and union member access
-> Structure and union member access through pointer
(type){list} Compound literal
2 ++ -- Prefix increment and decrement Right-to-left
+- Unary plus and minus
!~ Logical NOT and bitwise NOT
(type) Cast
* Indirection (dereference)
& Address-of
sizeof Size-of
_Alignof Alignment requirement
3 */% Multiplication, division, and remainder Left-to-right
4 +- Addition and subtraction
5 << >> Bitwise left shift and right shift
6 < <= For relational operators < and ≤ respectively
> >= For relational operators > and ≥ respectively
7 == != For relational = and ≠ respectively
8 & Bitwise AND
9 ^ Bitwise XOR (exclusive or)
10 | Bitwise OR (inclusive or)
11 && Logical AND
12 || Logical OR
13 ?: Ternary conditional Right-to-left
14 = Simple assignment
+= -= Assignment by sum and difference
*= /= %= Assignment by product, quotient, and remainder
<<= >>= Assignment by bitwise left shift and right shift
&= ^= |= Assignment by bitwise AND, XOR, and OR
15 , Comma Left-to-right

School of CSE, RV University, Bengaluru 85

You might also like