0% found this document useful (0 votes)
4 views42 pages

C Programming 2024

The document provides an overview of structured programming in C, emphasizing its top-down approach and modular design, which enhances code efficiency and reusability. It details the features, advantages, limitations, and applications of the C programming language, along with its data types, tokens, and structure of a C program. Additionally, it explains the process of writing, compiling, and executing C programs, including the use of header files for library functions.

Uploaded by

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

C Programming 2024

The document provides an overview of structured programming in C, emphasizing its top-down approach and modular design, which enhances code efficiency and reusability. It details the features, advantages, limitations, and applications of the C programming language, along with its data types, tokens, and structure of a C program. Additionally, it explains the process of writing, compiling, and executing C programs, including the use of header files for library functions.

Uploaded by

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

Structured Programing in C

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.

4.2 Structured Programming


Structured programming (sometimes known as modular programming) follows a
top-down approach, in which programmer separates the overall program structure
into different subsections. A defined function or set of similar functions is coded in a
separate module or sub module, which means that code can be loaded into memory
more efficiently and that modules can be reused in other programs. After a module
has been tested individually, it is then integrated with other modules into the overall
program structure. Some examples of structured programming languages are Pascal,
C, PLII, Ada etc.

4.3 Features of Structured Programming:


a) Top-Down Design
The top-down approach is the process of breaking down the complex problem into
simpler ones. In programming also, top-down approach is the stepwise process of
breaking down large and complex program into several simpler modules to organize
and code in an efficient way.

Computer Science : Grade 10 209


Payroll Programme

Modules A Modules B Modules C ModulesD


Read Write
Gross Deductio

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

b) Middle Level Language


It combines elements of a high level language with some features of assembler. As a
middle level language, C language manipulates memory address.

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.

Computer Science : Grade 10 211


d) Case Sensitive
C is a case-sensitive programming language. It understands the capital alphabets and
small alphabets as different values. For example, “Computer” and “COMPUTER”
are different values for C Language.

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)

Basic Data Types of C Language


i) int (Integer)
An Integer is a whole number either positive, negative or zero but no decimal values.
For example, 0, -5, 10

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.

Data Types Storage Size Range Format Specifier


short int 2 Bytes -32,768 to 32,767 %hd
unsigned short int 2 Bytes 0 to 65,535 %hu
unsigned int 4 Bytes 0 to 4,294,967,295 %u
int 4 Bytes -2,147,483,648 to 2,147,483,647 %d

Computer Science : Grade 10 213


long int 4 Bytes -2,147,483,648 to 2,147,483,647 %ld
unsigned long int 4 Bytes 0 to 4,294,967,295 %lu

Declaring an integer variable

In the above example, the intint a, b; is used to declare a and b as integer variables.
keyword

Likewise, we can declare integer variable


unsigned int d; in this way as well.
Here, the type of the variable is declared as unsigned int. It takes 4 bytes of memory
and can hold the integers between 0 and 4,294,967,295.

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

Declaring float type variable

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.

Storage Digits of Format


Data Types Range
Size Precision Specifier
double 8 Bytes 2.3E-308 to 1.7E+308 15 %fd

214 Computer Science : Grade 10


Declaring double type variable
double x;
x = 67823.34456;

iv) char
It holds only one character at a time.

Data Types Storage Size Format Specifier


char 1 Byte %c

Declaring char type variable


char m;

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.

C tokens are of six types. They are:

a) Keywords (eg: int, while),


b) Identifiers (eg: main, total),
Computer Science : Grade 10 215
c) Constants (eg: 10, 20),
d) Strings (eg: “total”, “hello”),
e) Special symbols (eg: (), {}),
f) Operators (eg: +, /,-,*)

C keywords (reserved word)


Keyboardis a set of special words which are already defined for some tasks. C has
only a set of 32 keywords, which have their predefined meaning and cannot be used
as a variable name. These words are also known as “reserved words”.

auto double int struct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned

Keywords in C Language
C Character set
Character Set is a group of valid characters and symbols supported by a
programming language.

A character denotes any alphabet, digit or special symbol used to represent


information. The below table shows the valid alphabets, numbers and special
symbols supported by C language.

216 Computer Science : Grade 10


Alphabets
Uppercase : A,B,C…......................................X, Y, Z
Lowercase : a,b,c…..........................................x,y,z
Digits:
0, 1, 2, 3, 4 …………. 9
Special characters
, < > . _ -
( ) ; $ : \
% [ ] # ? ~
' & { } " +
^ ! * / |

Special Characters in C Language


Identifiers
Identifiers are the names given to the entities such as variables, functions, arrays
structures and unions.

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

