0% found this document useful (0 votes)
3 views82 pages

C Program

This document is a final report on 'Programming in C' submitted by Kinjalk Khadka for the National Examination Board (NEB) under the supervision of Mr. Anjan (Sagar) Sharma at Nobel Academy. It includes sections on the introduction and features of the C programming language, its structure, data types, operators, control statements, arrays, strings, and various programming exercises. The report aims to fulfill the partial requirements for the NEB (10+2) curriculum in computer science.

Uploaded by

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

C Program

This document is a final report on 'Programming in C' submitted by Kinjalk Khadka for the National Examination Board (NEB) under the supervision of Mr. Anjan (Sagar) Sharma at Nobel Academy. It includes sections on the introduction and features of the C programming language, its structure, data types, operators, control statements, arrays, strings, and various programming exercises. The report aims to fulfill the partial requirements for the NEB (10+2) curriculum in computer science.

Uploaded by

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

National Examination Board

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

Under the supervision of


Mr. Anjan (Sagar) Sharma
Computer Science Lecturer
2081.11.11
PROJECT REPORT
On
Programming in C

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

Under the supervision of


Mr. Anjan (Sagar) Sharma
Computer Science Lecturer
2081.11.11
Date: 2081.11.11

RECOMMENDATION LETTER OF SUPERVISOR

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

1.1 Introduction and Features of C


language
Introduction
C is a powerful, general-purpose programming language developed by
Dennis Ritchie in 1972 at Bell Labs. It is widely used in system
programming, operating systems, embedded systems, and
application development. C is known for its simplicity, efficiency,
portability, and flexibility, making it one of the most popular
programming languages. It follows a structured programming
approach, which helps in writing clear and organized code.
One of the key features of C is its ability to provide low-level memory
access while maintaining high-level functionalities. It includes a rich set
of built-in functions and operators, making it suitable for developing
complex applications. Many modern programming languages like C++,
Java, and Python are influenced by C. C is highly portable, meaning
programs written in C can run on different platforms with minimal
changes. Due to its speed and efficiency, it is widely used in game
development, networking, and operating system development.

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.

Pre-processor and Header files


Pre-processor directive is special type of program that processes the code
before it passes through the compiler. The common preprocessor directive
is #include which helps to include the necessary header files for further
execution. The header file is the main file of c compiler that contains
inbuilt library functions. For example: #inlcude <stdio.h>

Void main function ()


Every C program must contain main () function. The instructions are
written inside the scope {} i.e. area of the main function. Mainly it has
two part: declaration part and executable part. The declaration part
declares the variables or constant, etc. The actual program codes are
written in the executable part.

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:

• #include <stdio.h>: It is the main standard input output header


file. It contains the function definition of input output functions such
as scanf(), printf().etc.
• #include <conio.h>: It is header file which is included in the
program this is used to use clrscr(), getch(), etc. We do not need to
include this file in C program. It is necessary C programs. conio
stands for console input output header file. The clrscr() helps to
clear the screen.
• #include<math.h>: This header file is used for mathematical
functions such as pow(), sqrt(), sin(), tan(), cos(), etc.
• #include <string.h>: It is string header file. It contains the
function definition of string processing functions such as
strlen(),strcat(), strcpy(),etc.

1.4 Character set used in C


The character set defines a group of letters, words, numbers, symbols,
and expressions which is used in C language. The character set in C
language can be grouped into the following three categories.

• Letters: uppercase A to Z and lowercase a to z.


• Digits: 0 to 9.
• Special Characters: Listed in the table.

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:

• // Single line comments


• /* multi line ……………………. Comments */

1.6 Identifiers, Keywords, and Tokens


The smallest part of C programming language is called C tokens. C
programs are written using these tokens. There are six types of C tokens
that are given below.
Keywords Operators Identifiers
Constants Strings Special Symbols

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:

• First Character must be an alphabet or underscore than digits  It


must consist of only letters, digits, and underscore.
• Any standard C language keyword cannot be used as identifier
name.
• It should not contain a space.
• It allows both uppercase and lowercase characters.

Valid identifiers
A1 B34 FIRST_NAME x_1

Invalid identifiers
1A 34AB int void FIRST-NAME
X.1

1.7 Basic Data Types in C


A data might be in the form of number, character, string or record and
they are called data types. Mainly C language provides two types of data:
primary data types and secondary data types. The secondary data types
will be discussed later.

17
C data
type
s
Primary Secondar
data ydata
types types
Characte Array
r
Intege Pointer
r
Float Structur
e
Double Union

1.8 Constants and Variables


