C Program
C Program
Nobel Academy
A FINAL REPORT
On
Programming in C
Submitted By
Kinjalk Khadka
Registration No.:
Grade: XI-CS
Submitted To
Department of Computer Science
Nobel Academy
A report submitted in partial fulfillment of the requirement for the NEB (10+2)
Submitted By
Kinjalk Khadka
Registration No.:
Grade: XI-CS
Submitted To
Department of Computer Science
Nobel Academy
I hereby recommend that this report proposed under my supervision by Kinjalk Khadka
(2081) entitled "Programming in C" be accepted as fulfilling partial requirements for the NEB
(10+2). To my best knowledge, this is an original work in computer science.
_____________________
Mr. Anjan (Sagar) Sharma
Project Supervisor
Department of Computer Science
Nobel Academy
Date: 2081.11.11
CERTIFICATE OF APPROVAL
The undersigned certify that they have read and recommended to the Department of Computer
Science for acceptance a report entitled "Programming in C" as fulfilling partial requirements
for the NEB (10+2).
_______________________ _______________________
Mr. Anjan (Sagar) Sharma Mr. Subash Kumar Yadav
Project Supervisor HoD of Computer Science
_______________________ _______________________
Mr. Ravi Poudel Sharma Name:
Coordinator External Examiner
ACKNOWLEDGEMENT
The completion of any task would be inadequate, and the satisfaction that accompanies it
would be worthless, unless we mention the people whose ceaseless cooperation made it
possible. It would be truly unjust if these powerful minds were not collectively
acknowledged. The constant guidance we received and the boundless encouragement they
showered upon us have made it possible for us to complete this successful project.
We are heartily grateful to our project guide, Principal Mr. Rabin Dahal, and the
Computer Science Department of Nobel Academy for their guidance and inspiration
throughout our work. His constructive suggestions served as milestones for our project.
We are also highly grateful to project guides Mr. Anjan (Sagar) Sharma and Mr. Subash
Kumar Yadav, as well as the Department of Nobel Academy, for their valuable time,
encouragement, and assistance in the completion of the project report. Their cooperative
behavior is sincerely acknowledged.
Lastly, we sincerely thank the teachers of Nobel Academy, who provided the concept for
this project and guided us from its initial stages to the successful completion of the final
product. We also thank our colleagues for their help in ensuring the successful completion
of the project.
Kinjalk Khadka
Registration No.:
Table of Contents
1.1 Introduction and Features of C language...........................................................................
Introduction................................................................................................................................
Features of C:.............................................................................................................................
1.2 Structure of C program........................................................................................................
Pre-processor and Header files..................................................................................................
Void main function ().................................................................................................................
Comments..................................................................................................................................
1.3 C preprocessor and Header files.........................................................................................
1.4 Character set used in C........................................................................................................
Special Characters......................................................................................................................
1.5 Use of Comments..................................................................................................................
1.6 Identifiers, Keywords, and Tokens.....................................................................................
Keywords...................................................................................................................................
Identifiers...................................................................................................................................
Valid identifiers..........................................................................................................................
Invalid identifiers.......................................................................................................................
1.7 Basic Data Types in C...........................................................................................................
1.8 Constants and Variables......................................................................................................
Variables.....................................................................................................................................
Constants....................................................................................................................................
1.10 Simple and Compound Statements....................................................................................
Simple Statement.......................................................................................................................
Compound Statement.................................................................................................................
1.11 Operators and expressions..................................................................................................
Arithmetic Operators..................................................................................................................
Relation Operators.....................................................................................................................
Logical Operators.......................................................................................................................
Assignment Operator.................................................................................................................
Unary Operator..........................................................................................................................
Ternary Operator (?: operator)...................................................................................................
1.12 Input/ output (I/O) Functions.............................................................................................
Differentiate between printf() and scanf() statements................................................................
Other input/output functions......................................................................................................
1.13 Selection Control statement: Decisions (if, if-else, if-else-if, nested and , switch).........
If statement.................................................................................................................................
If-else statement.........................................................................................................................
If-else-if statement.....................................................................................................................
Nested if else statement..............................................................................................................
Switch case statement................................................................................................................
1.14 Iteration Control Statement: Looping (while, do while, for nested)...............................
Looping......................................................................................................................................
While loop..................................................................................................................................
Do while loop.............................................................................................................................
Difference between while loop and do while loop.....................................................................
For loop......................................................................................................................................
Nested Loop...............................................................................................................................
1.15 Array: definition, types (1D and 2D), matrix addition and subtraction........................
Introduction to Array..................................................................................................................
Characteristics of array..............................................................................................................
Advantages of array...................................................................................................................
Disadvantages of array...............................................................................................................
Types of array.............................................................................................................................
One Dimensional Array.............................................................................................................
Multi Dimensional Array...........................................................................................................
Difference between one dimensional and two dimensional array.............................................
1.16 Strings: Definition and string function:............................................................................
strlen(),strcat(),strcmp(),strrev(),strcpy(),strlwr(),strupr().....................................................
Introduction to string..................................................................................................................
String handling functions...........................................................................................................
strlen() function..........................................................................................................................
strrev() function.........................................................................................................................
strcpy() function.........................................................................................................................
strcat() function..........................................................................................................................
strcmp() function........................................................................................................................
strlwr() function.........................................................................................................................
strupr() function.........................................................................................................................
Programs......................................................................................................................................
Lab Work 1.................................................................................................................................
1.Input three numbers & print their sum & average using C program......................................
2. Find out the square root of a number using C program.........................................................
3. Write a program to calculate and print simple interest (SI) and the net amount (A).............
4. Write a program to calculate distance using s = ut + ½ (at^2)...............................................
5. Write a program to calculate area and circumference of a circle...........................................
6. Write a program to convert temperature in Centigrade into Fahrenheit................................
7. Write a program to calculate to find the sum of two distances & the distance is
measured in feet & inch.........................................................................................................
8. Write a C program to enter number of days & convert it into years, months & days...........
9. Complete the following programs & discuss the outputs......................................................
10. Complete the following 2 examples & discuss the output of the programs........................
Lab Work 2.................................................................................................................................
1. Write a program to calculate area and circumference of a real circle....................................
2. Add a program to calculate whether the given number is odd or even..................................
3. Write a program to read a number and check whether it is positive negative or zero...........
4. Write a program that inputs cost price and selling price and determines whether there is
loss or gain.............................................................................................................................
5. Write a C program that reads three numbers and displays the largest and smallest among
them........................................................................................................................................
6. Write a C program that takes three different numbers and finds out the middle number......
7. Write a program to calculate and display real roots of a quadratic equation.........................
8. Write a program to find the commission amount on the basis of sales amount as per the
following conditions..............................................................................................................
9. Write an interactive program that takes length and breathe and performs the following
tasks on Menu based..............................................................................................................
10. Write a C program that takes a number less than 10 and displays its multiplication
table........................................................................................................................................
Lab Work 3.................................................................................................................................
1. Write a program to calculate and display the following series: 1 3 5…. to 10th term.....
2. Write a program to display square series of first ‘n’ natural numbers...................................
3. Write a program to calculate factorial of any number given by the user...............................
4. Write a program to calculate and display the multiplication table of a number....................
5. Write a program to display Fibonacci series having ‘n’ terms...............................................
6. Write a program to check the given number is Palindrome or not........................................
7. Write a program to calculate some of the following series: sum = 1 + ½ + 1/3 + ¼ …….
+ 1/n.......................................................................................................................................
8. Write a program to display the following output...................................................................
9. Write a program to check whether the given number is prime or not...................................
10. Write a program to display the prime series up to ‘n’.........................................................
Lab Work 4.................................................................................................................................
1. Write a program to input marks of five subjects and display the total and average marks.. .
2. Write a program to input ‘n’ numbers in an array and display the sum of even numbers
from the array.........................................................................................................................
3. Write a program to find the position of key number from given set of numbers which
are stored in an array..............................................................................................................
4. Write a program to read the age of hundred persons and count the number of persons in
the age group between 50 and 60 years.................................................................................
5. Write a program to input ‘n’ numbers and find out the greatest and smallest.......................
6. Write a program that takes salary of 100 employees and print the salary of employees in
ascending order......................................................................................................................
7. Write a program to transpose a matrix with size 3 X 3..........................................................
8. Write a program to calculate the sum of all elements of a matrix with size 3 X 3................
9. Write a program to calculate the sum of diagonal matrix with size 3 X 3.............................
10. Write a program to add two matrices with size 2 X 2 supplying by elements by the
user.........................................................................................................................................
Lab Work 5.................................................................................................................................
1. Write a program to find the length of a string without using built-in function......................
2. Write a program to reverse the given string without using built-in function.........................
3. Write a program to concatenate two given string without using built-in function................
4. Write a program to input line of text & count the number of digit, vowels, consonants,
white spaces & other characters.............................................................................................
5. Write a program to check whether the given string is palindrome or not..............................
6. Write a program to input the names of 10 students & sort them in alphabetical order..........
7. Write a program to search a string from the given set of strings...........................................
Reflection......................................................................................................................................
Conclusion....................................................................................................................................
References.....................................................................................................................................
1. C programming Language
Features of C:
• Simple & Efficient – Easy to learn and executes efficiently.
• Fast Execution – Programs written in C run faster than most other
languages.
• Structured Language – Code is divided into functions for better
readability.
• Portable – Code can be compiled and run on different platforms.
• Rich Library Functions – Many built-in functions are available.
11
1.2 Structure of C program
Every C program contains several building blocks know as functions. Each
function performs task independently. The basic structure of C program is
given below.
Comments
The comments are not the internal part of program codes. It is optional
but writing comments helps to understand the flow of programs and god
practice for internal documentation of programmer. It is also useful for
further modification and program testing.
Example: Program to print Hello World on Screen.
// program to print hello world <- Comments
#include <stdio.h> <- Preprocessor and Header File
void main() <- Main Function
{ <- Scope Start printf("Hello World"); <- Output Function to print
} <- Scope End
12
1.3 C preprocessor and Header files
Header files are standard library files of C-programming language which
contents the detail information about variables, constant, operators,
expressions, library function, etc. These necessary header files must be
included in our program codes before program compilation otherwise the
compiler does not executer our program codes. The pre-processor
directives help to include or link these header files to our program codes.
Example of pre-processor directives are:- #include #define, etc. Some of
the header files are listed below:
13
Special Characters
, Co
m
m
a
. Pe
rio
d
; Se
mi
co
lo
n
: Co
lo
n
?Q
ue
sti
on
m
ar
k
‘ Ap
os
tr
op
he
“Q
uo
ta
tio
n
m
ar
k
! Ex
cl
a
m
ati
on
m
ar
k
14
| Ve
rti
ca
l
ba
r
/ Sl
as
h
\ Ba
ck
sl
as
h
~ Til
de
_ & Ampersand
$ ^ Caret
% * Asterisk
- Minus Sign
+ Plus Sign
< Opening Angle (Less than
sign)
> Closing Angle (Greater
than sign)
( Left parenthesis
) Right parenthesis
[ Left bracket
] Right bracket
{ Left brace
} Right brace
# Hash
White space
15
1.5 Use of Comments
The comments have no effects on program codes but they are useful
components of program for program documentation. They help
programmers for the description of program for program codes. They also
make programmer to modify and testing of program. Comments can be
written in two forms:
Keywords
There are certain words which are reserved by the C compiler. These
words are known as keywords. They cannot be used as identifiers in the
program. Mainly there are 32 keywords use in standard C language.
auto double int
struct break else
long switch case
enum register typedef
char extern return
union const float
short unsigned continue
for signed void
default goto sizeof
volatile do if
16
static while
Identifiers
Identifiers are the names given to program unit such as variables,
structure, function, etc. They are not defined in programming language
but are used to define by the programmer. Some basic rules to define
identifiers are given below:
Valid identifiers
A1 B34 FIRST_NAME x_1
Invalid identifiers
1A 34AB int void FIRST-NAME
X.1
17
C data
type
s
Primary Secondar
data ydata
types types
Characte Array
r
Intege Pointer
r
Float Structur
e
Double Union
Constants
A constant value is the one which doesn‘t change during the execution of
a program.
C supports several types of constants.
1.9 Type of Specifier
18
It is also known as format specifier. Type of specifier controls the type and
format of the value to be printed or entered. Each conversion specification
begins with % sign and ends with a conversion character. The conversion
character defines data type of the corresponding argument.
Specifier Character Meaning
c Single Character
d Decimal integer
f Floating point value without
exponent form
Id Long integer
Simple Statement
A simple statement consists of an expression followed by a semicolon.
evaluated. Examples
b=5;
c=d+e;
printf(―Enter a number‖);
19
Compound Statement
A compound statement consists of several individual statements enclosed
in a pair of braces {}. It provides capability for embedding statements
within other statements.
Example
{
R=5;
Area=3.14*R*R;
}
Arithmetic Operators
All the basic arithmetic operations can be carried out in C. It can perform
arithmetic calculations such as addition, subtraction, multiplication, etc. It
uses two operands so that it is called binary operator. The types of
arithmetic operators are given below:
Operator Meaning Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus a%b
Operator(Remainder)
Relation Operators
It is required to compare the relationship between operands and bring out
a decision accordingly. It is also called comparison operator because it is
20
used to compare any two expressions. C supports the following relational
operators.
Logical Operators
Logical operators are used to give logical value either true or false. C has
the following logical operators; they compare or evaluate logical and
relational expressions.
Operator Meaning Example
&& Logical AND (a>b)&&(a>c)
|| Logical OR (a>b)||(a>c)
! Logical NOT !(a==b)
Assignment Operator
The assignment operator is used to assign the value of expression into
variable. It is written in the form:
Variable = expression
Example: x = a+b, x+=1, a-=1, a*=1, a/=2, a%=2
Unary Operator
The increment and decrement operators are useful operators in C
language. They are extensively used in loops. The syntax of the operators
is given below:
21
• Variable name—(decrement prefix)
Syntax:
A =10;
B=15;
X=(A>B) ? A : B;
22
It contains any simple It does not contain simple
characters, format characters, it contains
conversion specifiers or format conversion specifier
escape sequence and arg1, and arg1, arg2, arg3,…
arg2, … arguments(variables).
arguments(variables).
Syntax: Syntax:
printf(―control scanf(―control
string‖, arg1,arg2, string‖, arg1, arg2,
…); …);
Here control string may Here control string may
consist simple string or consist format conversion
format conversion specifier specifiers and arg1
and arg1, arg2, … are
arguments.
Example: Example:
void main() void main()
{ float a = {
987.55897; int a;
printf(―\n printf(―Enter a
%.3f‖,a); number‖); scanf(―
} %d‖,&a);
}
Synatx:
variable_name=getchar();
putchar(variable_name);
23
gets() and puts(): The gets() function is used for a completely different
purpose. It read a string (group of characters) from the standard input and
store in the given variable. It reads a whole line of input until a newline.
Syntax:
gets(variable);
puts(variable);
If statement
It is the simplest form of conditional statement in which statements are
executed if the test expression (condition) is true. When condition is false
there is no option to go within this structure; in such situation control
must out from the structure and statements outside the structure be
executed.
Syntax:
if(condition)
{
Statements;
24
}
If-else statement
The if-else statement is an extended form of the if statement that
provides an alternative path when the test expression (condition) is false.
If the condition is true, the statements inside the if block are executed;
however, if the condition is false, the statements inside the else block are
executed instead. This structure ensures that one of the two possible
blocks is always executed, allowing the program to handle both outcomes
of the condition. It makes decision-making more flexible by offering a
clear choice between two actions based on the evaluation of a condition.
Syntax:
if(condition){
statement1;
}else{
statement2;
If-else-if statement
The if-else-if statement is used when there are multiple conditions to
evaluate, and different actions need to be taken based on which condition
is true. It allows the program to check several test expressions in
sequence. When the first condition is true, its corresponding block is
executed, and the rest are skipped. If the first condition is false, the
program checks the next condition, and so on. If none of the if or else-if
conditions are true, the else block (if present) is executed as a default
case. This structure provides a way to handle complex decision-making
scenarios where multiple outcomes are possible.
Syntax:
25
if(condition1){
statement1;
}else if(condition2){
statement2;
}else if(condition n-1){
statement n-1;
}else{
statement n;
}
Syntax:
if(condition1){
if(condition2)
statement1;
else
statement2;
}else
statement3;
26
Switch case statement
The switch-case statement is a multi-way branch statement used to
simplify complex conditional logic where a single variable or expression is
compared against multiple constant values. Instead of writing many if-
else-if statements, the switch statement allows cleaner and more
readable code by matching the value of the expression with one of the
defined case labels. When a match is found, the corresponding block of
statements is executed. If no match is found, the optional default case is
executed. Each case usually ends with a break statement to prevent fall-
through to the next case. The switch-case structure is commonly used for
menu selections, command options, and other scenarios involving
multiple fixed choices.
Syntax:
switch(expression)
{
case constant1:
statement1;
break;
case constant2:
statement2;
break;
case constant n:
statement n;
break;
default:
statement;
}
27
1.14 Iteration Control Statement: Looping
(while, do while, for nested)
Looping
Looping is a programming technique used to execute a block of code
repeatedly as long as a specified condition remains true. It helps in
performing repetitive tasks efficiently without writing the same code
multiple times. There are different types of loops, such as for, while, and
do-while, each suited for specific situations depending on when the
condition is checked and how many times the loop is expected to run.
Loops are widely used in scenarios like iterating over arrays, processing
user input, generating patterns, and performing calculations. By using
loops, programs become more compact, manageable, and powerful in
handling repetitive logic.
Mainly there are three types of loop: for, while, and do while loop
While loop
The while loop is a control statement that allows code to be executed
repeatedly based on a given condition. It is one of the simplest types of
loops where the condition is checked before the execution of the loop
body. If the condition is true, the statements inside the loop are executed;
once the condition becomes false, the loop terminates, and control moves
to the next statement after the loop. This type of loop is best used when
the number of iterations is not known in advance and depends on
dynamic conditions during runtime. Care must be taken to update the
condition inside the loop to avoid infinite execution.
Syntax:
while (condition) {
statements;
increment/decrement;
}
28
Do while loop
The do-while loop is a variation of the while loop, where the loop body is
executed at least once before the condition is tested. In this structure, the
statements inside the loop are run first, and then the condition is checked.
If the condition is true, the loop continues to execute; if it is false, the loop
terminates. This makes the do-while loop useful in situations where the
code block needs to run at least once regardless of the condition, such as
taking user input before checking its validity. It ensures a minimum one-
time execution of the loop body, making it different from other loop types.
Syntax:
do {
statements;
increment/decrement;
}while(condition);
Example: Example:
void main(){ void main(){
int i=1; int i=1;
while(i>=10){ do{
printf(―Hello‖);
i++;
29
printf(―Hello‖) }while(i>=10);
i++; }
}
}
For loop
The for loop is a control statement used to repeat a block of code a
specific number of times, making it ideal for situations where the number
of iterations is known in advance. It consists of three parts: initialization
(where the loop counter is set), condition (which is evaluated before each
iteration to determine if the loop should continue), and update (where the
loop counter is modified after each iteration). Once the condition becomes
false, the loop exits. The for loop is commonly used for tasks like iterating
over arrays, counting, or generating sequences, as it provides a concise
and structured way to handle repetitive tasks with a predetermined
number of iterations.
Syntax:
for(initialization; condition; increment/decrement)
{
statements;
}
Nested Loop
A nested loop is a loop inside another loop, where the inner loop is
executed completely every time the outer loop executes one iteration.
This structure allows you to perform more complex repetitive tasks, such
as working with multi-dimensional data structures like matrices or grids.
The outer loop controls the number of times the inner loop will be
executed, and for each iteration of the outer loop, the inner loop runs
from start to finish. Nested loops are commonly used for tasks like
30
iterating over rows and columns of a matrix, generating patterns, or
processing combinations. However, care must be taken when using
nested loops, as they can increase the time complexity of the program
significantly if not managed efficiently.
Syntax:
for(initialization; condition; increment/decrement){
for (initialization; condition;
increment/decrement) {
statements;
}
}
Characteristics of array
Here are the key characteristics of an array:
31
• Fixed Size: The size of an array is defined at the time of its
creation and cannot be changed during runtime.
• Homogeneous Elements: All elements in an array are of the
same data type, such as all integers, all floats, or all characters.
• Contiguous Memory Allocation: Array elements are stored in
consecutive memory locations, which allows fast access using
indexing.
• Index-Based Access: Each element in the array can be accessed
directly using its index, making retrieval fast and efficient.
• Efficient Traversal: Arrays allow easy and efficient traversal using
loops due to their index-based structure.
• Static Structure: Arrays are static in nature, meaning memory is
allocated once and cannot be resized, which may lead to wastage
or shortage of memory.
• Ease of Use: Arrays simplify the code when dealing with multiple
values of the same type, reducing the need for multiple variables.
Advantages of array
Here are some advantages of using arrays in programming:
32
• Memory Efficiency: Since elements are stored in contiguous
memory locations, arrays help in better memory management and
access speed.
• Support for Multiple Dimensions: Arrays can be one-
dimensional, two-dimensional (like matrices), or even multi-
dimensional, allowing representation of complex data structures.
• Useful for Algorithms: Arrays are fundamental to many
algorithms such as searching, sorting, and dynamic programming
due to their simple structure and fast access time.
Disadvantages of array
Here are some common disadvantages of arrays:
• Fixed Size: The size of an array must be defined at the time of its
declaration and cannot be changed later, which may lead to
memory wastage or shortage.
• Homogeneous Data: Arrays can store only elements of the same
data type, limiting flexibility when handling mixed types of data.
• Insertion and Deletion Issues: Inserting or deleting elements in
an array can be inefficient, as it may require shifting elements to
maintain order.
• Wasted Memory: If the allocated array size is larger than needed,
the unused memory space is wasted.
• Lack of Built-in Functions: Compared to other data structures
like lists (in Python) or vectors (in C++), arrays have limited built-in
functionality for dynamic operations.
• No Bound Checking: In many programming languages, arrays do
not perform automatic bound checking, which can lead to
accessing invalid memory locations and cause runtime errors.
• Static Nature: Since arrays are static structures, they are not
suitable for situations where the amount of data is constantly
changing during program execution.
33
Types of array
One Dimensional Array
Like any other variable, we have to declare array before they are used.
float weight[100];
arrays, except that it consists more than one pair of square brackets that
brackets, one for row size and other for column size. The maximum
capacity of elements of array is the product of row size and column size.
= {100,200,300,200,150,50,350,500,600};
34
Row 0 100 200 300
[1][0] [1][1] [1][2]
Row 1 200 150 50
[2][0] [2][1] [2][2]
Row 2 350 500 600
It stores data either row wise or It sotres data in matrix form that is
column wise. row wise and column wise.
Syntax: Syntax:
data_type array_name[array_size]; data_type array_name[row_size]
Example: [column size]; Example:
int num[5]; int matrix[2][2];
strlen(),strcat(),strcmp(),strrev(),strcpy(),strl
wr(),strupr()
Introduction to string
A string is a data type used in programming to represent a sequence of
characters, such as letters, numbers, and symbols. Strings are commonly
used to store and manipulate text-based data like names, messages, or
35
paragraphs. They are usually enclosed in quotation marks (single or
double, depending on the language) and can be treated like arrays of
characters in many programming languages. Strings support various
operations such as concatenation, comparison, slicing, and searching,
making them highly useful in text processing tasks. Due to their flexibility
and importance in input/output handling, strings are one of the most
widely used data types in programming.
Syntax char
string_name[string_size]; Example
or,
String handling
functions
strlen() function
This functions returns the length of the string.
Syntax
36
I=strlen(str);
strrev() function
It is used to reverse a string. It accepts a string and reverses it and stores in the
same string.
Syntax
strrev(str);
strcpy() function
The strcpy() function is used to copy one string into another string.
Syntax:
strcpy(str1,str2);
strcat() function
The strcat() function is used to join or concatenate one string into
strcat(str1,str2);
strcmp() function
The strcmp() function is used to compare two strings, character by
character and stops the comparison when there is a difference in the SCII
value or the end of any one string and returns ASCII difference of the
characters that is integer which is either zero, position, or negative. If the
value is zero both strings are same, if the value is positive first string is
larger than second one otherwise first string is smaller than second one.
Syntax
v = strcmp(str1,str2);
strlwr() function
This function is used to convert uppercase characters of string into
lowercase characters.
Syntax
37
strlwr(str);
strupr() function
This function is used to convert lowercase characters of string into
Programs
Lab Work 1
1.Input three numbers & print their sum & average using C
program.
#include <stdio.h>
int main(){
int num1, num2, num3, sum, avg;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
sum = num1 + num2 + num3;
avg = sum / 3;
printf("Their sum is: %d & average: %d", sum, avg);
return 0 ;
38
scanf("%f", &num);
printf("Its square root is: %.2f", sqrt(num));
return 0;
}
39
int main() {
float u, t, a, s;
printf("Enter initial velocity (u) in m/s: \n");
scanf("%f", &u);
printf("Enter time (t) in seconds: ");
scanf("%f", &t);
printf("Enter acceleration (a) in m/s^2: ");
scanf("%f", &a);
s = (u * t) + (0.5 * a * t * t);
printf("The distance covered is: %.2f meters\n", s);
return 0; }
40
6. Write a program to convert temperature in Centigrade into
Fahrenheit.
#include <stdio.h>
int main() {
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = (celsius * 9 / 5) + 32;
printf("Temperature in Fahrenheit: %.2f\n", fahrenheit);
return 0;
}
41
totalInch = inch1 + inch2;
totalFeet = feet1 + feet2 + (totalInch / 12);
totalInch = totalInch % 12;
printf("The total distance is: %d feet %d inches\n", totalFeet, totalInch);
return 0;
}
42
float x;
int x1 = 5;
int x2 = 2;
x = x1 / x2;
printf(“%f”, x);
ANS:-
#include <stdio.h>
int main() {
float x;
int x1 = 5;
int x2 = 2;
x = x1 / x2;
printf("%f", x);
return 0;
}
Program 2
float x;
int x1 = 5;
int x2 = 2;
x =(float) x1 / x2;
printf(“%f”, x);
ANS:-
#include <stdio.h>
int main() {
float x;
int x1 = 5;
43
int x2 = 2;
x = (float)x1 / x2;
printf("%f", x);
return 0;
}
Program 2
int j;
int i = 5;
j = i++;
44
printf(“i = %d\nj = %d”, i, j);
ANS:-
#include <stdio.h>
int main() {
int i, j;
i = 5;
j = i++;
printf("i = %d\nj = %d", i, j);
return 0;
}
Lab Work 2
1. Write a program to calculate area and circumference of a real
circle.
#include <stdio.h>
int main() {
double radius, area, circumference;
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
area = (22 / 7) * radius * radius;
circumference = 2 * (22 / 7) * radius;
printf("Area of the circle: %.2lf\n", area);
printf("Circumference of the circle: %.2lf\n", circumference);
return 0;
}
45
2. Add a program to calculate whether the given number is odd or
even.
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number % 2 == 0) {
printf("%d is even.\n", number);
} else {
printf("%d is odd.\n", number);
}
return 0;
}
46
printf("The number is zero.\n");
}
return 0;
}
4. Write a program that inputs cost price and selling price and
determines whether there is loss or gain.
#include <stdio.h>
int main() {
float costPrice, sellingPrice;
printf("Enter the cost price: ");
scanf("%f", &costPrice);
printf("Enter the selling price: ");
scanf("%f", &sellingPrice);
if (sellingPrice > costPrice) {
printf("You made a gain of %.2f\n", sellingPrice - costPrice);
} else if (sellingPrice < costPrice) {
printf("You incurred a loss of %.2f\n", costPrice - sellingPrice);
} else {
printf("No gain, no loss.\n");
}
return 0;
}
47
int num1, num2, num3;
int largest, smallest;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
if(num1 > num2 && num1 > num3){
largest = num1;
}
else if(num2 > num3 && num2 > num1){
largest = num2;
}
else{
largest = num3;
}
if(num1 < num2 && num1 < num3){
smallest = num1;
}
else if(num2 < num1 && num2 < num3){
smallest = num2;
}
else{
smallest = num3;
}
printf("Largest number: %d\n", largest);
printf("Smallest number: %d\n", smallest);
return 0;}
48
6. Write a C program that takes three different numbers and finds
out the middle number.
#include <stdio.h>
int main() {
int num1, num2, num3, middle;
printf("Enter the three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
if ((num1 > num2 && num1 < num3) || (num1 < num2 && num1 > num3)) {
middle = num1;
} else if ((num2 > num1 && num2 < num3) || (num2 < num1 && num2 > num3))
{
middle = num2;
} else {
middle = num3;
}
printf("The middle number is: %d\n", middle);
return 0;}
49
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct: %.2f and %.2f\n", root1, root2);
} else if (discriminant == 0) {
root1 = -b / (2 * a);
printf("Roots are real and equal: %.2f and %.2f\n", root1, root1);
} else {
printf("No real roots exist\n");
}
return 0;
}
50
commission = salesAmount * 0.12;
} else {
printf("Invalid sales amount.\n");
return 1;
}
printf("The commission amount is: %.2f\n", commission);
return 0;
}
51
printf("Enter length: ");
scanf("%f", &length);
printf("Enter breadth: ");
scanf("%f", &breadth);
printf("Perimeter of Rectangle: %.2f\n", 2 * (length + breadth));
break;
case 3:
printf("Exiting program.\n");
default:
printf("Invalid choice. Please try again.\n");
}
return 0;
}
52
printf("%d x %d = %d\n", number, i, number * i);
}
}
return 0;
}
Lab Work 3
1. Write a program to calculate and display the following series: 1
3 5…. to 10th term.
#include <stdio.h>
int main() {
int i, term = 1;
printf("The series is: \n");
for(i = 0; i < 10; i++){
printf("%d\t", term);
term += 2;
}
return 0;
}
53
int main() {
int n, i;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Square series of first %d natural numbers:\n", n);
for (i = 1; i <= n; i++) {
printf("%d\t", i * i);
}
return 0;
}
54
4. Write a program to calculate and display the multiplication
table of a number.
#include <stdio.h>
int main() {
int num, i;
printf("Enter a number: ");
scanf("%d", &num);
printf("Multiplication Table of %d:\n", num);
for (i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
}
return 0; }
55
} else {
printf("Fibonacci Series: ");
for (int i = 1; i <= n; ++i) {
printf("%d\t", term1);
nextTerm = term1 + term2;
term1 = term2;
term2 = nextTerm;
}
}
return 0;
}
56
}
return 0;
}
57
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 5; j++) {
printf("%d\t", i * j); }
printf("\n"); }
return 0;
}
58
printf("%d is not a prime number.\n", num);
}
return 0;
}
59
return 0;
}
Lab Work 4
1. Write a program to input marks of five subjects and display the
total and average marks.
#include <stdio.h>
int main() {
float marks[5], total = 0, average;
int i;
printf("Enter marks of five subjects:\n");
for (i = 0; i < 5; i++){
printf("Subject %d: ", i + 1);
scanf("%f", &marks[i]);
total += marks[i];
}
average = total / 5;
printf("\nTotal Marks: %.2f\n", total);
printf("Average Marks: %.2f\n", average);
return 0;
}
60
2. Write a program to input ‘n’ numbers in an array and display
the sum of even numbers from the array.
#include <stdio.h>
int main() {
int size, i, sum = 0;
printf("Enter the array size: ");
scanf("%d", &size);
int arr[size];
printf("Enter the elements:\n");
for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
if (arr[i] % 2 == 0) {
sum += arr[i];
}
}
printf("Sum of even numbers: %d\n", sum);
return 0;
}
61
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the key to find: ");
scanf("%d", &key);
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
pos = i;
break;
}
}
if (pos != -1) {
printf("Key found at position: %d\n", pos + 1);
} else {
printf("Key not found\n");
}
return 0;
}
62
scanf("%d", &ages[i]);
if (ages[i] >= 50 && ages[i] <= 60) {
count++;
}
}
printf("Number of persons aged between 50 and 60: %d\n", count);
return 0;
}
63
64
5. Write a program to input ‘n’ numbers and find out the greatest
and smallest.
#include <stdio.h>
int main() {
int n, i, num, greatest, smallest;
printf("Enter the number of elements: ");
scanf("%d", &n);
if (n <= 0) {
printf("Invalid input.\n");
}
else
65
{
printf("Enter number 1: ");
scanf("%d", &num);
greatest = smallest = num;
for (i = 2; i <= n; i++) {
printf("Enter number %d: ", i);
scanf("%d", &num);
if (num > greatest) {
greatest = num;
}
if (num < smallest) {
smallest = num;
}
}
printf("Greatest: %d\n", greatest);
printf("Smallest: %d\n", smallest);
}
return 0;
}
66
int salaries[100], i, j, temp;
printf("Enter the salaries of 100 employees:\n");
for (i = 0; i < 100; i++) {
scanf("%d", &salaries[i]);
}
for (i = 0; i < 100 - 1; i++) {
for (j = 0; j < 100 - i - 1; j++) {
if (salaries[j] > salaries[j + 1]) {
temp = salaries[j];
salaries[j] = salaries[j + 1];
salaries[j + 1] = temp;
}
}
}
printf("Salaries in ascending order:\n");
for (i = 0; i < 100; i++) {
printf("%d\n", salaries[i]);
}
return 0;
}
67
7. Write a program to transpose a matrix with size 3 X 3.
#include <stdio.h>
int main() {
int matrix[3][3], transpose[3][3];
int i, j;
printf("Enter elements of the 3x3 matrix:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
}
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
transpose[j][i] = matrix[i][j];
}
}
printf("Transpose of the matrix:\n");
68
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}
69
9. Write a program to calculate the sum of diagonal matrix with
size 3 X 3.
#include <stdio.h>
int main() {
int matrix[3][3], i, sum = 0;
printf("Enter elements of the 3x3 matrix:\n");
for (i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
if (i == j) {
sum += matrix[i][j];
}
}
}
printf("Sum of diagonal elements: %d\n", sum);
return 0;
}
70
int main() {
int a[2][2], b[2][2], sum[2][2];
printf("Enter elements of first 2x2 matrix:\n");
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
scanf("%d", &a[i][j]);
}
}
printf("Enter elements of second 2x2 matrix:\n");
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
scanf("%d", &b[i][j]);
}
}
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
sum[i][j] = a[i][j] + b[i][j];
}
}
printf("Sum of the matrices:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++){
printf("%d\t", sum[i][j]);
}
printf("\n");
}
return 0;
}
71
Lab Work 5
1. Write a program to find the length of a string without using
built-in function.
#include <stdio.h>
int main() {
char str[100];
int length = 0;
printf("Enter a string: ");
scanf("%s", str);
while (str[length] != '\0') {
length++;
}
printf("Length of the string: %d\n", length);
return 0;
}
72
printf("Enter a string: ");
scanf("%s", str);
while (str[length] != '\0') {
length++;
}
for (i = 0; i < length; i++) {
reversed[i] = str[length - i - 1];
}
reversed[length] = '\0';
printf("Reversed string: %s\n", reversed);
return 0;
}
73
i++;
j++;
}
result[i] = '\0';
printf("Concatenated string: %s\n", result);
return 0;
}
74
} else {
others++;
}
}
printf("Digits: %d\n", digits);
printf("Vowels: %d\n", vowels);
printf("Consonants: %d\n", consonants);
printf("White spaces: %d\n", spaces);
printf("Other characters: %d\n", others);
return 0;
}
75
if (str[i] != rev[i]) {
flag = 0;
break;
}
}
if (flag) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
76
strcpy(names[j], temp);
}
}
}
printf("\nSorted names:\n");
for (i = 0; i < 10; i++) {
printf("%s\n", names[i]);
}
return 0;
}
77
"banana",
"cherry",
"date",
"mango"
};
char search[50];
int found = 0;
printf("Enter a string to search: ");
scanf("%s", search);
for (int i = 0; i < 5; i++) {
if (strcmp(strings[i], search) == 0) {
found = 1;
break;
}
if (found) {
printf("String found.\n");
} else {
printf("String not found.\n");
}
return 0;
}
78
Reflection
During my computer practical session, I worked on writing and executing C
programs. The objective was to apply theoretical concepts in a hands-on
environment and enhance my programming skills. I practiced writing programs
that involved basic input/output operations, loops, conditional statements, arrays,
and functions.
One of the tasks I completed was writing a program to [– e.g., find the factorial
of a number]. Initially, I faced some challenges with syntax errors and logical
mistakes, but through debugging and testing, I was able to correct them and
achieve the desired output. This process helped me understand how important it is
to carefully analyze code and test it thoroughly.
The practical also taught me how to structure a program properly and write clean,
readable code. I gained more confidence in using various C constructs and
improved my problem-solving skills. I realized that consistent practice is key to
mastering programming.
Overall, the practical session was productive and insightful. It reinforced the
concepts learned in class and gave me a clearer understanding of how C
programming works in real-world scenarios. I look forward to continuing to
improve my coding abilities through more practice and experimentation.
79
Conclusion
The C programming practical provided a strong foundation in understanding the
core concepts of programming such as loops, conditionals, functions, and arrays. It
offered me the chance to apply classroom knowledge to real-world coding
problems, allowing me to understand how syntax and logic come together to create
functional programs. Debugging and correcting errors gave me insight into how
important attention to detail is in programming. Each task helped build my
confidence, and with every successfully executed program, I became more
comfortable with the C language.
This practical experience also made me realize that programming is not just about
writing code, but about thinking logically and solving problems efficiently. I now
feel more prepared to take on more complex topics such as data structures and file
handling. Moving forward, I aim to continue practicing and possibly create small
projects to enhance my skills. Overall, this practical was a valuable step in my
learning journey, and it has motivated me to keep exploring and improving in the
field of computer
80
References
Books:
The C Programming Language by Brian W. Kernighan and Dennis
M. Ritchie
(Often referred to as “K&R”, this is the classic book written by the
creators of C.)
Let Us C by Yashavant Kanetkar
(A beginner-friendly book widely used in India and other countries
for learning C.)
C Programming: A Modern Approach by K. N. King
(Covers C in depth, suitable for both beginners and intermediate
learners.)
Online Platforms:
GeeksforGeeks – Comprehensive tutorials, code examples, and
problem-solving.
TutorialsPoint – Easy-to-follow C tutorials.
w3schools – C Tutorial – Great for beginners.
YouTube Channels:
CodeWithHarry – Beginner-friendly C programming series in
Hindi and English.
Jenny’s Lectures CS/IT NET&JRF – Detailed C tutorials
explained clearly.
freeCodeCamp.org – Offers a full 4+ hour C programming course
for beginners.
Neso Academy – Great for both concepts and practical coding in
C.
81
82