0% found this document useful (0 votes)
3 views

?️

The document provides a comprehensive overview of the C programming language, including its history, characteristics, advantages, and disadvantages. It details the basic structure of a C program, fundamental concepts such as data types, operators, and control structures, as well as input/output functions and arrays. The document serves as a foundational guide for understanding and utilizing C in software development.

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)
3 views

?️

The document provides a comprehensive overview of the C programming language, including its history, characteristics, advantages, and disadvantages. It details the basic structure of a C program, fundamental concepts such as data types, operators, and control structures, as well as input/output functions and arrays. The document serves as a foundational guide for understanding and utilizing C in software development.

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/ 68

OVERVIEW AND HISTORY OF C LANGUAGE.........................................................................................

Characteristics of C ……...........................1

Advantages of C………………………… 1

Disadvantages of C ………………..…….1

BASIC STRUCTURE OF C PROGRAM…………………………….2

C PRE-PROCESSOR AND HEADER FILES………………….3

The C preprocessor ……………….3

`Header Files 3

FUNDAMENTAL OF C 4

The C character sets 4

Comment 4

Comment is a text or set of other characters, which is not compiled or executed from the compiler. It
is written in the program to give required information to other programmers and the developrs
themselves. There are two types of comment writing methods: 4

C Tokens 5

Keywords 5

Identifiers 5

1
Data types in C 5

Primary data types 6

Derived data types 6

User defined data types 6

Constants and Variables 7

Constants 7

Variables 7

Escape Sequences 7

OPERATORS AND EXPRESSIONS 8

Operators 8

Expressions 8

Statements 9

A statement is a command given to the computer that instructs the computer to take a specific
action such as display to the screen or collect input. A computer program is made up of a series of
statements. 9

INPUT AND OUTPUT(I/O) FUNCTIONS 9

A set of rules or routine defined for input and output of data are called I/O functions. These
functions are responsible for receiving data from different components like keyboard, file or

2
network. In C, I/O operations are implemented in the library file <stdio.h>. There are two ways of
performing I/O operation in C. They are 9

Formatted I/O 9

Formatted I/O functions are used to read and display the data in desired format. Formatted IO
functions in C are: 9

Unformatted I/O 9

CONTROL STRUCTURE 10

Sequence Statements 10

Selection Statement 10

The if statement 10

The if else statement 11

Nested if statement 11

The if-else-if ladder 12

The switch statement 13

REPETITIVE STATEMENTS(LOOPS) 14

The while loop 14

The for loop 14

3
The do while loop 15

JUMP STATEMENTS 15

ARRAYS AND STRINGS 15

Introduction to arrays 15

TYPES OF ARRAY 15

Declaring and Initializing Arrays 16

Accessing Array Elements 16

Advantages of Arrays 16

Disadvantages of Arrays 16

STRING 16

Declaring and Initializing Strings 16

String Input and Output 17

Common String Functions (from <string.h>) 17

Differences Between Arrays and Strings 17

A) Arrays can store any data type, whereas strings specifically store characters. 17

Applications of Arrays and Strings 18

4
Conclusion 60

Reflection 61

OVERVIEW AND HISTORY OF C LANGUAGE

C is a high-level programming language that was developed by Dennis Ritchie in the early
1970s at Bell Laboratories. It was originally created for writing the Unix operating system,
which contributed to its widespread adoption. C provides a structured approach to
programming and allows direct access to memory, making it both powerful and efficient.

Over time, C became one of the most widely used programming languages and influenced
many modern languages. It is known for its simplicity and portability, enabling developers to
write programs that can run on different computer systems with minimal changes. Due to its
strong foundation, C continues to be an essential language in computer science and software
development.

Characteristics of C

1. It is a general purpose programming language.


2. It can run in any computer system.
3. It is efficient and fast due to its variety of data types and powerful operators
4. It contains the modern method of coding
5. Dynamic storage location is possible with C.

Advantages of C
1. It is structured language with functional flow control construct.
2. It is fast and efficient.
3. Any type of program can be developed in C.
4. It has ability to extend itself.

5
5. It is easy for debugging, testing and maintaining.

Disadvantages of C
1. C does not support object-oriented programming concepts.
2. C does not perform run-time type checking.
3. C has a complex syntax that can be challenging for beginners
4. It is still dependent on the underlying hardware and operating system.
5. C does not include built-in safety features.

BASIC STRUCTURE OF C PROGRAM


The basic structure of a C program is divided into 6 parts which makes it easy to read, modify,
document, and understand in a particular format. C program must follow the below-
mentioned outline in order to successfully compile and execute. Debugging is easier in a
well-structured C program.

There are 6 basic sections responsible for the proper execution of a program. Sections are
mentioned below:

1. Documentation section
2. Link section
3. Definition section
4. Global declaration section
5. Main () function section
6. Sub program section

The basic structure of C is illustrated as follows:

// Documentation

description: program to find sum

// Link

#include <stdio.h>

// Definition

#define X 20

// Global Declaration

6
int sum(int y);

// Main() Function

int main(void)

int y = 55;

printf("Sum: %d", sum(y));

return 0;

// Subprogram

int sum(int y)

return y + X;

C PRE-PROCESSOR AND HEADER FILES


The C preprocessor
Every program before compilation goes through a set of steps in the processing stage.
Preprocessing takes place in several logical steps. One of the major functions of C
preprocessor is Tokenizing. The final step of preprocessor is to link the resulting program
with necessary programs and library. Preprocessor directives follow the special syntax rules
and begin with the symbol # and do not require semicolon at the end. A set of commonly used
preprocessor directives are

1. #include – Used to include header files in a program.


2. #define – Used to define macros or constants.
3. #undef – Used to undefine a previously defined macro.
4. #ifdef – Checks if a macro is defined or not defined.
5. #else – Provides an alternative code block if the #if or #ifdef condition fails.
6. #endif –Specifies the end of #if.

7
7. #if – Used for conditional compilation based on a constant expression.
8. #ifndef–Tests whether the macro is not def.

`Header Files
In C programming, header files are files with a .h extension that contain function declarations,
macro definitions, and other reusable code components. They allow for better organization,
reusability, and modularity in a C program.One thing to be noted that the preprocessor directive
is #include and does not end with semicolon.