Computer Science : Grade 10 217


type of data is stored in a variable during the input and output operation such as taking
data from keyboard and display data on the screen. Some examples are %c, %d, %f,
etc.

Data Type Format Specifier


short int %hd

unsigned short int %hu

unsigned int %u

int %d

long int %ld

unsigned long int %lu

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:

218 Computer Science : Grade 10


/* This is my C program
*/ #include <stdio.h>
#include <conio.h> The above C program asks any two
void main() numbers from the keyboard and
{ displays their sum. In this program,
int a,b,c; three variables a,b and c are used and
printf ("Enter the first number their types are declared as integer
"); scanf("%d",&a); (int). Unlike QBASIC, we need to
printf ("Enter the second number declare the type and name of the
"); scanf("%d",&b); variables in the beginning of the
program.
c=a+b;
printf("Sum =
%d",c); getch();
}

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.

Computer Science : Grade 10 219


Step 2:
The second step is to compile the source code. During compilation, syntax error is
checked and removed from the source code. After compiling, the source code is
changed into binary format and creates a new file with the extension .obj. It is called
object program which cannot be edited.

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

Calling user defined for (optional)


}
user defined functions
function 1
function 2 [Optional]
function 3

220 Computer Science : Grade 10


Example of a C Program
/* To find the product of any two numbers */ Comments
#include <stdio.h>
#include <conio.h> Pre-processor directives
void main()
{
int a,b,c;
clrscr();
printf ("Type first number
"); scanf ("%d",&a);
printf ("Type second number
"); scanf ("%d",&b); main() function
c=a*b;
printf ("Product = %d",c);
getch();
}
Note: clrscr() function is similar to CLS statement in QBASIC. It erases the
previous contents of the output screen. The clrscr() function is defined in the header
file <conio.h>

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.

While writing program in C, we need to include different header files in the


beginning. In the above program, printf ( ) and scanf ( ) functions are used for output
and input operation. These functions are defined in the header file <stdio.h>. So, this
header file is included at the beginning of program which contains the code of
printf() and scanf() functions. All the code of header files will be added to the
program during compilation.

Computer Science : Grade 10 221


C Header Files
Different library functions are used to do different tasks in C language. For example,
we use scanf() function to ask data from keyboard. Each function is defined in a
special type of file. These files are called Header File and have extension .h. These
header files must be included using #include directive otherwise the compiler doesn’t
understand the library function we use and gives an error message. Here is the list of
some commonly used Header file and their purposes:

Header Files Purpose Functions Declared


stdio.h Used for standard input and printf(), scanf(), getchar(), putchar(),
output (I/O) operations. gets(), puts(), getc(), putc(), fopen,
fclose(), feof()
conio.h Contains declaration for clrscr(), exit()
console I/O functions.
ctype.h Used for character-handling or isupper(), is lower, isalpha()
testing characters.

math.h Declares mathematical pow(), squr(), cos(), tan(), sin(),


functions and macros. log()
stdlib.h Used for number conversions, rand(), srand()
storage allocations.

string.h Used for manipulating strings. strlen(), strcpy(), strcmp(), strcat(),


strlwr(), strupr(), strrev()

ii) Global Directives


In this section of C program, Global variables and User-defined function are declared.

iii) main () function


C program must start with main() function. This is the entry point of the program.

iv) { } Parenthesis
In C language, each function is defined inside parenthesis ({ }).

222 Computer Science : Grade 10


v) User-defined function
As in QBASIC, we can create different user-defined function as per our requirements.

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.

Some Examples of Escape Sequence:

\n - new line
\t - tab
\b - backspace
\o - null character
\? - question mark
\\ - slash
\' - single quote
\” - double quote

Computer Science : Grade 10 223


Format Identifier
We need to include format identifier to tell the data type in the area of format string of
printf() function. For example,

Variable Type Format Identifier


char %c
int %d
long int %ld
float %f

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,

\n prints from a new line

224 Computer Science : Grade 10


"Value of a and b are" → String Constant
%d → Format Identifier of int data type
a,b → Arugement List (Variables)
The output of the above program:

Note: Each C statement must be terminated by a semicolon(;).

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.

Computer Science : Grade 10 225


