C Programming 2024
C Programming 2024
4.1 Introduction
Computer cannot do anything by itself. It requires proper instructions to do any sort
of tasks. A set of these instructions is called a program. A program is created to solve
a particular task and a group of these programs is called software. We have already
known that there are different types of programming language to write programs
such as High-Level Language, Assembly Language and Low Level Language. There
are several approaches of programming which include Structured, Unstructured,
Procedural, Modular, Object Oriented programming etc.
Sub-
Modules
C1 Sub-Modules C2 Sub-Modules C3
Provident Fund
Income Loan
Top-Down Hierarchical Model
In the above example, the main program is “Payroll” which is broken down into
several modules and sub-modules.
b) Single–Entry, Single–Exit Concept
One of the main features of structured programming is that its modules have only one
entry and exit points. It does not support Go To statement. This feature makes easier
to understand the flow of control of the program.
Single-Entry, Single-Exit concept can be achieved from the three fundamental
Control Structure:
i) Sequence Structure
ii) Selection (Branching) Structure
iii) Loop (Iterations) Structure
Entry
Entry
Tru False
Action e
Loop
Action Action 1 Action 2
Action
Exit Condition TrueAction 1
Exit False
Sequence Exit
Loop
Selection
210 Computer Science : Grade 10
Advantages of Structured Programming
Reduced Complexity
Easy to Code
Take less time
Easy to debug
Reuse of modules
Flow of control is clear
C Programming
Introduction
C Language is a high-level structured programming language. Normally this
language is used to develop system software. The C programming language was
developed by Dennis Ritchie at Bell Labs during the early 1970s. Quite
unpredictably it derived from a computer language named B and from an earlier
language BCPL. Initially designed as a system programming language under UNIX,
it expanded to have wide usage on many different systems.
Features of C Language
There are certain features of C language. They are:
a) Structured
C is a Structured Programming Language. Like QBASIC, we break down a program
in several small modules in C. The module is called function. It makes the
programmer easier to manage and debug the code
c) Fast
It is many time faster than BASIC. Due to the variety of data type and a list of
powerful operators, programs written in C are fast and efficient.
e) Extendable
C is also an Extendable Programming Language. We can develop functions in C
Language and can be added in library for the purpose of using in other programs.
Limitation of C Language
C has some limitation though it is a powerful programming language. Some of its
limitation are:
a) No Run Time Type Checking
b) Does not support object oriented programming
c) C doesn't have the feature of reusability of source code extensively
d) C language has only 32 Keywords
e) C provides no data protection
f) C compilers can only identify errors and are incapable of handling exceptions
(run-time errors).
Application of C Language
C was initially used for system development work, in particular, the programs that
make-up the operating system. It is mainly because it produces code that runs nearly
as fast as code written in assembly language. But C language is not limited to
develop system software.
a) Operating System
b) Language Compilers/Interface
c) Assemblers
d) Text Editors
e) Print Spoolers
f) Network Devices
212 Computer Science : Grade 10
g) Modern Programs
h) DBMS
i) Utilities etc.
Data Types in C
C Language supports two types of data:
a) Basic Data Types
b) Derived Data Types
Basic Data Types Derived Data Types
Int (Integer) Arrays
Char (Character) Pointers
Float Structure
Double Unions
Void Enums (Enumerations)
Sub-types of Integer
C supports the different types of integer. Different integer types also have different
ranges upto which they can store numbers. These ranges may vary from compiler to
compiler. Below is list of ranges along with the memory requirement and format
specifies on 32-bit gcc compiler.
In the above example, the intint a, b; is used to declare a and b as integer variables.
keyword
ii) float
It accepts Floating point values.
Digits of Format
Data Types Storage Size Range
Precision Specifier
float 4 Bytes 1.2E-38 to 3.4E+38 6 %f
float b;
b = 1.732;
iii) double
It also accepts the real numbers like float data type but its range is higher than float
data type.
iv) char
It holds only one character at a time.
void
void means “nothing” or “null value”. We cannot create any variable of void
type. For example,
void hello (void)
{
………………….
}
The above function “hello” does not require any parameter and also does not
return any value.
C Token
C tokens are the basic buildings blocks in C language which are constructed together
to write a C program. Each and every smallest individual unit in a C program are
known as C tokens.
do if static while
Keywords in C Language
C Character set
Character Set is a group of valid characters and symbols supported by a
programming language.
For example,
int and total are called identifiers.
Here, price
price;
Rules for naming Identifiers:
i) The Identifier must start with an alphabet or an under score (_).
ii) Identifier can be made from the combination of alphabets, digits and under score.
iii) No any C keyword can be used as an Identifier.
iv) Identifier must be unique and can be used for a single purpose only.
Format Specifier
The format specifier is used during input and output operation. It tells the compiler
what
unsigned int %u
int %d
char %c
float %f
double %lf
Variables in C
A variable is used to hold data within your program. A variable represents a location in
your computer's memory. Every variable has two parts, a name and a data type.
Variable declaration
A variable declaration states the types of the variable, variable name and if necessary
initializes the variable to a given value.
For e.g.
int count;int number_of_students = 30;
Now, let’s look a whole program in C:
C Program
There are four steps of writing program in C. Each step has its own importance and
must be completed stepwise.
Step 1:
At first, the program is written in C Compiler editor. It is called source code. This
source code can be saved as a program file and its extension is .C. This source code
can be edited at any time.
Step 3:
The third step is called linking process. In this process, the required libraries are
linked to the program. Libraries prepare an appropriate environment to execute the C
program.
Step 4:
After the linking process, an executable file is created with the extension .exe. This
executable file can be run in any other computer without compiler.
Structure of C Program
Pre-Processor directives
Global Declarations
main ()
{
Local declarations
Program Statements
Parts of a C Program
i) Pre-processor directives
As part of compilation, the C compiler runs a program called the C pre-processor.
The preprocessor is able to add and remove code from your source file. One of the
major functions of C preprocessor is Tokenizing. The final step of the preprocessor is
to link the resulting program with necessary programs and library.
iv) { } Parenthesis
In C language, each function is defined inside parenthesis ({ }).
Output Function in C
Output function is used to show the calculated result or output on the screen. In C
language, printf() is one of the output function defined in <stdio.h> header file.
printf() function
In C Language, printf() function is used to print the valued on the screen. It is defined
in
<stdio.h> header file. So, the header file <stdio.h> must be added to use this function.
Syntax:
printf(“format string”,argument list);
format string is the combination of format identifier, escape sequence or string constant.
Escape Sequence
Escape Sequence is a pair of character that is used with printf() function to display
non-printing character or a special character on the screen.
\n - new line
\t - tab
\b - backspace
\o - null character
\? - question mark
\\ - slash
\' - single quote
\” - double quote
String Constant
String constant is a message to be displayed along with the other values stored in
variables. It is enclosed within double quotation (" ").
Argument List
It is a list of variables to be used in printf ( ) function.
For example,
#include
<stdio.h>
#include
<conio.h> void
main()
{
int
a=5,b=10;
clrscr();
In the above program,
Input Function in C
Input function is used to ask data for processing. In C language, scanf() is one of the
input function defined in <stdio.h> header file.
scanf() Function
scanf() is one of the most important functions of C Program. This function is also
defined in the header file <stdio.h> and used to ask value from keyboard.
Syntax:
scanf("format string", argument list);
format string is the combination of format identifier, escape sequence or string constant.
#include
Note: You can see the use of getch() function in every example of C program in this
book. The purpose of using this function in the sample program is to let the user to
<conio.h>
read output on the screen. If such type of function is not used, the output screen will
#include
be<stdio.h>
closed immediately
void after showing the output and returns to the coding window. In
the above program, after showing the output by printf() function, getch() asks a
main()
character and get chance to see the output until the character is not typed.
{
Arithmetic Calculations in C Program
char ch;
There are basically four types of arithmetic operations:
clrscr();
i) Addition
ch=getch(
ii) Subtraction
);
iii) Multiply
iv) Division
To perform the above arithmetic operations, C language supports the below arithmetic
operators:
C Expression
An expression consists of at least one operand with one or more operators. It is a legal
combination of symbols that represents a value.
For example,
C=A+B
#include
<conio.h> void
main()
clrscr();
int l,b,h,a,v;
scanf ("%d%d
%d",&l,&b,&h); a=l*b;
v=l*b*h; printf("\nArea=
nVolume=%d",v); getch();
}
Computer Science : Grade 10 229
Example of Arithmetic Calculation #2
/* Calculate total
marks and percentage
*/ #include <stdio.h>
#include <conio.h>
void main()
{
clrscr(); /* Calculate total marks and percentage */
int
e,m,c,t;
float p;
/* … */ is also used to write comment in C Lang
printf("Marks in English, Math comments in one or more lines.
& Computer ");
scanf("%d%d%d",&e,&m,&c);
t=e+m+c; Output:
p=t/3; //Full mark for all subject
is
100
printf("\nTotal Marks = %d
",t); printf("\nPercentage = %f
",p); getch();
Logical Calculation in C
The calculation that is done based on one or more conditions is called logical
calculations. Several relational or comparison operators are used to check the
condition which gives True or False as a calculated result.
Relational Operators in C
Relational Operator checks the relationship between two operands and returns either
1 (True) or 0 (False). In C programming, relational operators can be used to take
decisions and provide condition in looping statements.
Control structures in C
C is a structured programming language. Control structures form the basic entities of
a “structured programming language“. C supports three types of basic control
structures, which are used to alter the flow of execution of the program.
False Statement 1
Statement 1
Flowchart of a
selection structured program
c) Looping Structure
Looping is the process of repeating the execution of a statement or a block of statements
guided by a condition. A loop is terminated when the given condition is satisfied.
Start
n=1
Print"Nepal"
n<=5?
Stop
Flowchart of a
looping structured
program
Example:
#include
Output:
<stdio.h>
#include
<conio.h> void
main() Science : Grade 10
Computer 233
{
int a;
printf ("Type your marks
"); scanf ("%d",&a);
if(a>=40)
{
printf ("You are Pass");
printf ("\nCongratulations!!!");
}
if … else statement
The previous if statement executes the statement only if the given condition is True.
This statement is used to check one or more condition and execute the condition
either the condition is True or False.
Syntax :
if (condition)
{
statements
…………..
}
else
{
statements
…………..
}
Example:
#include
<stdio.h>
#include
<conio.h> void
main()
{
int a;
Output:
clrscr(
);
printf ("Type your marks
"); scanf ("%d",&a);
if(a>=40)
{
printf ("You are
Pass");
}
else
{
#include
<stdio.h>
#include
<conio.h> void
Output:
main()
{
int
num=1;
clrscr();
while (num<=10)
{
printf ("%d
",num); num++;
#include
<stdio.h>
#include
<conio.h> void
main()
{
Output:
int
num=1;
clrscr();
do
{
printf ("%d
",num); num++;
#include
<stdio.h>
#include
<conio.h> void
main()
Output:
{
clrscr(
); int
c;
for (c=1;c<=10;c++)
{
printf ("%d ",c);
statement
……………….}
Example:
Use of Loop – Example #1
//Fibonocci series 1 2 3 5 8
13 ... #include <stdio.h>
#include
<conio.h> void
main()
{
clrscr();
int
a=1,b=2,c,n=1;
Output:
do
{
printf ("%d
",a); c=a+b;
a=
b;
b=
c;
Exercises
1. Answer the following questions.
a) What is structured programming? Give any four examples of structured
programming language.
b) Write the advantages of structured programming.
c) Write the features of C language.
d) List the data types supported by ‘C’ language.
e) Explain the structure of C program.
f) Differentiate between int and float data type in C.
g) Explain the different looping statements used in C.
b) //Series 100 95 90 85 5
#include <stdio.h>
#include <conio.h>
int main()
{
cls;
int n=100;
do
{
scanf("%d ",n);
n=n-5;
}while(n>=5)
getch();
}
c) //Reverse of an integer
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
int n,r,d;
printf("Type an integer ");
1.
Lab Activities
Write the below program in C Language.
a) Write a program that asks any two numbers and find their sum.
b) Write a program that asks Principal Amount, Rate and Time and
calculates Simple Interest.
c) Write a program that asks length & breadth of a room and calculates its
area and perimeter.
d) Write a program that asks any two numbers and displays the smaller one.
e) Write a program to check whether the supplied number is divisible by 7
or not.
f) Write a program that asks your marks in Computer Science and checks
whether you are pass or fail if the pass mark is 40.
g) Write down C program to generate the below series:
i) 5, 10, 15, ….. 50
ii) 5, 10, 15, ….. up to 50th terms
iii) 1,2,4,8,16, …. up to 10th terms
iv) 999, 728, 511, …. up to 10th terms
v) 1,2,3,5,8,13,21, …. up to 10th terms
Technical
StructuredTerms
Programming : A programming approach to breakdown main program into
smaller logical modules
Top-Down Design : Process of breaking down the complex problem into
simpler ones
Variable : A memory location used to hold data during run-time Format
Specifier : Tells the type of data stored in a variable during input and
output operations
Identifier : The name given to any variable, function etc.
C Character Set : A group of valid characters and symbols supported by C
language
Logical Calculation : A type of calculation which is performed based on one
or more conditions