INPUT “DO YOU WANT TO RETRY?”; CH$
IF UCASE$(CH$)= “Y” THEN GOTO TOP
CLOSE #1
END
Program 21
WAP to delete unnecessary record from the data file named “STUDENT.DAT” according
to the input name and display message if data are not found. The data file contains fields
for student’s name, address and class.
OPEN “STUDENT.DAT” FOR INPUT AS #1
OPEN “TEMP.DAT” FOR OUTPUT AS #2
TOP:
CLS
INPUT “ENTER NAME TO DELETE DATA”; D$
FLAG = 0
WHILE NOT EOF(1)
INPUT #1,N$,A$,C
IF UCASE$(N$) = UCASE$(D$) THEN
PRINT “DATA DELETED”
FLAG = 1
ELSE
WRITE #2,N$,A$,C
END IF
WEND
IF FLAG = 0 THEN PRINT “DATA NOT FOUND”
INPUT “DO YOU WANT TO DELETE ANOTHER DATA?”;CH$
IF UCASE$(CH$) = “Y” THEN GOTO TOP
CLOSE
KILL “STUDENT.DAT”
NAME “TEMP.DAT” AS “STUDENT.DAT”
END
Innovative Task
Write any five file handling programming in A4 size paper and submit to your
teacher as your project work.
New Gateway to Computer Science Book -10 251
Assignment
1. Answer the following questions.
a. What is file in file handling?
b. Define data file and program file.
c. What are the types of file? Explain them in short.
d. What are the different modes to open a sequential data file?
e. Define output, input and append mode in short.
f. What is the EOF() function?
g. What are the differences between WRITE# and PRINT#?
h. Write down the function of the following statements.
i. OPEN statement ii. PRINT # statement iii. INPUT # statement
iv. INPUT $ () Statement v. NAME AS statement vi. KILL statement
vii. MKDIR statement viii. CHDIR statement ix. RMDIR statement
2. Debug the given program.
a. REM COPY DATA OF “SCR. INF” TO “DEST.INF”
OPEN .SCR.INF. FOR INPUT AS#1
OPEN .DEST.INF. FOR OUTPUT AS #2
WHILE NOT EF( )
INPUT#3, NM$, RN, AGE
WRITE#1, NM$, RN, AGE CLOSE #3, #2
END
COLSE #1, #2
b. REM to input the name of a person, post and salary and store them in a sequential
data file “SAL.DAT”.
OPEN “SAL.DAT” FOR OUTPUT AS #1
DO
INPUT “ENTER THE NAME ” ; N
INPUT “ENTER THE POST” ; P$
INPUT “ENTER THE SALARY” ; S$
PRINT #1 , N$,P,S$
INPUT “DO YOU WANT TO STORE MORE RECORDS ? (Y/N)” ; CH$
LOOP WHILE UCASE(C$)=”Y”
END
CLOSE#1
252 New Gateway to Computer Science Book -10
c. REM to display those record whose salary is greater than 15000 from the data file
“STAFF.DAT”
OPEN “STAFF.DAT” FOR INPUT AS #1
INPUT #1,N$, ADD$, A, S
IF S>=15000 THEN
DO WHILE NOT (EOF)
ENDIF
PR INT N$,ADD$,A,S
NEXT
CLOSE #6
END
3. Write a Qbasic program for the followings.
a. Write a program to store Roll no., Name, Class and Address of any five students.
b. Create a data file to store the records of few employees having name, address, post,
gender and salary fields.
c. A Sequential data file called ‘Marks. dat’ contains NAME, AGE, CITY and
TELEPHONE field. Write a program to display all the contents of that data file.
d. Create a sequential data file “std.dat” to store name and marks obtain in English,
Maths and Science for a few students.
e. A sequential data file called ‘marks.dat’ has stored data under the field heading
Roll No., Name, English, Nepali and Maths. Write a program to display all the
information of those students whose marks in Nepali is more than 50.
f. A Data file “Salary. Dat” contains the information of employee regarding their
Name, Post and Salary. Write a program to display all the information of employee
whose salary is greater than 15,000 and less than 40,000.
g. A sequential data file “Staff.dat” contains the name, address, post and salary of
employees. Write a program to read and display all the records stored in the data
file.
h. Write a program to store Member’s Name, Telephone Number, Age and E-mail ID
in sequential data file MEMBER.TXT. The program should continue or terminate
according to user’s choice.
New Gateway to Computer Science Book -10 253
i. Write a program to search and display only those records whose percentage is
more than 60% from the data file .RESULT.DAT which contains Student’s Symbol
number, Date of birth, Total Marks, Percentage and Division.
j. Write a program to display only those records whose price is 300 or more from a
sequentialdatafile“library.dat” thatcontainsbookname,publisher’sname,author’s
name and price.
k. A data file “STAFF. DAT” has stored records of few employees with email ID, First
name, Last name, post and salary. Write a program to display all the records of the
employees whose salary is more than 40,000.
l. A data file “LIB. TXT” consists of Book’s name, Author’s name and price of books.
Write a program to count and display the total number of records present in the
file.
m. A data file “ENFO INF” has numerous records with name, address and telephone
numbers in each record. Write a program to scan all the records form that file and
display only the records with address “DHADING”.
n. A sequential data file named “Nabil.txt” contains record of clients of a bank
including depositor’s name, deposited amount, time and rate of interest. WAP to
display detail of all depositors including simple interest.
254 New Gateway to Computer Science Book -10
Lesson
11 Programming in C
Learning Outcomes
At the end of this lesson, students will be able to:
identify C programming with its advantages and disadvantages.
tell the features of C programming.
explain the elements of C programming.
define constant, variable, and statements in C programming.
explain the C programming operators.
tell the data types and sizes.
list out the input and output functions used in C.
write various C programs.
C programming is a machine-independent general-purpose structured programming
language which is very popular and flexible. It was originally developed by Dennis
Ritchie for the UNIX operating system. It was first implemented on the Digital Equipment
Corporation PDP-11 computer in 1972. It is a powerful programming language which is
strongly associated with the UNIX operating system. Even most of the UNIX operating
system is coded in ‘C’. Initially ‘C’ programming was limited to the UNIX operating
system, but as it started spreading around the world, it became commercial, and many
compilers were released for cross-platform systems. C programming runs under a variety
of operating systems and hardware platforms, these days.
C programming is also called a structured programming language because it is used
to solve a large problem, C programming language divides the problem into smaller
modules called functions or procedures each of which handles a particular responsibility.
The program which solves the entire problem is a collection of such functions.
Advantages
It is simple and easy to understand and implement.
It is a building block for many other programming languages.
It is flexible which helps us to run code on any machine without making any changes.
It has many built-in functions that are helpful when building a program in C.
It is a structured programming language where complex problems are divided into
smaller blocks or functions.
New Gateway to Computer Science Book -10 255
Disadvantages
In the C programming language, the errors or the bugs aren’t detected after each line
of code.
It does not have concept of OOPs so that next programming language C++ was
developed.
There is no runtime checking in C language.
As the program extends it is very difficult to fix the bugs.
Structured Programming
Structured programming is also known as modular programming. It is a subset of
procedural programming that applies a logical structure on the program being written
to make it more efficient and easier to understand and modify. Structured programming
frequently employs a top-down design model, in which developers map out the overall
program structure into separate subsections. A defined function or a 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.
Features of C Programming
C programming is a simple language in the sense that it provides a structured approach,
library functions, data types, etc.
It is a machine independent language so it can be executed on different machines with
some machine specific changes.
It is a structured programming language.
It has lots of inbuilt functions that make the development fast.
It supports the feature of dynamic memory allocation.
It provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.
In C, we can call the function within the function. It provides code reusability for
every function.
Elements of C Programming
C Character Set
C programming uses the uppercase English alphabets A to Z, the lowercase letters a to z,
the numeric digits 0 to 9, and certain special characters such as !, * , +, - , % , <, > , & , [
], { }, ; , ?, @, “ “, ^ , #, !#, etc.
256 New Gateway to Computer Science Book -10
Identifiers and Keywords
Identifiers are names given to various items in the program, such as variables, functions
and arrays. An identifier consists of letters and digits, in any order, except that the first
character must be a letter. Both upper and lowercase letters are allowed. Some of the valid
identifiers are A, dd234, name_of_std, area, average, TOT, etc.
Keywords are the reserved words in the programming which are defined in the C
compiler. We cannot use the C keywords as the name of variable’s and function’s name,
etc. C has 32 keywords which are listed below in the table.
auto case break char
const continue default void
double enum extern
float else do
long goto for return
short int register static
struct signed sizeof while
unsigned switch volatile Union
typedef
if
Constants
Constants are those values which never change during the execution of the program. There
are various constants in C programming. Some of the constants are explained below.
Character constant: Character constant is always enclosed in single quotes such as ‘A’. It
indicates only one character such as char = ‘B’
Integer constant: A normal integer constant is written as 5647. It includes both positive
and negative numbers such as int num = 150, int num = -140.
Long integer constant: A long integer is recognized by the presence of L (uppercase or
lowercase) at the end of the constant, for example: 2748723L.
Floating point constants: A floating point constant contains a decimal point (555.102)
or an exponent (1e-2) or both. Their type is double unless suffixed. The suffix of f or F
indicates float; 1 or L indicates long double.
String constant: It is a sequence of characters which is written in pair of double quotes
(“ “). It is declared as array of characters. A string constant may consist of any combination
of digits, letters, escaped sequences and spaces. It also includes numbers but such numbers
cannot be used for mathematical calculations. Some examples of string constants are char
name = “Divyansh”, char age = “15”, etc.
New Gateway to Computer Science Book -10 257
Rules for Constructing String constants
A string constant may consist of any combination of digits, letters, escaped sequences
and spaces enclosed in double quotes.
Every string constant ends up with a NULL character which is automatically assigned
(before the closing double quotation mark) by the compiler.
Difference between single character constant and string constant
Single Character Constant String Constant
It is enclosed within single inverted A sequence of characters is enclosed in
commas. double quotes.
The maximum length of a character A string constant can be of any length.
constant can be one character.
A single character constant has an A single character string constant does not
equivalent integer value. have an equivalent integer value.
A single character constant occupies one A single string constant occupies two
byte. bytes.
Variables
A variable defines a location name where we can put value and we can use these values
whenever required in the program. Variable is a name or identifier which indicates some
physical address in the memory, where data will be stored in the form of the bits of string.
The value of a variable can be changed at different times of executions and it may be
chosen by the programmer.
Rules for naming variable:
Variable name must begin with letter or underscore.
Variables are case sensitive.
Variables name can be constructed with digits, letters.
Special symbols are not allowed other than underscore.
C keywords are not allowed to use.
Statements
A statement is a command given to the computer that instructs the computer to take
a specific action, like display message on the console, performing the mathematical
operation and so on. In C program, collection of statements and each statement must be
terminated with a semicolon (;).
258 New Gateway to Computer Science Book -10
Operators
C language offers many types of operators. They are,
Arithmetic operators
Assignment operators
Relational operators
Logical operators
Bit wise operators
Conditional operators (ternary operators)
Increment/decrement operators
Special operators
Arithmetic Operators
C Arithmetic operators are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus in C programs. Some of the arithmetic
operators with their examples are listed below in the table.
Arithmetic Operators/Operation Example
+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
/ (Division) A/B
% (Modulus) A%B
Assignment Operators
These are used to assign the values for the variables in C programs. In C programs, values
for the variables are assigned using assignment operators. For example, if the value “10”
is to be assigned for the variable “sum”, it can be assigned as “sum = 10;” There are 2
categories of assignment operators in C language. They are, simple assignment operator
such as = (equals to) and compound assignment operators such as +=, - =, * =, / =, % =,
& =, ^ = .
Operators Example/Description Example
= Assignment x+y
+= Add to x+=y
-= Subtract from x-=y
*= Multiply by x*=y
/= Divide by x/=y
Modulo by
%= x%=y
New Gateway to Computer Science Book -10 259
Relational Operators
These operators are used to compare the value of two variables. It is used to find the
relation between two variables. Some of the relational operators with their examples are
listed below in the table.
Operators Example/Description
> x > y (x is greater than y)
< x < y (x is less than y)
>= x >= y (x is greater than or equal to y)
<= x <= y (x is less than or equal to y)
== x == y (x is equal to y)
!= x != y (x is not equal to y)
Logical Operators
These operators are used to perform logical operations on the given two variables. There
are three logical operators in C language. They are, logical AND (&&), logical OR (||)
and logical NOT (!).
Operators Example/Description
&& (logical AND) (x>5)&&(y<5)
It returns true when both conditions are true.
|| (logical OR) (x>=10)||(y>=10)
It returns true when at-least one of the conditions is true.
! (logical NOT) !((x>5)&&(y<5))
It reverses the state of the operand “((x>5) && (y<5))”
If “((x>5) && (y<5))” is true, logical NOT operator makes it
false.
Bit wise Operators
These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT),
260 New Gateway to Computer Science Book -10
^ (XOR), << (left shift) and >> (right shift). Below are the bit-wise operators and their
name in c language.
& : Bitwise AND | : Bitwise OR
~ : Bitwise NOT ^ : XOR
<< : Left Shift >> : Right Shift
Conditional Operators (Ternary Operators)
Conditional operators return one value if condition is true and returns another value is
condition is false. This operator is also called as ternary operator. The (?) Question mark
and (:) colon are the ternary operators used in C programming.
Syntax: (Condition? true_value: false_value);
Increment / Decrement Operators
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs. These
operators are also called as a Unary operator. Below are the unary operators used in C
programming.
Operators Description
++
It is an increment operator which increases the value of operand.
-- Such as num = x ++ , num = ++ x.
It is a decrement operator which decreases the value of operand.
Such as num = x -- , num = -- x.
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
Special Operators
Below are some of the special operators that the C programming language offers.
Operators Description
& This is used to get the address of the variable.
*
This is used as a pointer to a variable.
Sizeof () This gives the size of the variable.
New Gateway to Computer Science Book -10 261
Data Types and Sizes
There are few basic data types in C. They are listed in the table below:
Data type Description Size Range
char 0 - 255
int It is used to store single character or 1 byte
float -2147483648 to
alphabet. 2147483647
double 3.4E-38 to 3.4E+38
It is used to store numeric value without 4 bytes
decimal portion.
It is used to store single precision floating 4 bytes
point number. Such number may contain
fraction & or an exponent.
It is used to store double precision floating 8 bytes 1.7E-308 to
point number with decimal places. 1.7E+308
The list of data types can be increased by using the data type qualifiers such as - short,
long, and unsigned. For example, an integer quantity can be defined as long, short, signed
or unsigned integer. The memory requirement of an integer data varies depending on the
compilers used. The qualified basic data types and their sizes are shown in table below.
Data type Size Range
short int 2 bytes -32768 to 32767
long int 4 bytes -2147483648 to 2147483647
unsigned short int 2 bytes 0 to 65535
unsigned int 4 bytes 0 to 4294967295
4 bytes 0 to 4294967295
unsigned long int 8 bytes 1.7E-308 to1.7E+308
long double (extended precision)
Input and Output Functions used in C
C programming has various library functions for data input and output, such as getchar,
putchar, scanf, printf, gets and puts. All these built-in functions are present in C header
files. These functions enable the transfer of data between the C program and standard
input/output devices. Input function means to provide the program with some data to be
used in the program and output function means to display data on screen or write the data
to a printer or a file.
262 New Gateway to Computer Science Book -10
scanf ( ) function
The scanf function is used to read formatted input data. The format in which input data is
to be provided is specified by the scanf function itself as its first parameter. The syntax of
scanf function is given below.
Syntax: scanf(<control string>, &address1, &address2, . . . , &address n);
In the above syntax the first parameter <control string> contains a list of format specifiers
indicating the format and type of data to be read. The remaining parameters - &address1,
&address2, ..., &address n are addresses of the variables where the read data will be stored.
scanf reads the input data as per the format specifiers and stores them to the corresponding
addresses. In the above syntax & is pre-fixed to the variable name to denote its address.
There must be the same number of format specifiers and addresses as there are input data.
For instance, in the following example:
Example: scanf(“%d %f”,&x,&y);
In the above example, the first argument is a string that contains two format specifiers-
%d and %f, the first format specifier (%d) is for argument &x and the second one (%f) is
for the argument &y. So, two pieces of input data will be read - the first piece is treated
according to %d and the second one is treated according to %f. Format specifiers in the
<control string> are always specified for the remaining arguments, in order, from left to
right.
The format specifiers described in the table below apply to both scanf and printf functions.
Format Input Data (scanf) Output Data (printf)
Specifier
%c reads a single character single character
%d
reads a numeric value as signed int. Treats signed decimal integer
%i the input data as a decimal number.
%o can read data value provided either as a print as a signed decimal
decimal int, hexadecimal int or octal int integer.
%x
reads data value as an octal number prints data as an octal integer
%u without leading zero.
%f
reads data value as a hexadecimal number prints data as a hexadecimal
integer without leading 0x.
reads data value as an unsigned integer prints as an unsigned integer.
reads data as a floating point value without prints as a floating point value
the exponent. (without exponent)
New Gateway to Computer Science Book -10 263
printf()
The printf function is used to output data onto the standard output device. In general, the
printf function is written as
Syntax: printf(<control string>, arg1, arg2, . . . , argn);
where the <control string> refers to a string containing required formatting information
as in scanf, and arg1, arg2, ..., argn are individual data variables whose values are to
be printed. However, unlike scanf, these data variable names are not preceded by the &
symbol. This is because printf is expected to only output the values of these variables and
not their addresses.
getchar()
This is a single character input function. getchar() reads a single character from the
standard input data stream. When you input a single character for the C program to read,
you must indicate end of data stream or end of input by pressing the return/enter key after
entering your response character.
putchar()
This is a single character output function. putchar() writes a single character to the standard
output data stream. The file associated with the standard output device, is normally the
console.
gets() and puts()
The standard library function gets accepts input in the form of a string. The character
string may even include white space characters. Each call to gets will read all the
characters from the input steam until an end of line character is encountered. The end of
line character is represented as \n and gets generated when you press the enter key. gets
assigns the read string to the variable that is passed as its parameters. gets assigns NULL
when an error occurs.
clrscr() function
The clrscr() function is used to clear the screen and move cursor to upper left hand corner
of screen. It can be used anywhere in the program. It is better to use before the declaration
part.
264 New Gateway to Computer Science Book -10
Understanding Header File
A header file is a file having an extension .h which contains C function declarations macro
definitions. It holds the definitions of various functions and their associated variables
that need to be imported into your C program with the help of pre-processor #include
statement. The default header file that comes with the C compiler is the stdio.h. Including
a header file means that using the content of header file in your source program. The basic
syntax of using these header files is given below.
Syntax: #include <file>
Some common header files included in C programming are listed below.
#include<stdio.h>: This standard input-output header file is used to perform input and
output operations in C such as scanf() and printf().
#include<string.h>: This string header file is used to perform string manipulation
operations like strlen and strcpy.
#include<conio.h>: The console input-output header file is used to perform console
input and console output operations like clrscr() to clear the screen and getch() to get the
character from the keyboard.
#include<stdlib.h>: The standard library header file is used to perform standard utility
functions like dynamic memory allocation, using functions such as malloc() and calloc().
#include<math.h>: The math header file is used to perform mathematical operations like
sqrt() and pow(). To obtain the square root and the power of a number respectively.
#include<ctype.h>: The character type header file is used to perform character type
functions like isaplha() and isdigit(). To find whether the given character is an alphabet
or a digit respectively.
#include<time.h>: The time header file is used to perform functions related to date
and time like setdate() and getdate(). To modify the system date and get the CPU time
respectively.
#include<graphics.h>: This header file provides access to a simple graphics library that
makes it possible to draw lines, rectangles, ovals, arcs, polygons, images, and strings on
a graphical window.
New Gateway to Computer Science Book -10 265
Program Writing
Example 1
Write a program to Display “ Shubharambha Publication Pvt. Ltd. “
#include <stdio.h>
int main()
{
printf(“Shubharambha Publication Pvt.Ltd”);
return 0;
}
Output
Shubharambha Publication Pvt.Ltd
In the above program, the #include<stdio.h> is a pre-processor command. This
command tells the compiler to include the contents of stdio.h (standard input and output)
file in the program. The stdio.h file contains functions such as scanf() and print() to
take input and display output respectively. If you use printf() function without writing
#include <stdio.h>, the program will not be compiled.
The execution of a C program starts from the main() function.
The printf() is a library function to send formatted output to the screen. In this program,
the printf() displays Shubharambha Publication Pvt. Ltd text on the screen.
The return 0; statement is the “Exit status” of the program. The program always ends
with this statement.
Example 2
Write a program to add any two integers.
#include <stdio.h>
int main()
{
int firstNumber, secondNumber, sum;
printf(“Enter two integers: “);
scanf(“%d %d”, &firstNumber, &secondNumber);
266 New Gateway to Computer Science Book -10
sum = firstNumber + secondNumber;
printf(“%d + %d = %d”, firstNumber, secondNumber, sum);
return 0;
}
Output
Enter two integers: 20 10
20 + 10 = 30
In this program, the user is asked to enter two integers. Two integers entered by the user
is stored in variables firstNumber and secondNumber respectively. This is done using
scanf() function. Then, variables firstNumber and secondNumber are added using +
operator and the result is stored in sum.
Finally, the sum is displayed on the screen using printf() function.
Example 3
Write a program to input temperature in Celsius and display the temperature in Fahrenheit.
#include <stdio.h>
int main()
{
float celsius, fahrenheit;
printf(“Enter the temperature in celcius :”);
scanf(“%f”, &celsius);
fahrenheit = 9.0 / 5 * celsius + 32;
printf(“Temperature in fahrenheit : %0.2f”, fahrenheit); r
eturn 0;
}
Example 4
Write a program which accepts principle, rate and time from user and prints the simple
interest.
#include <stdio.h>
int main()
{
New Gateway to Computer Science Book -10 267
float principle, rate, time, si;
printf(“Enter the principle :”);
scanf(“%f”, &principle);
printf(“Enter the rate :”);
scanf(“%f”, &rate);
printf(“Enter the time :”);
scanf(“%f”, &time);
si = principle * rate * time / 100;
printf(“Simple interest is %0.2f”, si);
return 0;
}
Example 5
Write a program that asks the user to input the length of sides of the triangle and prints
the area.
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, s, area;
printf(“Enter the length of side 1 :”);
scanf(“%f”, &a);
printf(“Enter the length of side 2 :”);
scanf(“%f”, &b);
printf(“Enter the length of side 3 :”);
scanf(“%f”, &c);
s = (a + b + c) / 2;
area = sqrt(s*(s - a)*(s - b)*(s - c));
printf(“\nThe area of the triangle is %0.2f”, area);
return 0;
}
Example 6
Write a program that prompts the user to input the radius of a circle and outputs the area
and circumference of the circle.
#include <stdio.h>
int main()
{
268 New Gateway to Computer Science Book -10
float radius, area, circumference;
printf(“Enter the radius of the circle :”);
scanf(“%f”, &radius);
area = 3.14 * radius * radius;
circumference = 2 * 3.14 * radius;
printf(“\nThe area of the circle is %0.2f”, area);
printf(“\nThe circumference of the circle is %0.2f”, circumference);
return 0;
}
Control Statements in c
The statements that are used to control the flow of execution of statements are known
as conditional control statements. Control statements enable us to specify the flow of
program control. It is the order in which the instructions in a program must be executed.
They make it possible to make decisions, to perform tasks repeatedly or to jump from one
section of code to another.
if statement
This is a popular decision making statement and is used to control the flow of execution
of statements. It is basically a two way decision statement and is used in conjunction with
as expression .The syntax is given below.
If(test condition)
{
statements;
}
If-else statement
The if-else statement is used to carry out a logical test and then take one of two possible
actions depending on the outcome of the test (i.e., whether the outcome is true or false).
The syntax for if-else statement is given below.
if (condition)
{
statements
}
else
{
statements
}
New Gateway to Computer Science Book -10 269
Example 7
A program to checks whether the entered number is positive or negative.
#include<stdio.h>
int main( )
{
int a;
printf(“n Enter a number:”);
scanf(“%d”, &a);
if(a>0)
{
printf( “n The number %d is positive.”,a);
}
else
{
Nested else-if Statements
The else-if statement is useful when you need to check multiple conditions within the
program, nesting of if-else blocks can be avoided using else-if statement. The syntax of
this statement is given below.
if(condition1)
{
// statement(s);
}
else if(condition2)
{
//statement(s);
}
else if (conditionN)
{
//statement(s);
}
else
{
//statement(s);
}
270 New Gateway to Computer Science Book -10
Example 8
A program to find the greatest of three numbers.
#include<stdio.h>
int main( )
{
int a, b,c;
a=6,b= 5, c=10;
if(a>b)
{
if(b>c)
{
printf(“nGreatest is: “ , a);
}
else if(c>a)
{
printf(“nGreatest is: “, c);
}
}
else if(b>c) //outermost if-else block
{
printf(“nGreatest is: “ , b);
}
else
{
printf( “nGreatest is: “ , c);
}
return 0;
}
Looping Statements in c
When you need to execute a block of code several number of times then you need to use
looping statement in C. In C programming language there are three types of loops they
are while, for and do-while.
While loop
This loop checks the condition at first. Iif the condition is true then control goes inside
the loop body otherwise it goes outside the body. It repeats in clock wise direction. The
syntax is given below.
New Gateway to Computer Science Book -10 271
while(condition)
{
Statements;
......
Increment/decrements (++ or --);
}
Example 9
#include<stdio.h> Output
#include<conio.h> 1
void main() 2
{ 3
int i; 4
clrscr();
i=1;
while(i<5)
{
printf(“\n%d”,i);
i++;
}
getch();
}
For loop
A for loop is a repetition control structure which allows us to write a loop that is executed
a specific number of times. The loop enables us to perform n number of steps together in
one line. The syntax is given below.
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Example 10
#include<stdio.h>
#include<conio.h>
void main()
{
272 New Gateway to Computer Science Book -10
int i; Output
clrscr(); 1
for(i=1;i<5;i++) 2
{ 3
printf(“\n%d”,i); 4
}
getch();
}
Do loop
A do while loop is a control flow statement that executes a block of code at least once,
and then repeatedly executes the block, or not, depending on a given condition at the end
of the block (in while). The syntax is given below.
do
{
Statements;
........
Increment/decrement (++ or --)
} while();
Example 11 Output
1
#include<stdio.h> 2
#include<conio.h> 3
void main() 4
{
int i;
clrscr();
i=1;
do
{
printf(“\n%d”,i);
i++;
}
while(i<5);
getch();
}
New Gateway to Computer Science Book -10 273
Practical Section in C Programming
Program 1
Write a program that allows the user to input two integers and displays the largest integer.
#include <stdio.h>
int main()
{
int num1, num2;
printf(“Enter two integers :”);
scanf(“%d%d”, &num1, &num2);
if (num1 > num2)
{
printf(“Largest number is %d.”, num1);
}
else
{
printf(“Largest number is %d.”, num2);
}
return 0;
}
Program 2
Write a program that prompts the user to input a number and displays if the number is
even or odd.
#include <stdio.h>
int main()
{
int num;
printf(“Enter a num:”);
scanf(“%d”, &num);
if(num % 2 == 0)
{
printf(“The number is even”);
}
274 New Gateway to Computer Science Book -10
else
{
printf(“The number is odd”);
}
return 0;
}
Program 3
Write a program that prompts the user to input a number and prints its factorial.
#include <stdio.h>
int main()
{
int i, n, fact = 1;
printf(“Enter a number :”);
scanf(“%d”, &n);
for (i = 1; i <= n; i++)
{
fact *= i;
}
printf(“The factorial of %d is %d.”, n, fact);
return 0;
}
Program 4
Write a program in C to read 10 numbers from keyboard and find their sum and average
by using for loop.
#include <stdio.h>
void main()
{
int i,n,sum=0;
float avg;
printf(“Input the 10 numbers : \n”);
for (i=1;i<=10;i++)
{
New Gateway to Computer Science Book -10 275
printf(“Number-%d :”,i);
scanf(“%d”,&n);
sum +=n;
}
avg=sum/10.0;
printf(“The sum of 10 no is : %d\nThe Average is : %f\n”,sum,avg);
}
Program 5
Write a program to print the numbers between 1 and 100 which are multiple of 3 using
the do while loop.
#include<stdio.h>
int main()
{
int i = 1;
do
{
if(i % 3 == 0)
{
printf(“%d “, i);
}
i++;
}while(i < 100);
return 0;
}
Program 6
Write a C program to print ODD numbers from 1 to N using while loop.
#include <stdio.h>
int main()
{
int number;
int n;
number=1;
276 New Gateway to Computer Science Book -10
printf(“Enter the value of N: “);
scanf(“%d”,&n);
printf(“Odd Numbers from 1 to %d:\n”,n);
while(number<=n)
{
if(number%2 != 0)
printf(“%d “,number);
number++;
}
return 0;
}
Program 7
Write a program to display a number if it is negative.
#include <stdio.h>
int main() {
int number;
printf(“Enter an integer: “);
scanf(“%d”, &number);
if (number < 0) {
printf(“You entered %d.\n”, number);
}
printf(“The if statement is easy.”);
return 0;
}
Program 8
Write a C program to check whether the entered number is prime or not.
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf(“Enter a positive integer: “);
scanf(“%d”, &n);
for (i = 2; i <= n / 2; ++i) {
// condition for non-prime
New Gateway to Computer Science Book -10 277
if (n % i == 0) {
flag = 1;
break;
}
}
if (n == 1) {
printf(“1 is neither prime nor composite.”);
}
else {
if (flag == 0)
printf(“%d is a prime number.”, n);
else
printf(“%d is not a prime number.”, n);
}
return 0;
}
Program 9
Write a program to print all uppercase alphabets using while loop.
#include <stdio.h>
int main()
{
char alphabet;
alphabet=’A’;
printf(“Uppercase alphabets:\n”);
while(alphabet<=’Z’)
{
printf(“%c”,alphabet);
alphabet++;
}
return0;
}
278 New Gateway to Computer Science Book -10
Program 10
Write a program to print the numbers from 1 to 100 using while loop in C.
#include <stdio.h>
int main()
{
int number;
number=1;
printf(“Numbers from 1 to 100: \n”);
while(number<=100)
{
printf(“%d”,number);
number++;
}
return0;
}
Program 11
Write a program using while or do while loop to read any integer number and print its
multiplication table.
#include <stdio.h>
int main()
{
intnum;
int i;
printf(“Enter an integer number: “);
scanf(“%d”,&num);
i=1;
while(i<=10){
printf(“%d\n”,(num*i));
i++;/*Increase loop counter*/
}
return0;
}
New Gateway to Computer Science Book -10 279
Program 12
Write a program to print all upper case and lower case alphabets.
#include <stdio.h>
int main()
{
char i;
printf(“Capital (upper) case characters:\n”);
for(i=’A’; i<=’Z’; i++)
printf(“%c”,i);
printf(“\n\nLower case characters:\n”);
for(i=’a’; i<=’z’; i++)
printf(“%c”,i);
return0;
}
Program 13
Write a program to print the uppercase and lowercase alphabets from A to K.
#include <stdio.h>
int main()
{
char i;
printf(“Capital (upper) case characters:\n”);
for(i=’A’; i<=’K’; i++)
printf(“%c”,i);
printf(“\n\nLower case characters:\n”);
for(i=’a’; i<=’k’; i++)
printf(“%c”,i);
return0;
}
280 New Gateway to Computer Science Book -10
Program 14 281
Write a program to find sum of natural numbers in given range.
#include <stdio.h>
int main()
{
int i, start, end, sum=0;
printf(“Enter lower limit: “);
scanf(“%d”,&start);
printf(“Enter upper limit: “);
scanf(“%d”,&end);
for(i=start; i<=end; i++)
{
sum+= i;
}
printf(“Sum of natural numbers from %d to %d = %d”, start, end, sum);
return0;
}
Program 15
Write a program to count the total digits in a given integer using loop.
#include <stdio.h>
int main()
{
longlongnum;
int count = 0;
printf(“Enter any number: “);
scanf(“%lld”, &num);
while(num != 0)
{
count++;
num /= 10;
}
printf(“Total digits: %d”, count);
return0;
}
New Gateway to Computer Science Book -10
Innovative Task
Make a list of 32 keywords used by C programming and make a list of at least 5
format specifier that are being used by C programming and submit to your teacher.
Assignment
1. Answer the following question.
a. What is C programming? Define it with its features.
b. Who was the inventor of C? When was it invented?
c. What are the advantages and disadvantages of C programming?
d. Define structure programming.
e. What are the elements of C programming?
f. Define C constant with its types.
g. What are the rules for naming variables?
h. Write differences between single character constant and string constant.
i. List out the operators used by C language.
j. Explain logical operators.
k. Define conditional operators with syntax.
l. What are the various data types used by C language?
m. List out some of the input and output functions used in C.
n. Write down the name of some format specifiers used by C.
o. Define header file with syntax.
p. What is control statement? Explain some control statements with syntax.
q. What is looping statement? Write down the types of looping statements with their
syntax.
282 New Gateway to Computer Science Book -10
2. Write a C program for the followings:
a. To input temperature in Celsius and display the temperature in Fahrenheit.
b. To input principle, rate and time from the user and print the simple interest.
c. To prompts the user to input the radius of a circle and outputs the area and
circumference of the circle.
d. To input two integers and displays the largest integer.
e. To input a number and displays if the number is even or odd.
f. To check whether the entered number is divisible by 3 and 5 or not.
g. To check whether the entered number is odd or even.
h. To display the area of four walls.
i. To display the first ten prime numbers.
j. To check whether the entered number is prime or not.
k. To display the greatest number among three different numbers.
l. To display the factorial of a given number.
m. To print the odd numbers from 1 to 100 using while loop, for loop and do loop.
n. To display the small letters from aa to mm.
o. To read any integer number and print its multiplication table.
p. To print the numbers between 1 and 100 which are multiple of 7 using the do
while loop.
New Gateway to Computer Science Book -10 283
List of Abbreviations
AC : Alternate Current
ADSL : Asymmetric Digital Signature Line
ANSI : American National Standard Institute
ARP : Address Resolution Protocol
ARPA : Advance Research Project Agency
ASCC : Automatic Sequence Controlled Calculator
ASCII : American Standard Code for Information Interchange
ATM : Automated Teller Machine
AVI : Audio-Video Interleaved
CAD : Computer Aided Design
CAE : Computer Aided Education
CAM : Computer Aided Manufacturing
CAN : Computer Association of Nepal
CBT : Computer Based Training
CDMA : Code Division Multiple Access
CMOS : Complementary Metallic Oxide Semiconductor
COBOL : Common Business Oriented Language
CREN : Council Research European Network
CRT : Cathode Ray Tube
CSMA/CD : Carrier Sense Multiple Access / Coliseum Detection
CVT : Constant Voltage Transformer
DARPA : Department of Advance Research Project Agency
DBMS : Database Management System
DHCP : Dynamic Host Configuration Protocol
284 New Gateway to Computer Science Book -10
DNS : Domain Name Server 285
DSP : Digital Signal Processor
DSS : Digital Satellite System
DVD : Digital Video Disk
EBCDIC : Extended Binary Coded Decimal Code
EDP : Electronic Data Processing
E-Mail : Electronic- Mail
FAQ : Frequently Asked Questions
FAT : File Allocation Table
FM : Frequency Modulation
FORTRAN : FORmula TRANslator
FTP : File Transfer Protocol
GIF : Graphic Interchange Format
GPRS : General Pocket Radio Service
GSM : Global System for Mobile communication
HTML : Hyper Text Make up Language
HTTP : Hyper Text Transfer Protocol
IAB : Internet Architecture Board
IBN : Interactive Broadband Network
IBT : Internet Based Training
ICT : Information Communication Technology
IETF : Internet Engineering Task Force
IFIP : International Federation of Information Processing
IP : Internet Protocol
IPX / SPX : Internetwork Packet Exchange / Sequenced Packet Exchange
IRC : Internet Relay Chat
New Gateway to Computer Science Book -10
IRTF : Internet Research Task Force
IS : Information Service
ISAPI : Internet Server Application Programming Interface
ISD : International Subscriber Dialling
ISDN : Integrated Service Digital Network
ISO : International Organization for Standardization
ISOC : Internet Society
ISP : Internet Service Provider
ITSP : Internet Telephony Service Provider
JPEG : Joint Photographic Expert Group
LAN : Local Area Network
LCD : Liquid Crystal Display
Mac OS : Macintosh Operating System
MAC : Media Access Control
MAN : Metro Area Network
MAP I : Messaging Application Programming Interface
MBPS : Mega Byte Per Second
MIDI : Musical Instrument Digital Interface
MMS : Multimedia Message Service
MODEM : Modulator and Demodulator
MPEG : Moving Pictures Experts Group
MPOA : Multi Protocol Over ATM
MPPP : Multilink Point-to-Point Protocol
MSAV : Microsoft Antivirus
MSB : Most Significant Bit
MSN : Microsoft Network
286 New Gateway to Computer Science Book -10
MUK : Multimedia Upgrade Kit 287
NetBEUI : Network Bios(Basic Input Output System) Enhance User Interface
NFS : Network File System
NIC : Network Interface Card
NITDC : National Information Technology Development Council
NOS : Network Operating System
OLE : Object Linking and Embedding
PCO : Public Call Office
PDF : Portable Document Format
POP : Post Office Protocol
PSTN : Public Switch Telephone Network
RARP : Reverse Address Resolution Protocol
RDBMS : Relational Database Management System
RIP : Routing Information Protocol
RJ-45 : Registered Jack - 45
RTF : Rich Text Format
RTP : Real Time Protocol.
SDSL : Symmetric Digital Subscriber Line
SGML : Standard Generalized Mark-up Language
SIM : Subscriber Identification Module
SMS : Short Message Service
SMTP : Simple Mail Transfer Protocol
SNA : System Network Architecture
SPX : Sequence Packet Exchange
SQL : Standard Query Language
STD : Standard Trunk Dialling
New Gateway to Computer Science Book -10
STP : Shielded Twisted Pair
TCP/IP : Transmission Control Protocol / Internet Protocol
UHF : Ultra High Frequency
UPS : Uninterruptible Power Supply
URL : Uniform Resource Locator
USB : Universal Serial Bus
USP : Universal Serial Port
UTP : Unshielded Twisted Pair
VCD : Video Cascade Recorder
VHF : Very High Frequency
VOIP : Voice Over Internet Protocol
VSAT : Very Small Aperture Terminal
W3C : World Wide Web Consortium
WAIS : Wide Area Information Server
WAN : Wide Area Network
WAP : Wireless Application Protocol
Wi Fi : Wireless Fidelity
WWW : World Wide Web
288 New Gateway to Computer Science Book -10