For example
In#include
the above program,
<stdio.h>
scanf ("%d",&a);
#include
%d → Format Identifier of int data type
<conio.h> void
&a → & – address operator, a – variable
main()
{ function in the above program asks an integer form keyboard and stores in the
This
variableint
‘a’.a;
clrscr(of the above program
The output
);
printf ("Type an integer
"); scanf ("%d",&a);
getch() function
getch() function is another input function of C language. This function is defined in the
header file <conio.h>. This function is used to ask any one character from keyboard.

226 Computer Science : Grade 10


For example,

#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:

List of Arithmetic Operators in C


If A=10 and B=20,

Computer Science : Grade 10 227


Operator Description Example Result
+ (Plus) - Addition Adds two operands A+B 30
- (Minus) – Subtraction Subtracts second operand from A-B -10
first operand
* (Asterisk) – Multiply two operands A*B 200
Multiplication
/ (Slash) – Division Divides first operand by second B/A 2
operand
% (Percentage Symbol) – Provides remainder when first B%A 0
Modulus Division operand is divided by second
operand
++ (Plus Plus) – Increment Increases the value of operand A++ 11
Operator by 1
-- ( M i n u s M i n u s ) – Decreases the value of operand B-- 19
Decrement Operator by 1

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

228 Computer Science : Grade 10


Example of Arithmetic Calculation #1

// Calculate area and volume of a

room #include <stdio.h>

#include

<conio.h> void

main()

clrscr();

int l,b,h,a,v;

printf ("Type length, breadth


and height ");

scanf ("%d%d

%d",&l,&b,&h); a=l*b;

v=l*b*h; printf("\nArea=

%d",a); printf ("\

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.

230 Computer Science : Grade 10


List of Relational Operators in C

If A=5 and B=10,

Operator Description Example Result


== Equal to A==B 0
> Greater than A>B 0
< Less than A<B 1
!= Not equal to A!=B 1
>= Greater than or equal to A>=B 0
<= Less than or equal to A<=B 1

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.

a) Sequence structure (straight line paths)


b) Selection structure (one or many branches)
Statement 1
c) Loop structure (repetition of a set of activities)

a) Sequential Structure Statement 2

In sequential structure, the statements are executed


one after another sequentially from top to bottom Statement 3
without changing the flow of program.
Flowchart of a
sequential structured program
b) Selection Structure
It is also called branching structure. In this structure, the control of the program is
transferred from one part of the program to another on the basis of specified
condition or without condition.

Computer Science : Grade 10 231


True
Condition

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

232 Computer Science : Grade 10


