0% found this document useful (0 votes)
6 views53 pages

Cover-CS-4

The document is a final report on 'Programming in C' submitted by Arjun Kafle to the National Examination Board at Nobel Academy, fulfilling partial requirements for the NEB (10+2). It includes sections on the introduction to C programming, advantages and disadvantages of the language, basic data types, constants, variables, operators, input/output functions, and sample programs. The report is supervised by Mr. Anjan (Sagar) Sharma and acknowledges the support of various faculty members.

Uploaded by

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

Cover-CS-4

The document is a final report on 'Programming in C' submitted by Arjun Kafle to the National Examination Board at Nobel Academy, fulfilling partial requirements for the NEB (10+2). It includes sections on the introduction to C programming, advantages and disadvantages of the language, basic data types, constants, variables, operators, input/output functions, and sample programs. The report is supervised by Mr. Anjan (Sagar) Sharma and acknowledges the support of various faculty members.

Uploaded by

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

National Examination Board

Nobel Academy

A FINAL REPORT

On

Programming in C

Submitted By
Arjun Kafle

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

1
PROJECT REPORT
On
Programming in C

A report submitted in partial fulfillment of the requirement for the NEB (10+2)

Submitted By

Arjun Kafle (2081)

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

2
Date: 2081.11.11

RECOMMENDATION LETTER OF SUPERVISOR

I hereby recommend that this report proposed under my supervision by Arjun Kafle (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

3
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

4
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.

Arjun Kafle
Registration No.:

5
CONTENTS

Character Set used in C............................................................................................................................... 9

Use of Comments....................................................................................................................................... 9

Keywords in C ............................................................................................................................................ 9

Basic Data Types in C ................................................................................................................................ 10

Constants and Variables ........................................................................................................................... 10

a. Variable ............................................................................................................................................... 10

b. Constant .............................................................................................................................................. 10
1. Integer Constant: ....................................................................................................................................11
2. Floating-point Constant: ........................................................................................................................11
3. Character Constant:...................................................................................................................................11
4. String Constant: ........................................................................................................................................11
5. Declaring Constants ..................................................................................................................................11
a. Using const Keyword: ......................................................................................................................11
b. Using #define Directive: ..................................................................................................................11

Simple and Compound Statements in C..................................................................................................... 11


a. Simple Statement in C ...................................................................................................................................11
b.Compound Statement in C ..............................................................................................................................11

Operators and Expressions in C................................................................................................................. 12


a. Operators ........................................................................................................................................................12
b. Expressions ....................................................................................................................................................12

Input/Output Functions ........................................................................................................................... 13


a. Types of I/O Functions ...........................................................................................................................13
i. Input Functions .........................................................................................................................................13
ii. Output Function .............................................................................................................................................14

Introduction to Control Statement............................................................................................................ 28


Branching Statements (Selective) ...................................................................................................................29

Introduction to Array ............................................................................................................................... 37

Characteristics of Array ............................................................................................................................ 37

Introduction to String ............................................................................................................................... 45


String Handling Functions ..............................................................................................................................45

6
INTRODUCTION TO C-PROGRAMMING LANGUAGE

C programming is the high level programming language developed by American


computer scientist Denish Ritchie early in the 1970s and implemented at Bell
Laboratories. C is a general-purpose, structured programming language. Its instruction
consists of terms that resemble algebraic expressions, augmented by certain English
keywords such as if, else, for, do and while. It is used to develop system programming
as well as for application program.

Advantages of C-Programming Language

a. It is portable and powerful programming language.

b. It has both features of high level language as well as low level language.

c. It is general-purpose high level programming language.

d. It is internationally standardized programming language.

e. If is structured programming language because the program is divided into


number of basic structures called functions.

Disadvantages of C-programming language

a. C does not support object-oriented programming concepts like classes and


objects.

b. Memory management must be done manually, increasing the risk of memory


leaks.

c. There is no built-in exception handling, making error handling more complex.

d. The language lacks run-time type checking, which can lead to undetected errors.

e. C has a limited set of standard libraries compared to modern languages.

Structure of C Program

The basic structure of C program is as follows:

7
1. Preprocessor ad Header Files

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

2. 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 parts:
declaration part and executable part. The declaration part declares the variable
constant, etc. The actual program codes are written in the executable part.

3. 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 good practice for internal
documentation of programmer. It is also useful for further modification and
program testing.

4. Compiling process.

The compilation process is the process of converting source file (program codes)
into executable file (machine codes or object codes). This is automatically
performed by the c compiler.

Source File

Compiler
Library
Other Files
Object Files Object File

Linker

Executable
File

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

a. Letters: upper case A to Z and lowercase a to z

b. Digits: 0 to 9

Use of Comments

The comments have no effects on program codes but they are useful components of
program for program documentation. They help programmer for the description of the
program codes. They also make programmer to modify and testing of a progam Comments
can be written in two forms:
c. Single Line Comments
d. Multi-Line Comments

Keywords in C

Keywords are special words that have a fixed meaning. These words are used by the C
compiler to understand the structure and instructions in a program. Since they are
reserved by the language, we cannot use them as variable names, function names, or any
other identifiers.
C has a set of standard keywords that help in writing programs. Each keyword has a
specific purpose, such as defining data types, controlling program flow, or handling
input/output.

int unsigned do static


float if break const
double else continue volatile
char switch goto struct

9
void case return union
short default auto enum
long for extern typedef
signed while register sizeof

Basic Data Types in C


In the C programming language, basic data types are the building blocks used to declare
variables and functions. These types tell the compiler what kind of data is being used. There
are the 4 basic data types in C. They are:

Data Type Description Example


int Used to store integers (whole numbers) int age = 25;
float Used to store decimal numbers (single float price = 12.5;
precision)
double Used for larger or more precise decimal double pi =
numbers (double precision) 3.14159;
char Used to store a single character char grade = ‘A’;

Constants and Variables


a. Variable
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:
1. They must always begin with a letter, although some systems permit underscore as the first
character.
2. White space is not allowed.
3. A variable should not be a keyword.
4. It should not contain any special characters.
5. It does not allow keyword.

b. Constant
A constant in C is a value that does not change during the execution of a program. Once
defined, its value remains fixed. There are several types of constants in C. They are:

10
1. Integer Constant:
An integer constant represents whole numbers without any decimal point, like 25 or -10.

2. Floating-point Constant:
A floating-point constant represents numbers with decimal points, such as 3.14 or -0.5.

3. Character Constant:
A character constant holds a single character enclosed in single quotes, like ‘A’ or ‘9’.

4. String Constant:
A string constant is a sequence of characters enclosed in double quotes, like “Hello” or
“123”.

5. Declaring Constants

a. Using const Keyword:


The const keyword is used to declare a constant variable whose value cannot be changed
during program execution.
b. Using #define Directive:
The #define directive creates a constant using a name, which is replaced by its
value before compilation.

Simple and Compound Statements in C

a. Simple Statement in C
A simple statement is a single instruction in C that ends with a semicolon (;). It performs one
task, such as assigning a value or calling a function.
Example: x = 10;

b.Compound Statement in C
A compound statement is a group of two or more statements enclosed in curly braces {}. It is
used to execute multiple statements where only one is normally allowed, such as inside if,
while, or for blocks. Example:

11
{
int a = 5;

int b = 10;
printf(“%d”, a + b);

Operators and Expressions in C


a. Operators
Operators are symbols used to perform operations on variables and values.
They tell the compiler what kind of computation or comparison to perform.

Example:
int a = 5 + 3; // ‘+’ is an operator.

b. Expressions
An expression is a combination of variables, constants, and operators that results es,
constants, and operators that results in a single value.It includes variables a and b, numbers
(2), and operators (+, *).The expression evaluates to a value when executed.
Example:
a + b * 2 // This is an expression.

Operator Type Operator(s) Description Example

Arithmetic +, -, *, /, % Used for a + b, a % b


mathematical
operations
Relational ==, !=, >, <, >=, Compares two a != b, a > b
<= values, returns
true/false
Logical &&, ` , !`
Assignment =, +=, -=, *=, /=, Assigns value to a a += 5 (a = a + 5)
%= variable
Increment/Decrement ++, -- Increases or a++, --b
decreases value by
1
Bitwise &, ` Operates on binary
bits
Conditional ?: Shorthand for if- a>b?a:b
(Ternary) else

12
Comma , Separates multiple a = (b = 3, b + 2)
expressions
Sizeof sizeof() Returns size of sizeof(int)
variable/data type
Typecast (type) Converts one data (float)a
type to another
Address & Pointer &, * & gets address, * &a, *ptr
dereferences
pointer

Input/Output Functions
In C programming, Input/Output functions are used to take information from the user (input)
and show information to the user (output). For example, if we want the user to enter their
name or age, we use input functions like scanf(). If we want to display a message or result on
the screen, we use output functions like printf(). These functions are part of the stdio.h
library, which we include at the beginning of your program. These functions are already
built-in in C and come from the stdio.h library (Standard Input Output).

a. Types of I/O Functions


i. Input Functions
These are used to take data from the user. Example: scanf(), getchar(), gets(), etc. Input
functions in C are used to take input from the user during program execution, for example,
scanf() is used to read values like numbers or characters from the keyboard. For example:
printf() Function
Syntax:

printf(“format string”, variables);

Example:

#include <stdio.h>

int main() {
int age = 25;
printf(“My age is %d\n”, age);
return 0;
}

13
ii. Output Function
These are used to show data on the screen. Example: printf(), putchar(), puts(), etc.Output
functions in C are used to display information on the screen, such as messages or results. The
most commonly used output function is printf(), which prints text or variable values to the
screen. For example:
scanf() Function
Syntax:
scanf(“format string”, &variables);

Write a program to input three numbers and print sum and average using C-program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, s, avg;
printf(“enter three numbers”);
scanf(“%d%d%d”, &a, &b, &c)
s = a+b+c;
avg = s/3
printf(“the sum is %d and the average is %d, s”);
getch();
}

Write a program to find out the square of a number.


#include<stdio.h>
#include<conio.h>

14
void main()
{
int a, s;
printf(“enter any number”);
scanf(“%d”, &a);
s = a*a;
printf(“the square of the number is %d, s”);
getch();}

Write a program to calculate and print simple interest.


#include<stdio.h>

#include<math.h>

int main()

float principal, rate, time, si, ci;

int n;

printf(“enter the amount: “);

scanf(“%d”,&principal);

printf(“enter the rate of interest in percent: “);

scanf(“%d”,&rate);

printf(“enter the time in year: “);

scanf(“%d”, &time)

si = principal*rate*time / 100;

printf(“simple interest is : %d”, si, );

15
getch();
Y
}

Write a program to calculate distance using s = ut + ½* at².


#include<stdio.h>

#include<math.h>

int main()

int u, t, a;

float s;

printf(“enter initial velocity”);

scanf(“%d”, &u);

printf(“enter time taken”);

scanf(“%d”, &t);

printf(“enter acceleration”);

scanf(“%d”, &a);

s = u*t + ½*a*t*t;

printf(“the distance is %d”, s);

return 0;

16
Write a program to calculate area and circumference of a circle.
#include<studio.h>

#include<conio.h>

int main()

float a, r, c;

const float pi = 3.14;

printf(“enter radius of circle”);

scanf(“%f”, &r);

a = pi*r*r;

c = 2*pi*r;

printf(“the area of circle is %.2f and the circumference of circle is %.2f”, a, c);

return 0;

Write a program to convert temperature in centigrade© into Fahrenheit(F).


#include<stdio.h>

int main()

float c, f;

float a = 1.8;

printf(“enter the temperature in centigrade©:”);

scanf(“%f”, &c);

17
f = a*c + 32;

printf(“the temperature in centigrade© into fahrenheit(f) is %.2f/n”, f);

return 0;

Write program to calculate sum of two distances and the distance is measured in terms
of feet and inch.
#include <stdio.h>

int main()

int feet1, inches1, feet2, inches2, totalfeet, totalinches;

printf(“Enter first distance (feet inches): “);

scanf(“%d %d”, &feet1, &inches1);

printf(“Enter second distance (feet inches): “);

scanf(“%d %d”, &feet2, &inches2);

totalinches = inches1 + inches2;

totalfeet = feet1 + feet2 + (totalinches / 12);

totalinches %= 12;

printf(“Total distance: %d feet %d nches\n”, totalfeet, totalinches);

return 0;

18
Write a program to enter number of days and convert it into years, months and days.
#include <stdio.h>

int main() {

int d, m, y, r, a;

printf(“Enter number of days: “);

scanf(“%d”, &d);

y = d / 365;

r = d % 365;

m = r / 30;

a = r % 30;

printf(“Years: %d, Months: %d, Days: %d\n”, y, m, a);

return 0;

19
Write a program to calculate area and circumference of a real circle.
#include <stdio.h>

#include <math.h>

#define pi 3.14159

int main()

float radius, area, circumference;

printf(“Enter the radius of the circle: “);

scanf(“%f”, &radius);

if (radius <= 0) {

printf(“Error: Radius must be a positive number!\n”);

else

area = pi * radius * radius;

circumference = 2 * pi * radius;

printf(“Area of the circle: %.2f\n”, area);

20
printf(“Circumference of the circle: %.2f\n”, circumference);

return 0;

Write a program to check whether the given number is odd or even.

#include<stdio.h>

int main()

int a, n;

printf(“Enter any number:”);

scanf(“%d”, &a);

n = a%2;

if(n == 0)

printf(“The given number is even”);

else

printf(“The given number is odd”);

return 0;

21
Write a program to calculate area and circumference of real circle (hint: real circle is a
circle having positive radius).

#include <stdio.h>
#define pi 3.14159
int main() {
double r, a, c;
printf(“Enter radius: “);
scanf(“%lf”, &r);
if (r > 0) {
a = pi * r * r;
c = 2 * pi * r;
printf(“Area: %.2lf\n”, a);
printf(“Circumference: %.2lf\n”, c);
} else {
printf(“Invalid radius\n”);
}
return 0;
}

Write a program to check whether the given number is odd or even.

#include <stdio.h>
int main() {
int n;
printf(“Enter a number: “);
scanf(“%d”, &n);
if (n % 2 == 0) {
printf(“%d is even\n”, n);
} else {
printf(“%d is odd\n”, n);
}
return 0;
}

Write a program to read a number and check whether it is positive, negative or zero.

#include <stdio.h>
int main() {
int n;
printf(“Enter a number: “);
scanf(“%d”, &n);
if (n > 0) {

22
printf(“%d is positive\n”, n);
} else if (n < 0) {
printf(“%d is negative\n”, n);
} else {
printf(“The number is zero\n”);
}
return 0;
}

Write a program that inputs cost price (cp) and selling price (sp) and determines
whether there is loss or gain.

#include <stdio.h>
int main() {
float cp, sp, result;
printf(“Enter cost price: “);
scanf(“%f”, &cp);
printf(“Enter selling price: “);
scanf(“%f”, &sp);
result = sp – cp;
if (result > 0) {
printf(“Profit: %.2f\n”, result);
} else if (result < 0) {
printf(“Loss: %.2f\n”, -result);
} else {
printf(“No profit, No loss\n”);
}
return 0;
}

Write a c program that reads three numbers and displays the largest and the smallest
among them.

#include <stdio.h>
int main() {
int a, b, c, largest, smallest;
printf(“Enter three numbers: “);
scanf(“%d %d %d”, &a, &b, &c);

if (a > b) {
if (a > c) {
largest = a;

23
} else {
largest = c;
}
} else {
if (b > c) {
largest = b;
} else {
largest = c;
}
}

if (a < b) {
if (a < c) {
smallest = a;
} else {
smallest = c;
}
} else {
if (b < c) {
smallest = b;
} else {
smallest = c;
}
}

printf(“Largest: %d\n”, largest);


printf(“Smallest: %d\n”, smallest);
return 0;
}

Write a c program that takes three different numbers and find out the middle number.

#include <stdio.h>
int main() {
int a, b, c;
printf(“Enter three different numbers: “);
scanf(“%d %d %d”, &a, &b, &c);

if (a > b) {
if (a < c) {
printf(“Middle number is: %d\n”, a);
} else if (b > c) {
printf(“Middle number is: %d\n”, b);
} else {
printf(“Middle number is: %d\n”, c);

24
}
} else {
if (a > c) {
printf(“Middle number is: %d\n”, a);
} else if (b < c) {
printf(“Middle number is: %d\n”, b);
} else {
printf(“Middle number is: %d\n”, c);
}
}

return 0;
}

Write a program to calculate and display real roots of a quadratic equation. (hint check
condition (b2-4ac)>0 for real root).

#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) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b – sqrt(discriminant)) / (2 * a);
printf(“real and distinct roots: %.2f and %.2f\n”, root1, root2);
} else if (discriminant == 0) {
root1 = -b / (2 * a);
printf(“Real and equal roots: %.2f\n”, root1);
} else {
printf(“No real roots\n”);
}

return 0;
}

Write a program to find the commission amount on the basis of sales amount as per the
following conditions:

25
Sales amount. Commission
0-1000 5%
1001-2000 10%
>2000 12%

#include <stdio.h>
int main() {
float sales, commission;

printf(“Enter the sales amount: “);


scanf(“%f”, &sales);

if (sales >= 0 && sales <= 1000) {


commission = sales * 0.05;
} else if (sales > 1000 && sales <= 2000) {
commission = sales * 0.10;
} else if (sales > 2000) {
commission = sales * 0.12;
} else {
printf(“Invalid sales amount\n”);
return 1;
}

printf(“Commission amount: %.2f\n”, commission);


return 0;
}

Write interactive program that takes length and breadth and performs the following
task.

A) area of rectangle
B) perimeter of rectangle
C) exit

#include <stdio.h>

int main() {
float length, breadth, area, perimeter;
int choice;

26
while (1) {
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);

if (choice == 1 || choice == 2) {
printf(“enter length and breadth of the rectangle: “);
scanf(“%f %f”, &length, &breadth);
}

if (choice == 1) {
area = length * breadth;
printf(“area of the rectangle: %.2f\n”, area);
} else if (choice == 2) {
perimeter = 2 * (length + breadth);
printf(“perimeter of the rectangle: %.2f\n”, perimeter);
} else if (choice == 3) {
printf(“exiting the program…\n”);
break;
} else {
printf(“invalid choice. please try again.\n”);
}
}

return 0;
}

27
Write a c program that takes a number less than 10 and display its multiplication table.

#include <stdio.h>

int main() {
int num;

printf(“enter a number less than 10: “);


scanf(“%d”, &num);

if (num >= 10 || num < 0) {


printf(“invalid input! please enter a number less than 10.\n”);
} else {
for (int i = 1; i <= 10; i++) {
printf(“%d x %d = %d\n”, num, i, num * i);
}
}

return 0;

Introduction to Control Statement

In most of the programs, the program statements are executed in the same order in which they
are written. Each instruction is executed only once. This is not enough in programming.
Sometimes we may have to execute program statements based on the given condition,
sometimes we may have to execute program statements repeatedly, sometimes we may have
to choose an option and perform the task accordingly. To carry out all these task and other
similar tasks, program statements must be executed in controlled way and it can be done
using control structure.

Control Structure is also known as control statement. It is defined as the group of statements
or function that helps to control the flow of instructions in a program. It allocates programmer

28
to control the flow of program statements execution in a program. It also specifies the order
of statements in program. If there are no control statements, the statements are executed in
sequential manner, commonly known as sequential statements. Mainly, there are three types
of control statements:

a. Branching Statements (Selective)

b. Looping Statements (Iterative or Repetitive)

c. Jumping statement (Unconditional)

Branching Statements (Selective)

If statement

It is the simplest form of conditional statement in which statements are executed if the te
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)
{
// if body
// Statements to execute if condition is
true
}

If else statement
It is another form of selective control structure which can handle both expected as well a
unexpected situation. In this control structure, statements written in body part of if an
executed if the condition is true otherwise statements written in body part of else an executed.
This is appropriate where we must check only one condition.

Syntax:

if (condition) {
// Code to execute if condition is true
}
else {
// Code to execute if condition is
false
}

29
If else if statement

When we have two or more conditions to be checked in a series we can use if-else if
statement. It is also known as multiple conditional statement/ multipath conditional
statement/if-else ladder.

Syntax:

Nested if else statement

An entire if else statement written within the body of if part or else part of another if e
statement is called nested if else statement. It is used when a condition is to be checke inside
another condition at a time in the same program to make decision.

Switch Case Statement

C switch statement is a multipath decision-making statement that allows selection and


xecution of a block of statements from several blocks of statements based upon the valm of
expression which is included within switch statement and branches accordingly. The
expression must be of an integral value or character constant. The switch statement body
consists of a series of case labels and an optional default label. The default label can appear
only once in the body of the switch statement.

Iteration Control Statement: Looping (while, do while, for nested)

Looping

Looping is the process of executing the same program statement or block of program
statements repeatedly for specified number of times or until the given condition is satisfied.
Loop structure is used to carry out looping. Loop is a control structure that executes the same
program statement or block of program statements repeatedly for specified number of times
or till the given condition is satisfied.

For example, if we want to display “C is the best” 10 times, one way to get the desired output
is we type printf(“C is the best”); 10 times, which is time consuming and hence not
preferable. Another way to perform this is use of loop structure. With loop structure we do

30
not need to type the same program statement again and again. Loop structure is also known
as repetitive control structure or iterative control structure.

Mainly there are three types of loop: for, while and do while loop.

While loop

It executes the program statements repeatedly until the given condition is true. It checks
condition at first, if it is found true then it executes the statements written in its body pin
otherwise it just gets out from the loop structure. It is also known as entry control or pre test
loop.

Do while loop

It also executes program statements repeatedly until the given condition is true. It executes
the program statements once at first then only condition is checked. If condition is your true
then it executes the program statements again, otherwise it gets out from the loop structure.
As it checks condition at last it is also known post-test loop or exit control loop.

For loop

It is the most common type of loop which is used to execute program statement or block of
program statements repeatedly for specified number of time. It is definite loop. Mainly it
consists three expressions initialization, condition and increment/decrement. The
initialization defines the loop starting point, condition defines the loop stopping points and
counter helps to increment and decrement the value of counter variable.

Nested Loop

We can write an entire loop structure inside another loop structure. So, loop inside loop is
called nested loop.

Infinite Loop

A loop which never terminates is called infinite loop that is it executes the program.
Statements repeatedly which does not meet any ending point.

Jumping Statement

Jumping statements are particularly used to jump execution of program statements f one
place to another place inside a program. These statements may execute same program
statement repeatedly or skip some program statements. There are three jumping statements:
break, continue and goto statement.

Break Statement

As its name implies, it is used to break the normal flow of program statement executionin
loop and switch case statement. It allows us to exit from innermost enclosing loop or switch
statement as soon as certain condition is satisfied. When ‘break” is encountered in program

31
(loop body/switch statement), remaining part of the loop/switch statement is skipped and
control will be passed to the next statement after loop; terminating the loop/switch statement.
For example, when the counter value of the loop becomes i4, then the loop is immediately
terminated.

Continue statement

As its name implies, it is used to continue the normal flow of program statement executive in
loop; skipping the iteration in the loop as soon as certain condition is satisfied. What
“continue” is encountered in the program (loop body) then that particular iteration skipped
and the loop will be continued with the next iteration.

Goto statement

When goto staternent is encountered in a program then it transfers the control of the program
statements execution unconditionally to the location specified by the goa statement within a
current function.

c language lab works 3 looping statements

Write a program to calculate and display the following series: 1 3 5……… to 10th term.

#include <stdio.h>
int main() {
int term = 1, i;
for(i = 0; i < 10; i++) {
printf(“%d “, term);
term += 2;
}
return 0;
}

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

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

32
int n, i;
scanf(“%d”, &n);
for(i = 1; i <= n; i++) {
printf(“%d “, i * i);
}
return 0;
}

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

#include <stdio.h>
int main() {
int n, i, factorial = 1;
scanf(“%d”, &n);
for(i = 1; i <= n; i++) {
factorial = factorial*i;
}
printf(“Factorial of %d is %d”, n, factorial);
return 0;
}

Write a program to calculate and display the multiplication table of a number.

#include <stdio.h>
int main() {
int n, i;
scanf(“%d”, &n);
for(i = 1; i <= 10; i++) {
printf(“%d x %d = %d\n”, n, i, n * i);
}
return 0;
}

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

#include <stdio.h>
int main() {
int n, i;
int first = 0, second = 1, next;
scanf(“%d”, &n);
printf(“Fibonacci series: “);

33
for(i = 1; i <= n; i++) {
if(i == 1) {
printf(“%d “, first);
continue;
}
if(i == 2) {
printf(“%d “, second);
continue;
}
next = first + second;
first = second;
second = next;
printf(“%d “, next);
}
return 0;
}

Write a program to check the given number is palindrome or not palindrome.

#include <stdio.h>
int main() {
int n, reverse = 0, remainder, original;
scanf(“%d”, &n);
original = n;

while (n != 0) {
remainder = n % 10;
reverse = reverse * 10 + remainder;
n /= 10;
}

if (original == reverse)
printf(“The number is a palindrome.”);
else
printf(“The number is not a palindrome.”);

return 0;
}

Write a program to calculate sum of the following series.


Sum = 1+1/2+1/3+1/4+………+1/n

34
#include <stdio.h>
int main() {
int n, sum = 0;
scanf(“%d”, &n);

for(int i = 1; i <= n; i++) {


sum += 1 / i;
}

printf(“%d”, sum);
return 0;
}

Write a program to display the following output:

12345
2 4 6 8 10
3 6 9 12 15

#include <stdio.h>
int main() {
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 5; j++) {
printf(“%d “, i * j);
}
printf(“\n”);
}
return 0;
}

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

#include <stdio.h>
int main() {
int n, i, count = 0;
scanf(“%d”, &n);

for (i = 1; i <= n; i++) {


if (n % i == 0) {
count++;
}
}

35
if (count == 2)
printf(“The number is prime.”);
else
printf(“The number is not prime.”);

return 0;
}

Write a program to display the prime series up


2 3 5 7 11 upto nth term.

#include <stdio.h>
int main() {
int n, num = 2, c, i, p;
scanf(“%d”, &n);

for(c = 0; c < n; num++) {


p = 1;
for(i = 2; i <= num / 2; i++) {
if(num % i == 0) {
p = 0;
break;
}
}
if(p && num > 1) {
printf(“%d “, num);
c++;
}
}

return 0;
}

c language lab works 4: array

write a program to input marks of 5 subjects and display the total and average marks.

#include <stdio.h>
int main() {
int marks[5], total = 0;
float average;

36
for(int i = 0; i < 5; i++) {
scanf(“%d”, &marks[i]);
total += marks[i];
}

average = total / 5.0;

printf(“Total: %d\n”, total);


printf(“Average: %.2f\n”, average);

return 0;
}

Introduction to Array

It may be convenient to store a collection of similar data elements in different separate


variables. For example, if the age of 100 persons were to be stored in variables with unique
names, it certainly would be difficult, that means 100 variables needed for assigning the
Individual values. So, an array certainly solves this problem because basically the variable
name is the same. We differentiate among the values in an array by its unique subscripts with
defined size. An array is a collection of similar type of date items treated as single unit. It acts
to store related duty under the same name with an index, also known as a subscript which
helps to access individual array element.

Characteristics of Array

a. All the array elements share the common name

b. The elements of array are stored in contiguous memory locations.

c. By declaring or using array, program becomes short and simple which handles large
volume of similar kinds of data items.

d. We put the array size of fixed length as required that means once the size is declared
then the size will be fixed at the execution time of the program, so called static type.

e. We can randomly access to every element using numeric index, index starts from 0
and ends at size-1.

Advantages of array

a. It is easier for handling similar types of data in a program.

37
b. It is efficient for solving problems like sorting, searching, indexing etc.

c. It is very close to matrix; therefore it is easy for solving matrix related problems.

d. Graphic is an array of pixels so, graphics manipulation can be easily be done using
array.

Disadvantages of Array

a. It is not possible to hold dissimilar type of data in an array.

b. It is difficult to visualize the multi-dimensional array.

c. It is static in nature, so it is difficult to define the size of array during running time.

Types of Array

There are two types of array which are as follows.

One Dimensional Array:


An array which has only one subscript is named as dimensional array, a subscript is a number
of large bracket in which we put the size of the 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);

Multi Dimensional Array:


An array which has more than one subscript is named as multi dimensional array, subscripts
define each dimensions of the array.Multidimensional arrays are defined the same as one-
dimensional arrays, excer that consists more than one pair of square brackets that is subscript.
Thus, a two dimensionil arzay 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. A dimensional array will require three square brackets, and so on. In general
terms multidimensional array definition can be written as

Data type array_name[expression1][expression2]…….[expressionn);

In two dimensional array declaration we write,

38
Syntax

Data type array_name[row_size][column size);

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 n, sum = 0;
scanf(“%d”, &n);

int arr[n];

for(int i = 0; i < n; i++) {


scanf(“%d”, &arr[i]);
}

for(int i = 0; i < n; i++) {


if(arr[i] % 2 == 0) {
sum += arr[i];
}
}

printf(“sum of even numbers: %d\n”, sum);

return 0;
}

write a program to find the position of the key number from given set of numbers which any
stored in an array. [sequential search]

#include <stdio.h>
int main() {
int n, key, position = -1;
scanf(“%d”, &n);

int arr[n];

for(int i = 0; i < n; i++) {


scanf(“%d”, &arr[i]);

39
}

scanf(“%d”, &key);

for(int i = 0; i < n; i++) {


if(arr[i] == key) {
position = i + 1;
break;
}
}

if(position != -1)
printf(“key %d found at position %d\n”, key, position);
else
printf(“key %d not found\n”, key);

return 0;
}

write a program to read the age of 100 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++) {


scanf(“%d”, &ages[i]);
}

for (int i = 0; i < 100; i++) {


if (ages[i] >= 50 && ages[i] <= 60) {
count++;
}
}

printf(“%d\n”, count);
return 0;
}

40
87, 34, 91, 29, 72, 94, 62, 39, 46, 66, 98, 96, 10, 48, 57, 97, 65, 67, 59, 17, 57, 23, 10, 86, 37,
47, 65, 83, 27, 17, 4, 61, 71, 25, 47, 27, 48, 67, 85, 43, 43, 51, 65, 63, 62, 49, 34, 16, 14, 66,
28, 68, 27, 87, 18, 65, 18, 23, 94, 7, 81, 32, 57, 80, 77, 2, 20, 48, 6, 34, 43, 84, 63, 52, 84, 10,
61, 81, 51, 7, 14, 99, 23, 44, 70, 86, 95, 16, 4, 32, 81, 19, 3, 29, 50, 50, 63, 46, 68, 1

write a program to input ‘n’ numbers and find out the greatest and smallest numbers.
#include <stdio.h>

int main() {
int n, i;
scanf(“%d”, &n);

int numbers[n];
int greatest, smallest;

for (i = 0; i < n; i++) {


scanf(“%d”, &numbers[i]);
}

greatest = numbers[0];
smallest = numbers[0];

for (i = 1; i < n; i++) {


if (numbers[i] > greatest) {
greatest = numbers[i];
}
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}

printf(“greatest: %d\n”, greatest);


printf(“smallest: %d\n”, smallest);

return 0;
}

41
write a program that takes salary of 100 employees and print the salary of the employes
ascending order.
#include <stdio.h>

int main() {
int salaries[100], i, j, temp;

for (i = 0; i < 100; i++) {


scanf(“%d”, &salaries[i]);
}

for (i = 0; i < 99; i++) {


for (j = i + 1; j < 100; j++) {
if (salaries[i] > salaries[j]) {
temp = salaries[i];
salaries[i] = salaries[j];
salaries[j] = temp;
}
}
}

for (i = 0; i < 100; i++) {


printf(“%d\n”, salaries[i]);
}

return 0;
}

write a program to transpose a matrix with size 3x3.


#include <stdio.h>

int main() {
int matrix[3][3], transpose[3][3], i, j;

printf(“enter the 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];

42
}
}

printf(“transposed matrix is:\n”);


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(“%d “, transpose[i][j]);
}
printf(“\n”);
}

return 0;
}

write a program to calculate the sum of all elements of a matrix with size 3x3.
#include <stdio.h>

int main() {
int matrix[3][3], sum = 0, i, j;

printf(“enter the 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++) {
sum += matrix[i][j];
}
}

printf(“sum of all elements: %d\n”, sum);

return 0;
}

write a program to calculate the sum of diagonal matrix with size 3x3.
#include <stdio.h>

43
int main() {
int matrix[3][3], sum = 0, i, j;

for (i = 0; i < 3; i++) {


for (j = 0; j < 3; j++) {
scanf(“%d”, &matrix[i][j]);
}
}

for (i = 0; i < 3; i++) {


sum += matrix[i][i];
}

printf(“%d\n”, sum);

return 0;
}

write a program to add two matrices with size 2x2 supplying by elements by the user.
#include <stdio.h>

int main() {
int matrix1[2][2], matrix2[2][2], sum[2][2], i, j;

for (i = 0; i < 2; i++) {


for (j = 0; j < 2; j++) {
scanf(“%d”, &matrix1[i][j]);
}
}

for (i = 0; i < 2; i++) {


for (j = 0; j < 2; j++) {
scanf(“%d”, &matrix2[i][j]);
}
}

for (i = 0; i < 2; i++) {


for (j = 0; j < 2; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

for (i = 0; i < 2; i++) {


for (j = 0; j < 2; j++) {
printf(“%d “, sum[i][j]);
}
printf(“\n”);
}

44
return 0;
}

Introduction to String

String is the set of characters, digits and symbol. We can also define string as the array of
characters. The end of string is marked with special character, the '\0' that means Null
character. The size in a character string represents the maximum number of characters that
the string can hold. A string is defined as an array of characters which contains characters,
symbols, numbers, etc.

Syntax:

Char string name[string_size];

As in above syntax, char refers to the character data type that will be stored in the array,
string name is the name of the string variable and string size indicates number of characters
that can be stored inside the array.

String Handling Functions


The C library supports many string handling functions that can be used to carry out many of
the string manipulation. The header file #include<string.h> is used for string manipulation
functions. Some of the common string manipulation functions are:

Strlen() function

The strlen() function returns the length of a string which takes the string name argument.

Syntax:

i=strlen(str);

Where str is the name of string and I is the length of the


string, returned by strlen() function.

Strrev() function

The strrev() function is used to reverse the given string. It takes a string, reverses it and stores
in the same string.

45
Syntax:

strrev(str);

Where str is given string to be converted into reverse


order.

Strcpy() function

The strcpy() function is used to copy one string into another string. It takes two strings on
empty string and the given string. It copies the given string into empty string.
Syntax

Strcpy(str1,str2);

Where str1, str2 are two strings. The content of string


str2 is copied on string str1.

Strcat() function

The strcat() function is used to join or concatenate one string into other string. It takes two
stings and second string is concatenated over first string.
Syntax

Strcat(str1,str2);

Where str1, str2 are two strings. The content of str2 is


concatenated to str1.

Strcmp() function

The strcmp() function is used to compare two strings, character by character and stops
comparison when there is a difference in the ASCII value or the end of any one string and
returns ASCII difference of the characters that is integer which is either zero, positive value
or negative value. 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

46
V=strcmp(str1,str2);

Where str1,str2 are two strings to be compared and v is a value returned by the function.

Strlwr() function

The striwr() function is used to convert upper case characters of string into lower case
characters.
Syntax

Strlwr (str);

Where str is string to be converted into lower case characters.

Strapr() function

The strupr() function is used to convert lower case characters of string into upper ca
characters.

Syntax

Strupr (str);

Where str is string to be converted into upper case characters.

C Language Lab Works 5: String

47
Write a program to find the length of string without using built in function.

#include<stdio.h>
int main(){
char s[100];
int i=0;
scanf("%s", s);
while(s[i]!='\0') i++;
printf("Length: %d\n", i);
return 0;
}

Write a program to reverse the given string without using built in function.

#include<stdio.h>
int main() {
char s[100], rev[100];
int i=0, len=0;
scanf(“%s”, s);
while(s[len]!=’\0’) len++;
for(i=0;i<len;i++) rev[i]=s[len-1-i];
rev[len]=’\0’;
printf(“reverse: %s\n”, rev);
return 0;
}

Write a program to concatenate two given strings without using built in function.

#include<stdio.h>
int main() {
char a[100], b[100], c[200];
int i=0, j=0;
scanf(“%s %s”, a, b);
while(a[i]!=’\0’) { c[i]=a[i]; i++; }
while(b[j]!=’\0’) { c[i]=b[j]; i++; j++; }
c[i]=’\0’;

48
printf(“concatenated: %s\n”, c);
return 0;
}

Write programs for the following problems using built in functions: strlen() and
strrev().

#include<stdio.h>
#include<string.h>
int main() {
char s[100];
scanf(“%s”, s);
printf(“length: %lu\n”, strlen(s));
printf(“reverse: %s\n”, strrev(s));
return 0;
}

Write programs for the following problems using built in functions: strcmp() and
strcpy().

#include<stdio.h>
#include<string.h>
int main() {
char a[100], b[100], c[100];
scanf(“%s %s”, a, b);
printf(“compare: %d\n”, strcmp(a, b));
strcpy(c, a);
printf(“copied: %s\n”, c);
return 0;
}

Write programs for the following problems using built in functions: strcat() and
strupri).

49
#include<stdio.h>
#include<string.h>
int main() {
char a[100], b[100];
scanf(“%s %s”, a, b);
strcat(a, b);
printf(“concatenated: %s\n”, a);
printf(“uppercase: %s\n”, strupr(a));
return 0;
}

Write a program to input line of text and count the number of digit, vowels, consonants,
wh spaces and other characters.

#include<stdio.h>
#include<ctype.h>
int main() {
char s[200];
int d=0,v=0,c=0,w=0,o=0,i=0;
gets(s);
while(s[i]!=’\0’) {
if(isdigit(s[i])) d++;
else if(strchr(“aeiouaeiou”,s[i])) v++;
else if(isalpha(s[i])) c++;
else if(s[i]==’ ‘) w++;
else o++;
i++;
}
printf(“digits:%d vowels:%d consonants:%d spaces:%d others:%d\n”,d,v,c,w,o);
return 0;
}

Write a program to check whether the given string is palindrome or not.

#include<stdio.h>
#include<string.h>

50
int main() {
char s[100];
int i, len, pal=1;
scanf(“%s”, s);
len = strlen(s);
for(i=0;i<len/2;i++) if(s[i]!=s[len-1-i]) pal=0;
printf(“%s\n”, pal?”palindrome”:”not palindrome”);
return 0;
}

Write a program to input the names of 10 students and 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++) gets(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]);
strcpy(names[j],temp);
}
for(i=0;i<10;i++) puts(names[i]);
return 0;
}

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] = {

“Maths”, “Physics”, “Chemistry”, “Computer Science”, “English”, “Nepali” };


char search[50];
int found = 0;
printf(“enter a string to search: “);

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

SOURCES

GeeksforGeeks – https://www.geeksforgeeks.org/c-programming-language/

TutorialsPoint – https://www.tutorialspoint.com/cprogramming/
W3Schools – https://www.w3schools.com/c/

52
CONCLUSION
In conclusion, this project has really helped me understand the basics and importance of the C
programming language. C is often called the “mother of all programming languages” because
many other languages are built on its concepts. Working on this project showed me just how
important C is in the world of programming and how it helps us learn the core ideas behind
writing code.

During this project, I learned and practiced many important topics like data types, operators,
loops, conditional statements (like if-else), arrays, functions, pointers, structures, and file
handling. These are the basic tools every programmer needs to know. By using them, I was
able to write programs that are clean, organized, and easier to understand.

One of the more difficult but interesting parts of C was learning about pointers. At first, it
was confusing, but over time, I began to understand how powerful they are. Pointers helped
me see how memory is used and controlled in a program, which is something many high-
level languages hide from us. This knowledge gave me a better understanding of how
computers actually work.

I also learned how important it is to divide a big task into smaller pieces by using functions.
This made my code easier to manage, test, and reuse. It also made solving problems feel less
overwhelming.

Another thing I noticed is that even though C looks simple, it gives you a lot of control over
your program. It helps you learn how programs really run behind the scenes, especially in
system-level programming like operating systems and hardware control.

Overall, this project not only improved my coding skills but also made me more confident in
using C. It has prepared me to explore more advanced programming concepts and even other
languages in the future. I now understand why C is still taught and used today—it builds a
strong foundation that every programmer can benefit from.

53

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