Variables
A variable is a value that can change any time. It is a memory location
used to store a data value. A variable name should be carefully chosen by
the programmer so that its use is reflected in a useful way in the entire
program. Any variable declared in a program should confirm to the
following:

• They must always begin with a letter, although some systems


permit underscore as the first character.
• White space is not allowed.
• A variable should not be a keyword
• It should not contain any special character
• It does not allow keyword

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

i Signed decimal integer


o Octal integer without leading
zero
s String
x Hexadecimal integer, without
leading zero

Id Long integer

1.10 Simple and Compound Statements


Statement causes the computer to carry out some action. It is terminated
by semicolon. The statements are categorized into types: simple
statement and compound statement.

Simple Statement
A simple statement consists of an expression followed by a semicolon.

The execution of a simple statement causes the expression to be

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;
}

1.11 Operators and expressions


An operator is defined as a meaningful symbol which helps to carry out
specific calculations or logical comparison. An operand is termed as
variable or constant that holds data operation. An expression is defined as
the combination of operators and operands. C language provides wide
variety of operators which are follows:

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.

Operator Meaning Example


< Is less than a<b
<= Is less than or equal a<=b
to
> Is greater than a>b
>= Is greater than or a>=b
requal to
== Is equal to a==b
!= Is not equal to a!=b

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:

• ++ variable name(increment prefix)


• Variable name++(increment postfix)
• --variable name(decrement prefix)

21
• Variable name—(decrement prefix)

Ternary Operator (?: operator)


Ternary operator is also known as conditional operator as it checks
condition to make decision. It uses two symbol: the question mark (?) and
the colon (:) but not together as in >=, <= etc. This is the only operator
use in C that takes three operands, so it is named as ternary operator.

Syntax:

(condition) ? statement 1 : statement 2


Example:

A =10;
B=15;
X=(A>B) ? A : B;

1.12 Input/ output (I/O) Functions


Like other languages, C does not have any built-in input/output
statements as part of syntax. All input/output operations are carried out
through printf() and scanf() function. These functions are known as the
standard I/O library function because they can take or accept any type of
data. Each program that uses a standard input/ output function must
contain a statement #include<stdio.h> at the beginning. The instruction
#include<stdio.h> tells the compiler to search for a file named stdio.h
and place its contents at this point in the program. The contents of the
header file become part of the source code when it is compiled.

Differentiate between printf() and scanf() statements


printf() scanf()
 It is used to display contents  It is used to get inputs from
(text/number) the user.

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);
}

Other input/output functions

getchar()/putchar(): The getchar() function is used to read (or accept)


a single character. It cannot take more than one character. The
putchar() function is used to display character contained in the
variable name at the terminal.

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);

1.13 Selection Control statement: Decisions


(if, if-else, if-else-if, nested and , switch)
A control statement in programming is a fundamental concept used to
dictate the flow of execution of a program. It allows the program to make
decisions, repeat certain actions, or jump to specific parts of the code
based on specific conditions. Control statements are essential for creating
dynamic and responsive programs, as they enable developers to control
how and when different blocks of code are executed. The main types of
control statements include conditional statements (like if, if-else, and
switch), looping statements (such as for, while, and do-while), and
branching statements (like break, continue, and return). These statements
work together to make programs more logical, efficient, and interactive.

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;
}

Nested if else statement


The nested if-else statement is a form of conditional statement in which
an if or else block contains another if-else statement inside it. This
structure allows the program to make a second-level decision based on
the result of the first condition. When the outer condition is true, the inner
if-else is evaluated to make a more specific decision. Similarly, if the outer
condition is false, an inner if-else inside the else block can also be used.
This form of nesting helps in handling situations where decisions depend
on multiple layers of conditions, making the program more precise and
logically structured.

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);

Difference between while loop and do while loop


While loop Do while loop
In this loop the condition is In this loop, the condition is
checked in the beginning. check at the end.

It uses keyword ‗while’ It uses keyword ‗do‘ and ‗while‘


The syntax is as follows: The syntax is as follows:
while (condition) { do {
statements; statements;
increment/decrement; 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;
}
}

1.15 Array: definition, types (1D and 2D),


matrix addition and subtraction
Introduction to Array
An array is a data structure used in programming to store a fixed-size
collection of elements of the same data type under a single variable
name. Each element in an array is stored in a contiguous memory
location and can be accessed using its index, with indexing typically
starting from 0. Arrays are useful when you need to work with multiple
values of the same type, such as a list of numbers, names, or other
items, making it easier to organize and manipulate data efficiently. They
help in reducing the number of variables and simplify operations like
searching, sorting, and iterating over elements. Arrays can be one-
dimensional or multi-dimensional depending on the complexity of the
data being handled.

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:

• Efficient Data Management: Arrays allow you to store and


manage multiple values of the same data type under a single
variable name, making the code more organized and easier to
manage.
• Indexed Access: Elements can be accessed quickly using their
index, which improves the speed of data retrieval and
manipulation.
• Reduced Code Complexity: Instead of declaring many variables,
a single array can hold all the values, reducing redundancy and
making the code cleaner.
• Ease of Traversal: Arrays can be easily traversed using loops like
for or while, allowing efficient processing of data.

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.

The general form of one dimensional array declaration is, Syntax

data_type_array_name[array_size]; Example int a[5];

float weight[100];

char temp[10]; int


marks[5] = {50,60,65,70,55};
marks[0] marks[1] marks[2] marks[3] marks[4]
50 60 65 70 55
index 0 index 2 index 3 index 4 index 5

Multi Dimensional Array


Multidimensional arrays are defined the same as one –dimensional

arrays, except that it consists more than one pair of square brackets that

is subscript. Thus, a two dimensional array will require two square

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.

Syntax data_type_array_name[row_size][column_size]; Example

int x[2][2]; float num[2][3]; char str[5][5]; int matrix[3][3]

= {100,200,300,200,150,50,350,500,600};

Column 0 Column 1 Column


2
[0][0] [0][1] [0][2]

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

Difference between one dimensional and two


dimensional array
One dimensional array Two dimensional array
It consists of only one subscript. It consists of two subscripts.
Maximum size will be the sized of Maximum size will be the product of
array which we define in program. row and column size of array which
we define in program.

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];

1.16 Strings: Definition and string


function:

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

char name[10]; char

address[10]; char str[100];

char title[10] = {‗c‘,‘‘,‘p‘,‘r‘,‘o‘,‘g‘,‘r‘,‘a‘,‘m‘,‘m‘,‘i‘,‘n‘,‘g‘};

or,

char title[10]=‖c programming‖;

name[0] name[0] name[0] name[0] name[0] name[0] name[0] name[0] name[0]


name[0]
‗c‘ ‗‘ ‗p‘ ‗r‘ ‗o‘ ‗g‘ ‗r‘ ‗m‘ ‗m‘ ‗\0‘
Index 0 Index 1 Index 2 Index 3 Index 4 Index 5 Index 6 Index 7 Index 8 Index
9

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

other string. Syntax

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

uppercase characters. Syntax

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 ;

2. Find out the square root of a number using C program.


#include <stdio.h>
#include <math.h>
int main(){
float num;
printf("Enter a number: ");

38
scanf("%f", &num);
printf("Its square root is: %.2f", sqrt(num));
return 0;
}

3. Write a program to calculate and print simple interest (SI) and


the net amount (A).
#include <stdio.h>
int main() {
float principal, rate, time, simpleInterest, netAmount;
printf("Enter the principal amount: ");
scanf("%f", &principal);
printf("Enter the annual interest rate (in percentage): ");
scanf("%f", &rate);
printf("Enter the time (in years): ");
scanf("%f", &time);
simpleInterest = (principal * rate * time) / 100;
netAmount = principal + simpleInterest;
printf("Simple Interest (SI): %.2f\n", simpleInterest);
printf("Net Amount (A): %.2f\n", netAmount);
return 0;
}

4. Write a program to calculate distance using s = ut + ½ (at^2).


#include <stdio.h>

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; }

5. Write a program to calculate area and circumference of a circle.


#include <stdio.h>
#define PI 3.14159
int main() {
float radius, area, circumference;
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
area = PI * radius * radius;
circumference = 2 * PI * radius;
printf("Area of the circle: %.2f\n", area);
printf("Circumference of the circle: %.2f\n", circumference);
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;
}

7. Write a program to calculate to find the sum of two distances &


the distance is measured in feet & inch.
#include <stdio.h>
int main() {
int feet1, inch1, feet2, inch2;
int totalFeet, totalInch;
printf("Enter the first distance:\n");
printf("Feet: ");
scanf("%d", &feet1);
printf("Inches: ");
scanf("%d", &inch1);
printf("Enter the second distance:\n");
printf("Feet: ");
scanf("%d", &feet2);
printf("Inches: ");
scanf("%d", &inch2);

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;
}

8. Write a C program to enter number of days & convert it into