Header Files Meaning


<stdio.h> It is used to perform input and output operations using functions.
<conio.h> It is a non-standard (compiler-specific) C library that provides
functions for handling console input and output operations.
<string.h> It is used to perform various functionalities related to string
manipulation.
<math.h> It is used to perform mathematical operations.
<graphics.h> It is used to handle the graphic functions.
<time.h> It is used to perform functions related to date() and time().
<float.h> It is used to define floating-point limit (e.g., min/max values,
precision) for ensuring portability across systems.
<assert.h> It is used to debugging and error checking.

FUNDAMENTAL OF C
The C character sets

The set of alphabets, digits, white characters and other symbols used in any programming
language is called a character set. The character set used in c are:

1. Letters or alphabets
2. Digits
3. Special characters
4. White Spaces

8
Comment
Comment is a text or set of other characters, which is not compiled or executed from
the compiler. It is written in the program to give required information to other
programmers and the developers themselves. There are two types of comment writing
methods:

• Single line comment


• Multiple line comment

C Tokens

In C programming, tokens are the smallest units in a program that have meaningful
representations. Tokens are the building blocks of a C program, and they are recognized by
the C compiler to form valid expressions and statements.

There are five types of tokens which are

• Keywords
• Identifiers
• Constants
• String Constants
• Operators

Keywords

Keyword is a reserved word that is already stored by the c language developer. The reserved
word cannot be used as the identifiers. There 32 Keywords in C according to the ANSI
(American National Standard Institute) in c language. They are: void, printf, scanf, if, else,
while, getch, do, for, break, continue etc.

Identifiers

Every word used in C program to refer to the names of variables, functions, arrays, pointers
and symbolic constants are called identifiers. These are user defined names and consist of a
9
sequence of letters and digits, with a letter as a first character. Some valid identifiers are count,
total_sum, StudentAge, num1 etc.

Data types in C

A data type defines a set of values and that a variable can store a value along with a set of
operations that can be performed on that variable. They help the compiler allocate the correct
amount of memory and perform operations accordingly. C language data types can be classified
as,

• Primary data type


• Derived data type
• User defined data type

