Programming in C Lab Manual
Programming in C Lab Manual
PROGRAMMING IN C
COURSE CODE: CS1003
I SEMESTER B.Tech (Hons.)
LABORATORY CERTIFICATE
USN: Semester:
Marks
Maximum Obtained
25
Date:
CS1003 : Programming in C (2024–2025)
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
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.
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)
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.
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.
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.
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.
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.
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
Record + Viva-voce
Total = Attendance +=
(7 Marks) (2 Marks) (5 Marks)
PART – B
Write-up, execution, and viva-voce rubrics for Mid-term evaluation (Max: 8 marks)
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)
Write-up, execution, and viva-voce rubrics for Semester-end evaluation (Max: 10 marks)
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)
*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)
PART – A
PROGRAM – 1
Pre-requisites:
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
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,
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 " ∑ ¿.
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 .
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
PROGRAM – 2
Pre-requisites:
Arithmetic Operators.
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.
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
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);
}
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
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
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
PROGRAM – 3
Pre-requisites:
Media Source:
https://media.geeksforgeeks.org/wp-content/uploads/20230424101456
/Conditional-Statements-in-c.webp
−b ± √ b2−4 ac
The roots of a quadratic equation, a x 2 +bx +c are given by the quadratic formula: x= .
2a
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
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.
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 .
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.
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
PROGRAM – 4
Pre-requisites:
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
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 ' ∑ ¿.
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.
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
PROGRAM – 5
Pre-requisites:
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.
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.
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.
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 .
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
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));
}
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)
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
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.
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.
- 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
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
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 ]
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
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
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
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.
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
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
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;
....
};
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.
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
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.
- rewind (file_pointer);
Used to bring the file pointer to the beginning of the file.
OUTPUT:
Write-up, execution, and viva-voce rubrics for labs being evaluated (Max: 10 marks)
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)
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