years, months & days.
#include <stdio.h>
int main() {
int days, years, months, remainingDays;
printf("Enter the number of days: ");
scanf("%d", &days);
years = days / 365;
days = days % 365;
months = days / 30;
remainingDays = days % 30;
printf("Years: %d, Months: %d, Days: %d\n", years, months, remainingDays);
return 0;
}

9. Complete the following programs & discuss the outputs.


Program 1

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;
}

10. Complete the following 2 examples & discuss the output of


the programs.
Program 1
int j;
int i = 5;
j = ++i;
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;
}

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;
}

3. Write a program to read a number and check whether it is


positive negative or zero.
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (number > 0) {
printf("The number is positive.\n");
} else if (number < 0) {
printf("The number is negative.\n");
} else {

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;
}

5. Write a C program that reads three numbers and displays the


largest and smallest among them.
#include <stdio.h>
int main() {

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;}

7. Write a program to calculate and display real roots of a


quadratic equation.
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, discriminant, root1, root2;
printf("Enter coefficients a, b, and c: ");
scanf("%f %f %f", &a, &b, &c);
discriminant = b * b - 4 * a * c;
if (discriminant > 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;
}

8. Write a program to find the commission amount on the basis of


sales amount as per the following conditions
Sales Amount Commission
0 – 1000 5%
1001 – 2000 10%
>2000 12%

#include <stdio.h>
int main() {
float salesAmount, commission;
printf("Enter the sales amount: ");
scanf("%f", &salesAmount);
if (salesAmount >= 0 && salesAmount <= 1000) {
commission = salesAmount * 0.05;
} else if (salesAmount > 1000 && salesAmount <= 2000) {
commission = salesAmount * 0.10;
} else if (salesAmount > 2000) {

50
commission = salesAmount * 0.12;
} else {
printf("Invalid sales amount.\n");
return 1;
}
printf("The commission amount is: %.2f\n", commission);
return 0;
}

9. Write an interactive program that takes length and breathe and


performs the following tasks on Menu based.
a) area of rectangle b) perimeter of rectangle c) exit
#include <stdio.h>
int main() {
float length, breadth;
int choice;
printf("\nMenu:\n");
printf("1. Area of Rectangle\n");
printf("2. Perimeter of Rectangle\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter length: ");
scanf("%f", &length);
printf("Enter breadth: ");
scanf("%f", &breadth);
printf("Area of Rectangle: %.2f\n", length * breadth);
break;
case 2:

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;
}

10. Write a C program that takes a number less than 10 and


displays its multiplication table.
#include <stdio.h>
int main() {
int number;
printf("Enter a number less than 10: ");
scanf("%d", &number);
if (number >= 10) {
printf("The number must be less than 10.\n");
}
else{
printf("Multiplication table for %d:\n", number);
for (int i = 1; i <= 10; i++) {

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;
}

2. Write a program to display square series of first ‘n’ natural


numbers.
#include <stdio.h>

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;
}

3. Write a program to calculate factorial of any number given by


the user.
#include <stdio.h>
int main() {
int num, i;
float factorial = 1;
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial of a negative number doesn't exist.\n");
} else {
for (i = 1; i <= num; ++i) {
factorial *= i;
}
printf("Factorial of %d = %.0f\n", num, factorial);
}
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; }

5. Write a program to display Fibonacci series having ‘n’ terms.


#include <stdio.h>
int main() {
int n, term1 = 0, term2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
if (n <= 0) {
printf("Please enter a positive integer.\n");

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;
}

6. Write a program to check the given number is Palindrome or


not.
#include <stdio.h>
int main() {
int num, reverse = 0, rem, temp;
printf("Enter an integer: ");
scanf("%d", &num);
temp = num;
while (num != 0) {
rem = num % 10;
reverse = reverse * 10 + rem;
num /= 10;
}
if (temp == reverse) {
printf("%d is a Palindrome.\n", temp);
} else {
printf("%d is not a Palindrome.\n", temp);

56
}
return 0;
}

7. Write a program to calculate some of the following series: sum


= 1 + ½ + 1/3 + ¼ ……. + 1/n.

#include <stdio.h>
int main() {
int n;
double sum = 0.0;
printf("Enter a range: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += (1.0 / i);
}
printf("The sum of the series is: %.2f\n", sum);
return 0;
}

8. Write a program to display the following output.


1 2 3 4 5
2 4 6 8 10
3 6 9 12 15

#include <stdio.h>
int main() {

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;
}

9. Write a program to check whether the given number is prime or


not.
#include <stdio.h>
int main() {
int num, i, check = 1;
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num <= 1) {
check = 0;
} else {
for (i = 2; i < num; i++) {
if (num % i == 0) {
check = 0;
break;
}
}
}
if (check) {
printf("%d is a prime number.\n", num);
} else {

58
printf("%d is not a prime number.\n", num);
}
return 0;
}