Primary data types

The fundamental data types are called primary data type of C language. They are also used to
build other data types.

(a) Integer data types


(b) Floating point
(c) Character type
(d) The void type

Derived data types

Derived data types are also known as secondary data types. These are collection of same or
different primary data types. The derived data types are:

(a) Array
(b) Structure
(c) Union
(d) Pointer etc

10
User defined data types

C language supports a feature where user can define an identifier that characterizes an existing
data type. This user defined data type identifier can later be used to declare variables. In short
its purpose is to redefine the name of a existing data type.

Constants and Variables


Constants

A value that does not change during the execution of the program is called constant. Such value
remains as it is until the written code is changed. Constant is sometimes called literal. Literal
is data items which never change its` value during entire run of program.

There are four types of constants. They are:

(a) Integer constant


(b) Floating point constant
(c) Character constant
(d) String constant

variables

A variable is an identifier that is used to represent a single data item. Variable may take different
value add different items during execution the data item must be assigned to the variable at
some point in the program. Example: total, Average, calculate_tax etc.

Escape Sequences
The escape sequence in C is the characters or the sequence of characters that can be used
inside the string literal. The purpose of the escape sequence is to represent the characters that
cannot be used normally using the keyboard.

The table below lists some common escape sequences in C language.

Escape sequence Use


\n Audible alert or beep sound
\a Backspace delete on character to the left

11
\b Move cursor to the Next or New line of the screen
\n Vertical tab
\t Horizontal tab
\’ Single quote
\” Double quote
\\ Backslash
\0 Null character

OPERATORS AND EXPRESSIONS


Operators

An operator is a symbol or sign that operates on single or multiple data items and tells the
computer to perform certain operations on one or more data items (operands). Operators are of
two different types which are binary and unary.

According to utility and action operators are divided into following:

• Arithmetic Operations
• Relational Operators
• Logical Operators
• Assignment Operators
• Increment and Decrement Operators
• Conditional Operators
• Bitwise Operators
• Special Operators

Expressions

An expression is combination of variables, constants, operators, parentheses and function call,


arranged as per the syntax of language. On evaluation, it produces new value. Some of the
examples of c expressions are given below

12
Algebraic expression C expression
a+b a+b
a×b a*b

(a+b)×c (a + b) * c

(ab/c) a*b/c
(a+b)(a+b) (a+b)*(a+b)
a≥b

a >= b

Statements
A statement is a command given to the computer that instructs the computer to take a
specific action such as display to the screen or collect input. A computer program is
made up of a series of statements.

There are two types of statement in C. They are:

a. Simple statement
b. Compound statement

INPUT AND OUTPUT(I/O) FUNCTIONS

A set of rules or routine defined for input and output of data are called I/O functions. These
functions are responsible for receiving data from different components like keyboard, file or
network. In C, I/O operations are implemented in the library file <stdio.h>. There are two ways
of performing I/O operation in C. They are
1. Formatted I/O
2. Unformatted I/O

Formatted I/O
Formatted I/O functions are used to read and display the data in desired format. Formatted IO
functions in C are:
a. The printf() function
b. The scanf() function

13
Unformatted I/O
Unformatted functions do not allow the user to read or display data in his customized format.
This library functions basically deal with a single character or a string of character. They are
also divided into two types.

a. Single character I/O functions


b. String I/O function

CONTROL STRUCTURE
A control structure in C is a fundamental programming concept that determines the flow of
execution of a program. It allows a program to make decisions, repeat actions, and jump to
different sections of code based on specific conditions. Control structure are divided into three
sub sections:

• Sequence statements
• Selection statements
• Looping statements

Sequence Statements
A sequence statement in C refers to the default flow of execution, where statements are
executed one after another in the order they appear in the program. This is the simplest control
structure, as no decision-making or looping is involved.

Syntax:

statement1;

statement2;

statement3;

...

Statement n;

14
Selection Statement
A selection statement is a programming construct that allows a program to choose between
different paths of execution based on a condition. It helps in decision-making by executing
specific blocks of code depending on whether a condition evaluates to true or false.

The if statement
An if statement is a selection control structure that allows a program to execute a block of code only if
a specified condition evaluates to true. If the condition is false, the block is skipped.

Syntax:

if (condition) {

statement;

The if else statement

The if-else statement is used to execute one block of code if a condition is true, and another
block if the condition is false.

Syntax:

if (condition) {

statement1;

} else {

Statement2;

Nested if statement

A nested if statement is an if statement placed inside another if statement. It allows checking multiple
conditions in a hierarchical manner, where an inner if executes only if the outer if condition is true.

15
Syntax:

if (condition1) {

if (condition_2) ;

statement-1;

else

statement-2;

else

statement-3;

The if-else-if ladder

The if-else-if ladder is a decision-making structure used when multiple conditions need to be
checked sequentially. If one condition is true, its corresponding block is executed, and the
remaining conditions are skipped.

Syntax:

if (condition1) {

statement-1;

} else if (condition2) {

Statement-2;

} else if (condition3) {

Statement-3;

} else {

16
Statement-n;

The switch statement

The switch statement is a selection control structure that allows a variable to be compared
with multiple possible values (cases). It is an alternative to multiple if-else-if statements when
checking for equality.

Syntax:

switch (expression) {

case value1:

statement-1;

break;

case value2:

statement-2;

break;

case valuen:

statement-n;

break;

default:

default_statemnet

17
REPETITIVE STATEMENTS(LOOPS)

A loop is a control structure in programming that allows a block of code to be executed


repeatedly until a specified condition is met. Loops help automate repetitive tasks and
improve code efficiency. There are two types of loops in C:

• The for loop


• The while loop
• The do while loop

The while loop

A while loop is a control structure that repeatedly executes a block of code as long as a
specified condition remains true. It is used when the number of iterations is not known in
advance and depends on a condition.

Syntax:

while (condition) {

statement body;

The for loop


A for loop is a control structure used to execute a block of code a fixed number of times. It
is ideal when the number of iterations is known beforehand.

Syntax:

for (initialization; condition; update) {

statement;

18
• The do while loop
A do-while loop is a control structure that executes a block of code at least once, and then repeatedly
executes it as long as a specified condition is true.

Syntax;

do {

statement

} while (condition);

JUMP STATEMENTS
In C, jump statements are used to jump from one part of the code to another altering the
normal flow of the program. They are used to transfer the program control to somewhere else
in the program. There are four types of jump statements in C. They are:

• The break statement


• The continue statement
• The return statement
• The goto statement

ARRAYS AND STRINGS


Introduction to arrays
Array is a collection of items of the same variable type that are stored at contiguous memory
locations. It is one of the most popular and simple data structures used in programming. In
an array, all the elements are stored in contiguous memory locations. So, if we initialize an
array, the elements will be allocated sequentially in memory.

TYPES OF ARRAY
One-Dimensional Arrays: A list of elements stored in a single row or column.

Multi-Dimensional Arrays:Arrays that have more than one dimension, such as 2D arrays
(matrices) or 3D arrays.

19
Declaring and Initializing Arrays

Declaration: datatype arrayName[size];

Example: int numbers[5];

Initialization: int numbers[5] = {1, 2, 3, 4, 5};

Accessing Array Elements

Each element in an array is accessed using an index, starting from 0.

Example: printf("%d", numbers[2]); // Output: 3

Advantages of Arrays

Efficient data storage.

Easy access to elements using an index.

Useful for implementing other data structures like stacks and queues.

Disadvantages of Arrays

Fixed size (cannot grow dynamically).

Insertion and deletion operations can be costly.

STRING

A string is a sequence of characters stored in an array of char type, terminated by a null


character \0.

Declaring and Initializing Strings

Declaration: char str[10];

Initialization:

20
char str[] = "Hello";

char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

String Input and Output

A) Using scanf() (reads until a space):

char name[20];
scanf("%s", name);

B) Using gets() (reads entire line, but unsafe):

gets(name);

C) Using fgets() (safe way to read strings):

fgets(name, sizeof(name), stdin);

Common String Functions (from <string.h>)


Function Purpose

strlen(str) Returns the length of the string.

strcpy(dest, src) Copies one string to another.

strcmp(str1, str2) Compares two strings.

strcat(dest, src) Concatenates two strings.

strchr(str, ch) Finds the first occurrence of a character.

strstr(str1, str2) Finds the first occurrence of a substring.

Differences Between Arrays and Strings

A) Arrays can store any data type, whereas strings specifically store characters.

B) Strings require a null character (\0) to indicate the end, whereas arrays do not.

21
C) String operations require special functions (strcmp, strcpy), whereas array operations
use simple indexing.

Applications of Arrays and Strings

A) Arrays are used in sorting, searching, and dynamic programming.


B) Strings are used in text processing, password validation, and data parsing

By understanding arrays and strings, programmers can efficiently manage and manipulate
data in their programs. Both play a crucial role in data structures and algorithms.

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

scanf("%f", &num);

22
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>

int main() {

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

24
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: ");

25
scanf("%d", &inch2);

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

26
9. Complete the following programs & discuss the outputs.
Program 1

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;

27
int x1 = 5;

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

printf(“i = %d\nj = %d”, i, j);

ANS:-

28
#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;

2. Add a program to calculate whether the given number is odd or even.


#include <stdio.h>

int main() {

29
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 {

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>

30
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() {

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;

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

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;

32
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) {

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%

33
>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) {

commission = salesAmount * 0.12;

} else {

printf("Invalid sales amount.\n");

return 1;

printf("The commission amount is: %.2f\n", commission);

return 0;

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

35
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++) {

printf("%d x %d = %d\n", number, i, number * i);

return 0;

36
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>

int main() {

int n, i;

printf("Enter the value of n: ");

scanf("%d", &n);

printf("Square series of first %d natural numbers:\n", n);

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

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

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

} else {

printf("Fibonacci Series: ");

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

printf("%d\t", term1);

nextTerm = term1 + term2;

term1 = term2;

term2 = nextTerm;

return 0;

39
}

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

return 0;

40
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() {

int i, j;

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

for (j = 1; j <= 5; j++) {

printf("%d\t", i * j); }

printf("\n"); }

return 0;

41
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 {

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

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

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

43
scanf("%f", &marks[i]);

total += marks[i];

average = total / 5;

printf("\nTotal Marks: %.2f\n", total);

printf("Average Marks: %.2f\n", average);

return 0;

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;

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

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;

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

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;

46
47
48
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

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;

49
6. Write a program that takes salary of 100 employees and print the salary of employees in
ascending order.
#include <stdio.h>

int main() {

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;

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

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

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

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

9. Write a program to calculate the sum of diagonal matrix with size 3 X 3.


#include <stdio.h>

int main() {

52
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>

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++){

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

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

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

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;

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

i++;

j++;

result[i] = '\0';

printf("Concatenated string: %s\n", result);

return 0;

}#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: ");

56
scanf("%s", str2);

// Copy first string into result

while (str1[i] != '\0') {

result[i] = str1[i];

i++;

// Copy second string into result

while (str2[j] != '\0') {

result[i] = str2[j];

i++;

j++;

result[i] = '\0'; // Null-terminate the concatenated string

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

57
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++;

} 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() {

58
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++) {

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

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

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

60
"apple",

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

8) Write a program to concatenate to given string without using built in function.


#include <stdio.h>

void concatenate(char str1[], char str2[], char result[]) {

int i = 0, j = 0;

while (str1[i] != '\0') {

result[i] = str1[i];

61
i++; }

while (str2[j] != '\0') {

result[i] = str2[j];

i++;

j++;

result[i] = '\0';

int main() {

char str1[100], str2[100], result[200];

printf("Enter first string: ");

gets(str1);

printf("Enter second string: ");

gets(str2);

concatenate(str1, str2, result);

printf("Concatenated string: %s\n", result);

return 0;

9) Write program for the following problems using built in function: strlen() and strcpy().
#include <stdio.h>

#include <string.h>

int main() {

char str1[100], str2[100], result[200];

printf("Enter first string: ");

gets(str1);

printf("Enter second string: ");

gets(str2);

strcat(str1, str2);

62
printf("Concatenated string: %s\n", str1);

printf("Length of concatenated string: %lu\n", strlen(str1));

printf("Reversed string: %s\n", strrev(str1));

return 0;

10) Write program for the following problems using built in function: strcmp() and strcpy().
#include <stdio.h>

#include <string.h>

int main() {

char str1[100], str2[100], result[200];

printf("Enter first string: ");

gets(str1);

printf("Enter second string: ");

gets(str2);

strcat(str1, str2);

printf("Concatenated string: %s\n", str1);

printf("Length of concatenated string: %lu\n", strlen(str1));

printf("Reversed string: %s\n", strrev(str1));

int comparison = strcmp(str1, str2);

if (comparison == 0)

printf("Strings are equal.\n");

else if (comparison > 0)

printf("First string is greater.\n");

else

printf("Second string is greater.\n");

strcpy(result, str1);

63
printf("Copied string: %s\n", result);

return 0;

Conclusion

In conclusion, this project has been a significant step in my journey of understanding and mastering
the C programming language. C is widely regarded as the mother of all modern programming
languages, and through this project, I have realized just how foundational it is to the field of
computer science and software development.

Throughout the course of this project, I explored and practiced various fundamental concepts of C
programming, including data types, operators, control structures (such as loops and conditional
statements), arrays, functions, pointers, structures, and file handling. Each of these components
plays a vital role in enabling efficient and structured programming, and gaining proficiency in them
has strengthened my ability to write clean, optimized, and logical code.

One of the most powerful features of C is its use of pointers, which allow direct memory access and
manipulation. Although initially challenging, working with pointers has deepened my understanding
of how memory management works in programming, especially in low-level system tasks. In
addition, learning about functions and modular programming has taught me how to divide complex
problems into smaller, manageable parts, which is a valuable skill in software development.

C's simplicity in structure, yet depth in capabilities, has made it clear why it is still used for
developing operating systems, embedded systems, compilers, and various performance-critical
applications. It offers both control and flexibility, making it an ideal choice for learning how a
computer truly operates behind the scenes.

Completing this project has not only enhanced my technical knowledge but also improved my logical
thinking, debugging skills, and patience. I have learned the importance of writing efficient code,
checking for errors, and thinking critically when designing algorithms. The hands-on experience has
given me more confidence to tackle more complex projects in the future, whether in C or other
programming languages that are built on similar principles.

Overall, this project has been a rewarding learning experience. It has laid a strong foundation for
further studies in computer science and programming, and I believe the knowledge gained from
working with C will continue to support my growth as a programmer. I am excited to explore more

64
advanced concepts and look forward to applying what I have learned in real-world scenarios and
future projects.

Reflection

Working on this project based on the C programming language has been an eye-opening and
transformative experience for me. At the beginning, I was both curious and intimidated by C,
especially because it is known for being closer to hardware and less forgiving than modern high-level
languages. However, as I delved deeper into the concepts and started writing actual code, I found
myself becoming more comfortable and confident with each step.

One of the biggest lessons I learned is the importance of understanding the fundamentals. Unlike
other languages that often hide the complexity, C forces you to deal with it directly. This was
challenging at times, especially when dealing with pointers, memory allocation, and file handling.
But those challenges also taught me patience, attention to detail, and how to think more logically
and analytically.

There were moments of frustration—errors that wouldn’t go away, bugs I couldn’t figure out—but
each time I solved one, the satisfaction made all the effort worth it. Debugging, which once felt like a
tiresome task, slowly became an essential and even enjoyable part of the learning process. It taught
me to be persistent and to think critically about what I write.

One particular highlight was learning how to break down problems into smaller, manageable parts
using functions. It helped me write clearer, more organized code, and made me realize how structure
and planning are key aspects of good programming—not just typing code.

Moreover, this project helped me understand the significance of low-level programming. By working
directly with memory and system-level functions, I gained a better appreciation for how software
actually interacts with hardware, which is something that many high-level languages abstract away.
This experience has sparked my interest in exploring topics like operating systems, embedded
systems, and even cybersecurity in the future.

In reflection, I can confidently say that this project has not only improved my programming skills but
also made me a more thoughtful and resourceful learner. It has reinforced the idea that learning to
code is not just about syntax—it’s about problem-solving, logic, creativity, and perseverance. I now
feel better prepared to take on more advanced languages and projects, and I’m excited to continue
building on the strong foundation that C has provided me.

65
66
67
68

You might also like