if statement
if statement is used to test one or more condition and execute statement(s) if the given
condition is True.
Syntax:
if (condition)
{
statements
…………………
}
If the condition mentioned in the syntax is True, then the statements written inside the
parenthesis { } will be executed.

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
{

234 Computer Science : Grade 10


In the above program, if the value of a is greater than or equal to 40 then the message
“You are Pass” will be printed, otherwise, the program shows “You are Fail”.

Example of Logical Calculation


#1
//Check ODD or
EVEN #include
<stdio.h> #include
<conio.h> void
main()
{
clrscr(
); int
n;
printf("Type any number
Output:
"); scanf("%d",&n);
if (n%2==0)
{
printf ("\nIt is even.");
}else{
printf ("\nIt is odd.");

Computer Science : Grade 10 235


Example of Logical Calculation
#2
/* Find the GREATER number
*/ #include <stdio.h>
#include
<conio.h> int
main()
{
clrscr(
); int
a,b;
printf("Type first number
"); scanf("%d",&a);
printf("Type second
number Output:
");
scanf("%d",&b
); if(a>b)
{
printf("Greater
number
is %d ",a);
}else{
printf("Greater
number

236 Computer Science : Grade 10


Looping in C
The looping statement allows a set of instructions to be performed repeatedly until a
certain condition is fulfilled. The looping statements are also called iteration
statements. Looping statements in C
C provides three kinds of loops:
i) while loop
ii) do loop
iii) for loop
i) while loop
The while loop continues executing a block of code till the given condition is true. The
loop will be terminated when the condition becomes false.
Syntax:
initial variable declaration
while (condition)
{
statements
………………
// increment of counter
}
Example:

#include
<stdio.h>
#include
<conio.h> void
Output:
main()
{
int
num=1;
clrscr();
while (num<=10)
{
printf ("%d
",num); num++;

Computer Science : Grade 10 237


In the above program, the value of variable (counter) num is initialized as 1. The
loop continues till the values of num is less than or equal to 10. In each iteration
(loop), the current value of num is printed and the value of num is increased by 1.
When the value of num becomes 11, the condition becomes false and the loop will be
terminated.
ii) do loop
The do loop also executes a block of code as long as a condition is satisfied. The
difference between a "do" loop and a "while" loop is that the while loop tests its
condition before the execution of loop; the "do" loop tests its condition after the
execution of loop. Syntax:
initial value declaration
do
{
statement
………………
// increment of counter
} while (condition);

#include
<stdio.h>
#include
<conio.h> void
main()
{
Output:
int
num=1;
clrscr();
do
{
printf ("%d
",num); num++;

238 Computer Science : Grade 10


Difference between while/do loop
iii) for loop
The for loop can execute a block of code for a fixed number of repetitions. It is easy
to use and defined in a single statement.

while loop do loop


Test expression (condition) is checked at Code is executed at first then the
first. condition
is checked.
It is also called entry-controlled loop It is also called exit-controlled loop
elgG5. elgG5
n=1 n=1
while (n>10) do
{ {
printf ("%d",n); printf ("%d",n);
n++; n++;
} } while (n>10);
Output: Nothing Output: 1

#include
<stdio.h>
#include
<conio.h> void
main()
Output:
{
clrscr(
); int
c;
for (c=1;c<=10;c++)
{
printf ("%d ",c);

Computer Science : Grade 10 239


Syntax:
for (intialization, condition, increment/decrement )

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;

240 Computer Science : Grade 10


Use of Loop – Example #2
//Series 1 2 4 8 ... upto 10th
terms #include <stdio.h>
#include
<conio.h> void
main()
Output:
{
clrscr();
int
n=1,c;
for (c=1;c<=10;c++)
{
printf ("%d
",n); n=n*2;
}

Computer Science : Grade 10 241


Use of Loop – Example #3
//Check PRIME or
COMPOSITE #include
<stdio.h>
#include
Output:
<conio.h> void
main()
{
clrscr();
int
n,i,c=0;
printf ("Type any number
"); scanf ("%d",&n);
for (i=2;i<=n-1;i++)
{
if(n%i==0) c++;
}
if (c==0)
printf("The number
is
prime. ");
else
printf("The number is

242 Computer Science : Grade 10


Use of Loop – Example #4
//Sum of individual
digits #include
<stdio.h> #include
<conio.h>
void main()
{
int
n,r,s=0;
clrscr();
printf("Type any one integer
"); scanf("%d",&n); Output:
while (n!=0)
{
r=n%10;
s=s+r;
n=n/1
0;
}
printf("Sum of individual

Computer Science : Grade 10 243


Exercises
 C is a high-level Structured Programming Language.
 C has only 32 keywords.
 C is a case-sensitive programming language.
 C language is used to develop Operating System, Language
Compilers/Interface, Text Editors, Network Devices, Modern Programs,
DBMS, Utilities etc.
 C supports two data types: Basic and Derived
 Basic data type includes int, char, float etc.
 Like QBASIC, C program is also written using different control statements
such as if statement, looping statement.
 C provides three looping statements: do, while and for.

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.

2. Fill in the blanks.


a) Structured Programming is also known as ……………. .
b) Single-Entry, Single-Exit concept can be achieved from the …………….
fundamental Control Structure.
c) To run any program, we need memory location to store data which is called

244 Computer Science : Grade 10


……….....
d)is the name given to any variable, function etc.
e) A group of valid characters and symbols supported by C language is called
……………. .
f) The printf() function is defined in.......................header file.
g) There are basically......................types of arithmetic operations.
h) C language has......................keywords.

3. State whether the following statements are 'True' or 'False'.


a) Top-Down Design is the process of breaking down the complex problem
into simpler ones.
b) Format specifier tells the type of data stored in a variable during input
and output operations.
c) C is not a case-sensitive language.
d) C Language has all the features of Object Oriented Programming
Language such as Classes, Objects, Inheritance etc.
e) C language is far closer to the hardware than most other languages.
f) We use printf() function to ask data from keyboard.
g) C is a Structured Programming Language.

4. Re-Write the below programs after correcting the bugs.


a) // Calculate sum of any three numbers
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
int a,b,c,s;
printf ("Type any three numbers ");

Computer Science : Grade 10 245


scanf ("%f%f%f%f",a,b,c);
s=a+b+c printf("\
nSum=",&s);
getch();
}

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

246 Computer Science : Grade 10


scanf("%d",&n);
while(n<>0)
{
d=n mod 10;
r=r*10+d;
n=n/10;
}
printf("\nReversed integer = %d ",d);
}

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

Computer Science : Grade 10 247


vi) 1 22 333
4444
55555
h) Write a program that asks any one integer and calculates the sum of its
individual digits.
i) Write a program that asks any one integer and displays its reverse.
j) Write a program that asks any one integer and checks whether it is an
Armstrong number or not.
k) Write a program that asks any one integer and calculates its factorial.
l) Write a program that asks any one integer and displays its factors.
m) Write a program to check whether the supplied number is prime or composite.

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

You might also like