10. Write a program to display the prime series up to ‘n’..


#include <stdio.h>
int main() {
int num, i, j, check;
printf("Enter a number: ");
scanf("%d", &num);
if (num <= 1) {
printf("Error: Enter a number greater than 1.\n");
}
else {
printf("Prime numbers up to %d are:\n", num);
for (i = 2; i <= num; i++) {
check = 1;
for (j = 2; j * j <= i; j++) {
if (i % j == 0) {
check = 0;
}
}
if (check) {
printf("%d\t", i);
}
}
printf("\n");
}

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;
}

3. Write a program to find the position of key number from given


set of numbers which are stored in an array.

#include <stdio.h>
int main() {
int n, key, pos = -1;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];

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;
}

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.

#include <stdio.h>
int main() {
int ages[100], count = 0;
for (int i = 0; i < 100; i++) {
printf("Enter age of person %d: ", i + 1);

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;
}

6. Write a program that takes salary of 100 employees and print


the salary of employees in ascending order.
#include <stdio.h>
int main() {

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;
}

8. Write a program to calculate the sum of all elements of a


matrix with size 3 X 3.
#include <stdio.h>
int main() {
int matrix[3][3], sum = 0;
printf("Enter elements of the matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
sum += matrix[i][j];
}
}
printf("Sum of all elements: %d\n", sum);
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;
}

10. Write a program to add two matrices with size 2 X 2 supplying


by elements by the user.
#include <stdio.h>

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;
}

2. Write a program to reverse the given string without using built-


in function.
#include <stdio.h>
int main() {
char str[100], reversed[100];
int i, length = 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;
}

3. Write a program to concatenate two given string without using


built-in function.
#include <stdio.h>
int main() {
char str1[100], str2[100], result[200];
int i = 0, j = 0;
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
while (str1[i] != '\0') {
result[i] = str1[i];
i++;
}
while (str2[j] != '\0') {
result[i] = str2[j];

73
i++;
j++;
}
result[i] = '\0';
printf("Concatenated string: %s\n", result);
return 0;
}

4. Write a program to input line of text & count the number of


digit, vowels, consonants, white spaces & other characters.
#include <stdio.h>
int main() {
char text[1000];
int i, digits = 0, vowels = 0, consonants = 0, spaces = 0, others = 0;
printf("Enter a line of text: ");
fgets(text, sizeof(text), stdin);
for (i = 0; text[i] != '\0'; i++) {
if ((text[i] >= 'a' && text[i] <= 'z') || (text[i] >= 'A' && text[i] <= 'Z')) {
if (text[i] == 'a' || text[i] == 'e' || text[i] == 'i' || text[i] == 'o' || text[i] ==
'u' ||
text[i] == 'A' || text[i] == 'E' || text[i] == 'I' || text[i] == 'O' || text[i] ==
'U') {
vowels++;
} else {
consonants++;
}
} else if (text[i] >= '0' && text[i] <= '9') {
digits++;
} else if (text[i] == ' ' || text[i] == '\t') {
spaces++;

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;
}

5. Write a program to check whether the given string is


palindrome or not.
#include <stdio.h>
#include <string.h>
int main() {
char str[100], rev[100];
int i, len, flag = 1;
printf("Enter a string: ");
scanf("%s", str);
len = strlen(str);
for (i = 0; i < len; i++) {
rev[i] = str[len - i - 1];
}
rev[len] = '\0';
for (i = 0; i < len; i++) {

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;
}

6. Write a program to input the names of 10 students & sort them


in alphabetical order.
#include <stdio.h>
#include <string.h>
int main() {
char names[10][50], temp[50];
int i, j;
for (i = 0; i < 10; i++) {
printf("Enter name of student %d: ", i + 1);
scanf("%s", names[i]);
}
for (i = 0; i < 9; i++) {
for (j = i + 1; j < 10; j++) {
if (strcmp(names[i], names[j]) > 0) {
strcpy(temp, names[i]);
strcpy(names[i], names[j]);

76
strcpy(names[j], temp);
}
}
}
printf("\nSorted names:\n");
for (i = 0; i < 10; i++) {
printf("%s\n", names[i]);
}
return 0;
}

7. Write a program to search a string from the given set of strings.


#include <stdio.h>
#include <string.h>
int main() {
char strings[5][50] = {
"apple",

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy