Saturday, June 16, 2012

Course in detail for grade XII (Computer Science)

Loading
Course in detail for grade XII
Course topics
1.             System development concept
1.1 Feasibility study
1.2 System development life cycle
1.2.i System Study
1.2.2 System Design
1.23 Programming
1.2.4 Testing
1 .2.5 ImplementatiOn
1.3 System security
2.             Database management system
2.1 Data modeling
2.1.1 Purpose
2.1.2 Components
2.1.2.1 Relationship
2.1.2.2 Entities and attributes
2.1.2.3 Domains and identifiers
2.2 Methodology
2.2.1 To1) down methodology
2.2.2 Normalization
2.3 Database design
2.3.1 Relational model
2.3.2 Network model
2.3.3 Hierarchical model
2.4 Data security
3.             Networking concept
3.1 Introduction
3.2 Computer networks
3.3 Transmission media
3.4 Topologies
3.5 Sharing techniques
4. Programming language
4.1Review of algorithms
4.2 Program development using C Language
4.3 Concept of object oriented progratnrning
4.4 Documentation techniques
5. Computer and security
5.1 The impact of computers in society
5.2 Cyber law
5.3 Ethical aspects
6. State of art in computer technology
6.1 Multimedia
6.2 Internet
6.3 Artificial intelligence in computer
6.4 Contemporary technology
7.             Project work
7.1          System design and development in C or C++
The project should be assigned to individual student

An example of prefix mode:
x = 10;
y=++x;
After these statements are executed, x has the value 11, and y has the value 10. The value of x was assigned to y, and then x was incremented. In contrast, the following statements result in both y and x having the value 11. x is incremented, and then its value is assigned to y.
An example of postfix mode
x=10;
y=++x;

d) Relational operator:
Cs relational operators are used to compare expressions, asking questions such as, “Is x greater than 100?” or “Is y equal to 0?” An expression containing a relational operator evaluates to either true (1) or false (0).
C’s relational operators.
Operator                                                 Symbol                                                Example
Equal                                                      = =                                                        x==y
Greater than                                           >                                                           x > y
Less than                                                 <                                                            x<y
Greater than or equal to                       >=                                                         x >= y
Less than or equal to                            < =                                                        x <= y
Not equal                                                !=                                                         x != y

e) Logical operator:
C’s logical operators let you combine two or more relational expressions into a single expression that evaluates to either true or false.
C’s logical operators.
Operator                               Symbol                  Example
AND                       &&                        exp1 && exp2
 OR                           ||                            exp1 || exp2
NOT                       !                              !expl

f) Ternary operator:
The ternary operator is C’s only ternary operator, meaning that it takes three operands. Its syntax is
expi ? exp2: exp3;

If exp 1 evaluates to true (that is, nonzero), the entire expression evaluates to the value of exp2. If expi evaluates to false (that is, zero), the entire expression evaluates as the value of exp3. For example, the following statement assigns the value 1 to x if y is true and assigns 100 to x if y is false:
x=y ? 1: 100;
Likewise, to make z equal to the larger of x and y, you could write z= (x>y) ? x : y;
Perhaps you’ve noticed that the conditional operator functions somewhat like an if statement. The preceding statement could also be written like this:
if(x>y)
z=x;
else
z=y;
The ternary operator can’t be used in all situations in place of an if...else construction, but the conditional operator is more concise. The ternary operator can also be used in places you can’t use an if statement, such as inside a single printf() statement:
printf (“The larger value is %d”,((x >y)?x:y));

g) Comma operator:
It permits two different expression to appear in situation where only one expression would ordinarily be used.
Example: {
int a, b, c;
c=(a= 10,b=20,a+b);
print f(”c = %d”, c);
}

9. ‘What is a statement? Explain different types of statement with examples.
Ans: Any line written in a ‘c’ editor that normally terminates by a semicolon ‘;‘ is called statement. Examples:
int a, b, c, d= 55;
 float rate;
 char n; etc.
The different types of statements are:

a) Null statement:
If you place a semicolon by itself on a line, you create a null statement--a statement that doesn’t perform any action. This is perfectly legal in C. Example:
;- Null statement

b) Expression statement:
An expression statement is a constant, variable or combination of constant and variable. This can also include a function call. An expression statement consists of any valid C expression and followed by a semicolon.
Examples:
a=b;                                        -Expression statement
 c=a+b;                  - Expression statement
greater (a, b,c);     -Function call

c) Compound statement:
A compound statement, also called a block, is a group of two or more C statements within a pair of braces ({ and}). Unlike an expression statement, a compound statement does not end with a semicolon.
Example: {
printf(”Hello, “);
printf(”sathi!”);
}

In C, a block can be used anywhere a single statement can be used. Many examples of this appear throughout this book. Note that the enclosing braces can be positioned in different ways.

d) Control statement:
Control statements are used to create special program features, such as logical tests, loops and branches. Examples:
i) if(a>b)
printf(”A is greater”);
else
printf("B is greater”);
ii) while

10. What do you know about comments and escape sequences?
Ans: Comments are the statements that are used for user aid. Such statements are ignored by the compiler. A comment is denoted by
/ *……………. */ For multi statements
Anything written between this is ignored by the compiler
// For single statement
Escape sequence: These are the characters not printed when used but provide various functions. Escape sequences are always started with a backslash' \'. Commonly used escape sequences are:
Character              Escape sequence
bell (alert)                              \a
backspace                             \b
horizontal tab       \t
new line                 \n
carriage return      \r
quotation mark    \"
backslash                              \\
null                                         \0 etc.

11. Explain the following terms:
a) Symbolic constants
b) Library functions
c) Header files
Ans: a) Symbolic constants: A symbolic constant allows a name to appear in place of numeric constant, character constant or a string. symbolic constants are usually defined at the beginning of the program. Symbolic constants may appear later in the program in place of numeric constants, character constant and so on. At the time of compiling each occurrence of a symbolic constant get replaced by its corresponding character sequence. Examples:
#defineAND &&
# define Pi 3.1412
 # define True 1
# define friend “Susan” etc.
b) Library functions: Many functions of C is carried out by library functions. These functions perform file access, mathematical computation graphics, memory management data conversion etc. A typical set of library functions will include a large number of functions that are common to most C compilers. Examples : sqrt ( ), to lower ( ), to upper, abs ( ) etc.
c) Header files: By placing thern required library function declaration in special source file is called header file.
Or
•Header files contain definitions of funètions and variables which can be incorporated into any C program by using the pre-processor #include statement.Standard header files are provided with each compiler, and cover a range of areas:string handling, mathematics, data conversion, printing and reading of variables, etc.
•To use any of the standard functions, the appropriate header file should be included.This is done at the beginning of the C source file. For example, to use the function printf() in a program, the line #include <stdio.h> should be at the beginning of the source file, because the declaration for printf() is found in the file stdio.h. All header files have the extension ii
#include <string.h>
 #include <math.h>
#incilude "mylib.h"
• The use of angle brackets <> informs the compiler to search the compiler’s include directories for the specified file. The use of the double quotes" " around the filename informs the compiler to start tbe search in the current directory for the specified file.
Some commonly used header files are:
stdio.h, conio.h, process.h, math.h, ctype.h, string.h, stdlib.h etc.

12. What are data types? Explain.
Ans: Data types are used to declare the variable name in C language. C supports different types of data, each of which may be represnted differently within the computer’s memory. There are the various data types and these are:
Data typeData sub_ typeBytesFormatRange
Signed
.
character
I
%c
— 128 to 127
Unsigned character
1
%c
.
0 to 255
Computer Science 13
(4 A Refresher Manual of Computer Science for Grade XII
Short signed
Numeric .
mt
Short Unsigned
mt
2
%d
—32768 to 32767
2
%d
Oto 65535
Long signed mt
4
%Id
—2147483648 to 2147483647
Long
unsigned mt
4
%id
0 to
4294967295
Float
4
% f
3.4E—38 to
3.4E+38
Double
8
% if
1.7E—308 to
1.7E+308
Long double
10
%lf
3.4E-4932 to
3.4E + 4932
13. For what purpose main() function and #include directive are used.
Ans: The main() Function -
The oniy main component that is required in every C program is the main() function.The main() function consists of the name main followed by a pair of empty parenthesis (0) and a pair of braces ({}). Within the braces are statements that make up the main body of the program. Under normal circumstances, program execution starts at the first statementin main() and terminates at the last statement in mainO.
The #include directive
The #inciude directive instructs the C compiler to add the contents of an include file into your program during compilation. An include file is a separate disk file that contains information needed by your program or the compiler. Several of these files (sometimes called header flies) are supplied with your compiler. You never need to modif’ the information in these files; that’s why they’re kept separate from your source code. Include files should all have an .h extension (for example, STDIO.H).
You use the #include directive to instruct the compiler to add a specific include file to your proam during compilation. The #include directive in this sample program means “Add the contents of the file STDIO.H.” Most C programs require one or more include files.
Computer Science
15
(4. What is branchng?Write down the syntax of if ,if. .else and if..ejse if..else statement.
Aiic: Branching is based on decision making. If the decision is satisfied, then it can perform the task, otherwise it executes the line next to
It.
The various branching statements are:
(a) if else
(b) if else if else
(c) switch. . .case
yiQfjfif..else and if..else if..else statement are:
->The if Statement if(expression)
statement];
If expression is true, statement] is executed. If expression is not true,
statement! is ignored.
->The if..else Statement if(expression)
statement];
else
statement2;
If expression is true, statement I is executed; otherwise, statement2 is executed.
—>The if..else if..else Statement if(expressionl)
statement];
else if(expressio,i2)
statement2;
else
statement3;
If the first expression, expression!, is true, statement] is executed before the program continues with the next_statement, If the first expression is not true, the second e)pression, expression2, is checked. If the first expression is not true, and the second is true, statement2 is executed. If both expressions are false, statement3 is executed. Only one of the three statements is executed at a time.
What is looping?Write down the syntax of while,for and do while statement.
Looping is a process which allows the data to be repeated unless or until some condition has been satisfied. The various looping statements are:
(a) for
(b) while
(c) do while
Syntax of while,for and do while statement are:
a) for
syntax>for (expi; exp2; exp3)
{
)
statementi;
where,
expi = Initial expression
exp2=Conditional expression exp3=Increment or decrement
‘When a for statement is encountered during progrars execution, the following events occur:
1. The expression, expi is evaluated. expi is usually ai assignment statement that sets a variable to a particular valuer
2. The expression, exp2, i.e. condition is evaluated, condition i typically a relational expression.
3. If exp2, i.e.condition evaluates to false (that is, as zero), th for statement terminates, and execution passes to the fir statement following statement.
4. If exp2, i.e. condition evaluates to true (that is, as nonzero the C statement(s) in statement are executed.
5. The exp3, i.e. increment or decrement is evaluated an execu.tion returns to step 2.
b) while
syntax>while (condition)
16 A Refresher Manual of Computer Science for Grade XII
15.
Ans:
statement 1;
When program execution reaches a while statement, U following events occur:
1.       The expression condition is evaluated.
Computer Science
17
2. If condition evaluates to false (that is, zero), the while statement terminates, and execution passes to the first statement following statement.
3. If condition evaluates to true (that is,’ nonzero), the C statement(s) in statement are executed.
4. Execution returns to step 1.
• c) do while syntax: do
{
while (condition);
When program execution reaches a do.. .while statement, the
following events occur:
1. The statements in statement are executed.
2. condition is evaluated. If it’s true,. execution returns to step 1. If it’s false, the loop terminates
16. What is infinite loop? Differentiate between “break” and “continue” statements.
Ans: A loop that has no stopping or never ending condition is called an infinite loop. Example: ,
for(; ;) while(1)
{ } { I
Break: The “break” statement is used to terminate the control from the loop.It is normally used in switch-case statement,the break statement must be used if not the control will be transferred to the subsequent case condition also. Example:
#include<stdio.h>
a = a + 1;
if (a%3==O)
break; printf (“%d”,a);
Result:
2
statement 1;
statement2;
#include<conio.h> void mainO
mt a =1;
while (a < 20)
I
18 A Refresher Manual of Computer Science for Grade XII
getchO;
I
Continue: The “continue” statement skips the rest of execution of the loop. Example:
#include<stdio.h> ___________________
#include<conio.h>
void main()
{
mt a =1; while (a < 10)
I
getchO;
a=a+ 1; if (a%3==0)
continue;
printf (‘%d”,a);
17. Differentiate between ‘for and ‘while’ statements.
Ans: Differentiation between for’ and’while’ statements:
For
While
a)
The for statement executes the initial expression first. It then checks the condition, If the condition is true, the statements execute. Once the statements are completed, the increment expression or decrement is evaluated. The for statement then rechecks the condition and continues to loop until the condition is false.
It allows repeated execution of a statement or block of statements as long as the condition remains true (nonzero). If the condition is not true when the while command is first executed, the statement(s) is never executed.
b)
syntax>
for (expi; exp2; exp3)
{
statementi;
where,
syntax>while (condition)
{
statementi;
Result:
2 4 5 7 8 10
Computer Science 19
exp1 = Initial expression exp2=Conditional
expression
exp3=Increment or
decrement
•
The flow chart of for loop.
:ion:Tmestts
The flow chart of while
Example:Displaying 1 to 10 numbers
# include <stdio.h> # include <conio.h> void main ()
{
mt a;
for (a = 1; a <= 10; +÷a)
printf(”%d\t”, a);
getchCY; •‘
I
Example: Displaying 1 to
10 numbers
it include <stdio.h>
# include <conio.h>
void main ()
{
mt a;
a= 1;
while (a <= 10)
{
printf(”%d\t”, a);
a=a+1;
getch();
18. Differentiate between ‘while’ and ‘do while’ statements.
[HSEB-2061,2062]
Ans: Differentiation between while and do while statements:
While
Do while
a)
It allows repeated execution of
a statement or block of
statements as long as the
condition remains true
The do while statement executes a body of instruction at least one time and more if an expression remains true.
(nonzero). If the condition is
not true when the while
command is first executed, the
statement(s) is never executed.
20 A Refresher Manual of Computer Science for Grade Xli
{
statement 1; statement2;
statement 1; statement2;
while (condition);
for
program
printing ito 10 nos.
# include<stdio.h>
# include<conio.h>
void main ()
{
Example: A program
printing 1 to 10 nos.
# include<stdio.h>
# include<conio.h>
void main ()
{
mt a;
a= 1;
while (a <= 10)
printf(%d\t”, a); a = a + 1;
getch();
inta= 1; do
printf(”%d\t”, a);
‘ a=a+1;
} while (a <=10);
getch( ) ;
}
I
19.
Ans:
Differentiate between local and global variables. Differentiation between local and_global_variables:
Local variable
Global variable
a)
It is the way to declare the
variable. A variable is declared
A variable declared outside a
block that is available to other
within a bléck is called a local
black of the program is called
variable to that block,
a global variable.
b)
Example:
Example:
void main C)
mt a = 10; II global variables
{
inta= 10;//locaito
voidmain()
{
//main
inta=6;
Computer Science 21
‘What is switch case statement? Explain it with examples. It allows us to select a choice out of many available choices.
Syntax:
switch (variable name)
case value 1
break;
case value2: ‘
break; case value3:
break;
default:
printf (“Sunday”);
break;
printf (“Monday”); break;
printf(”Tuesday”);
break;
printf(”Wednesday”);
break;
20.
A ns:
Example: inta; printf(”Enter number of day:”):
scanf(”%d”,&a);
switch (a)
case 1
case 2:
case 3:
case 4:
case 5:
22 A Refresher Manual of Computer Science for Grade XII
printfC’Thursday”); break;
priritf(”Friday”);
break;
case 7:
}
printfC’Saturday”):
break
printf (“nor the value”); exit(O);
default:
Write the syntax and an example of “goto” statement.
The goto statement is used to alter the normal sequence of t program execution by transferring control to some other parts the program.
syntax> goto Iidentifier;
Example: A program for finding odd or even numbers by usii GOTO statement.
# include <stdio.h>
# include <0no.h>
void main ()
1
mt n;
char ch;
x : clrscr ( );
printf(”Enter any number =“); scanf(”%d”, & n);
if (n% 2 0)
prmntf (“Even number”);
else
printf (“Odd number”);
printf(”Do you want to continue (YIN) = “); scanf(”%c”, ch);
if(ch = = ‘Y’ Itch =
goto x; getchO;
case 6:
21.
Ans:
Computer Science 23
char C;
c = getchar 0;
printf(”\n input character = %c”, c); getchO;
{
}
char ch;
printf (“Enter any letter :—“); ch = getchar 0; printf (“Output”); putchar (ch); ghetchO;
22. Describe the getchar and putchar function with limitation.
Ans: Getchar: It returns only one character at a time from a standard input device. The getchar accept all type of characters even space, tab, blank, return. This function has the limitation, i.e. this isn’t used for numeric operations and also not used for looping.
Example:
# include<stdio.h>
- #include<conio.h> void main ()
Putchar: It transmits a single character to a standard output device. This function accepts all types of characters even space, tab, blank. This function has also the limitation, that isn’t used for numeric operation and not displaying for loops.
Example:
# include <stdio.h> #include<conio.h> void main ()
2.5. Write short notes on “Format Specifier”.
Ans: Format specifiers are characters starting with % sign and followed
with a character. It identifies the data type that is being processed.
It is also knownas “conversion specifier”.
Some of character specifications used with format specifiers are:
Character Meaning
% First character
— (minus sign) Used for left justification.
w Used for specifying width of field.
24 A Refresher Manual of Computer Science for Grade XII
• (dot) Used for specifying decimal part.
p Used for specifying precision.
List of format specifiers symbol.
Data type
Integer
Unsigned integer %
Octal % o
Hexadecimal % x
Float % f
Float (scientific or exponential) e
character c %s
string
Example:
main ()
{
mt r;
float a;
r 2;
a = 12.562, 01547;
printf (“%d”, r); II prints 2 at initial position of screen
printf (“%lOd’, r); II prints 2 leaving 10 spaces. Righ justified.
printf (“%—d”, r); II prints 2 left justified printfC’%f’a); 1/ prints 12.56201547 printf(”%10.2f’a); II prints 12.56 leaving 10 spaces printf(’%e”a); II printsl.2562O1c + 01 printf (“%15.2e”,a) I/prints 1.25e + 01 leaving 15 space Right tified.
;1]
Format specfier symbol wed
24. What is a nested loop? Explain.
Ans: A loop inside the loop is called nested loop. Example:
for (i = 1; 1 < 5; ++i)
thr0=l;ji;i)
Inner printfC’%d’. I);
printf (“\n’);
Example:
#include<stdio.h>
#include<conio.h>
Computer Science 25
C Programmings — 1;0]
1. Write a program to calculate area and circumference of a circle
where radious of a circle is ipputed and define pi as constant.
Aits; #include<stdio.h>
#include<conio.h>
#define pi 3.14
void main()
mt r;
float a,c; printf(”Enter value of radious=’); scanf(’%d” ,&r);
a=pi*r*r; c=2*pi*r;
printf(”Area=%.2f\n” ,a); printf(”\nCircumsatances=%.2f”,c); getchO;
void main()
mt i,j;
for(i= 1 ;i<=5;÷±i)
forQ= 1 ;j<=i;++j) printf(’%d”,i);
printf(”\n”);
getchO;
Result
22
333
4444
55555
Result:
Enter value of radius =2
Area= 12.56
Circumferences= 12.56
26 A Refresher Manual of Computer Science for Grade Xli
Write a program that read principle, time and rate to calculate simple interest and total amount.
#include<stdio.h>
#include<conio.h>
void main()
mt p,t; float r,si,ta; printfC’Enter Principle=”); scanf(”%d” ,&p); printfC’Enter time=”); scanf(”%d” ,&t); printf(”Enter rate=”); scanf(”%f’,&r);
si=(p*t*r)I100
ta=si+p;
printfCSiniple Interest=%.3fn’ ,si); printfC’\nTotal Amount=%.3f’ ,ta); getchO;
Write a program to convert temperature in Fahrenheit (F) into centigrade (c). [F = 1.8 c + 321
#include<stdio.h>
#include<conio.h> Result:
void main () Enter temp infahereinheit—200
Result —93 .33
float C;
printf (“\n enter temp in fahrenheit =“); scanf (‘%d’, & f); c=(f—32)l1.8;
printf (“Result = %.2f”, c); getch C);
Enter princzple=5t700
Enter time = 5
Enter rate= 6
2.
Ans:
3.
Ans:
Simple Interest=1500.000 TotalAmount=6500. 000
{
mt f;
1-
Computer Science 27
Write a program asking cost of pen in paisa. Convert it into nearest rupees and paisa.
#include <stdio.h> #include <conio.h> void main (
I
mt paisa, rup, paisal;
printf (“Enter cost of pen in paisa =“); scanf (“%d”, & paisa);
rup = paisa/100; paisal = paisa% 100; printf (“Rupees = %d\n”, rup); printf (“Paisa = %d\n”, paisal); getch
5. Write a program to enter distance detween two cities in km and convert it into meter, centimeter,inch and ft. [inch=cm/2.54, m=km*1000, ft=inch/12, cm=m*1001
Ans: #include<stdio.h> #include<conio.h>
void main()
mt km,m,c; - I
float m,c,i,f printf(”Enter value of Kilometer=”); scanf(”%d” ,&km);
m=km* 1000; c=m*100; i=c/5.54;
f=i/12;
printf(”Meter=%d\n”,m); — printf(”\nCentemeter=%d\n” ,c); printf(”\nlnch=%.3f\n”,i); printf(”\nFeet=%.3f\n”,f); getchO;
4,
Ans:
Result:
Enter cost ofpen in paisa =205
Rupees =2
Pai.ca= c
Result:
Enter value of kilometer=200
Meter=200000
Centimeter=20000000
Inch =3610108.250
Feet —300842 .344


2 A Refresher Manual of Computer Science for Grade Xli
6. Write a program to enter 4-digit number and find sum of the first and last digit of the number. [e.g. 4567, sum = 4 ÷ 7
Ans: #include <stdio.h>
#include <conio.h>
void main ( )
{ .1
mt n, r, sum = 0;
printf (“Enter 4-digit number =“);
scanf (“%d’, &n); [i1
= n!1000 Enter 4-digit number= 1234
sum offirst and last digit=5 ]
sum sum + t; = n%1O; sum sum + r;
7. Write a program to supply length and breadth of a rectangle. Find out area and perimeter. Result:
Ans: #include <stdio.h> Enter breadth * length-4 6
void main ( ) ogle24
#include <conio.h>
Perimeter of a rectangle=2O
mt 1, b, a, p;
printf (“Enter breadth & length =“); scanf (“%d%d”, &b, &l);
a = l*b;
p=2*O+b);
printf (“Area of a rcctangle = %d\n”, a); printf (“Perimeter of a rectangle = %d\n”, p); getch ( );
}
printf (“sum of first and last digit %d”, sum); getch();
}
Computer Science 29
Ans: #include<stdio.h> #include<conio.h> void main ( )
total = eng + nep + math + acc + cscience; per = tot2l/5;
printf (“Total = %d\n”, total); printf (“Percentage = %.2f’, per); getch 0;
Write a program to read any two numbers through the keyboard and to perform simple arithmetic operations (i.e. addition, subtraction, multiplication & division) and display the results using scanf and printf functions.
#1 nclude<stdio.h>
Result:
#include<math.h>
void main(
mt a, b, sum, sub, mul; float div;
printf (“Enter any two numbers =“);
scanf(”%d %d”, &a, &b);
sum = a + b;
sub a — b;
mul = a’b;
8. Write a program to find total and percentage of a student whose marks are given below:
Subjects
Marks
English
65
Nepali
55
Computer Science
70
Math
80
Account
60
mt eng=65, nep=55, math=80, acc=60, cscience=70; mt total;
float per;
II
Ana:
Result:
Total=330
Percentage= 66
Enter any two numbers =5 2
Addition =7
Subtraction =3
Multiplication = 10
Division =3.500000
30 A Refresher Manual of Computer Science for Grade xii
div = a/b;
printf (“Addition =%d\n”, sum);
printf (“Subtraction =%d\n”, sub);
printf( Multiplication =%d\0”, mul);
printf ( Division %f\n”, div);
getch( );
10. Write a program to enter 4-digit number and find sum of them.
(i.e. 1234 = 1 .+ 2 + 3 + 4 = 10)
Ans: #include<stdio.h>
#include<conio.h>
void main( )
mt num, r, n, sum = 0;
print1 (“Enter 4-digit number =“);
scanf (“%d”, & num);
r = num % 10; Result:
num/10 Enter 4-digit number”2354
sum = sum + r; Sum of4-digit=14
r = n% 10;
n = n/10;
sum = sum + r;
r n% 10;
n = n/10;
sum = sum + r;
r = n% 10;
sum = sum + r;
printf (“sum of 4-digit = %d”; sum);
getch 0;
}
Computer Science 31
I I. Write a program to solve the quadratic equation ax2 + bx + c = 0,
‘,J— b ±b2 — 4ac
where x = 2a
Ans: #include<stdio.h>
#include<conio.h>
1 i i
#incluae<matn.n>
void main ()
inta,b,c;
float x, y;
printf (“Enter the value of a, b & c =“);
scanf(”%d %d %d”, &a, &b, &c);
x = pow ((— b + b*b — 4*a*c),0.5)12*a;
y = pow ((_b_b*b_4*a*c),0.5)12*a;
Printf (“Value of x = %fn”, x);
Printf (“Value of y = %fn”, y);
getch 0;
—
I. Write a program that accepts an integer and checks whether it is
divisible by 3 and 5 or not.
#include<stdio.h>
1 Result:
#inciucie<conio.h>
void mainO Enter an integer=15
mt a; Divisible by 3 and 5.
printf(”Enter an integer=”);
scanf(”%d”,&a);
if(a%3==0 && a%5==0)
printf (“Divisible by 3 and 5.”);
else
printf(”Not divisible by 3 and 5”);
getchO;
2. Write a program to enter any number and check whether the
entered number is odd or even.
AnN: # include<stdio.h> Result:
# include<conio.h> Enter any number=4
void main() The entered number is even.
32 A Refresher Manuai of Computer Science for Grade Xii
}
intn;
printf (“Enter any number = scanf (“%d”, &n);
if (n% 2 = = 0)
printf (‘The entered number is even”); else
printf (“The entered number is odd’); getchO;
3. Write a C program to read any number and check whether th entered number is divisible by 5 but nt by 11. [HSEB 2065
Ans: #include<stdio.h> #include<conio.h>
void main()
{
inta; printf(”Enter an integer=”); scanf(”%d”,&a);
Result:
Enter ay integer= 15
Divisible by 5 but not
by 11.
if(a%5==0 && a%1 !=O)
printf (“Divisible by 5 but not by 11”);
else
printf(”Not”); getchO;
4. Write a program to enter any character entered character is vowel or consonant.
Ans: # include <stdio.h> # include <conio.h>
void main ( )
char ch;
printf (“Enter any character =“); scanf (“%c’, ch);
if(ch = = ‘a’ ch = = ‘e ch = = ‘i’ ch = = ‘0’ ch = = H ch==’A’IIch==’E’IIch==’O’IIch==’I’IIch==’U’)
printf (“vowel”);
}
and check whether thi
{
Result:
Enter any character= e vowel
}
else
printf (“consonant”); getch ();
3. Write a program to enter any year and check whether the entered year is leap or not.
Ans: #include<stdjoh>
#include<conjo.h> /
void main ()
Result:
Enter year= 2000 [hap year.
mt year;
printf (“Enter year = ‘); scanf(”%d”, & year);
if(year% 400 = = 0 I year % 100! = 0 && year% 4 = = 0) printf (“Leap year”);
else
printf (“Not a leap year =“); getch();
( Write a C program to read any two numbers ,check first number is divisible by secondor nçt.
Aii: #include<stdjo.h> #include<conjoh>
void mainO
mi Pirst,second; irintf(”Enter any two numbers:”); scan f(”%d%d”,&first,&second).
[isuit: 7
Enter any two numbers =20 3 [yt divisible
i f(first%second==0)
printf (“First is divisible by second number”);
cisc
printf(”Not divisible”);
getchO;
Computer Science 33
{
Write a program to test whether the triangle is right angled or not, if three sides of triangle are given.
#include<stdio.h>
#include<conio.h>
mt a, b, C;
Result:
Enter the value of a, b, c =60 30 It is right angled triangle.
printf (“Enter the value of a, b and c
scanf (“%d %d %d”, &a, &b, &c);
if(a + b = =9011 a + c= = 90 lIb + c= = 90) printf (‘It is a right angled triangle.”); else
prmntf (“It is not a right-angled triangle”);
getchQ;
Write a program to enter any two numbers and find the greate number among these two numbers.
#include<stdio.h>
#include<conio.h> rResult
void main ()
I
mt a, b;
printf (“Enter any two numbers =); scanf (“%d %d”, &a, &b); -
if (a> b)
printf (“A is the greatest number”); else
printf (“B is the greatest number”);
getch ( );
9. A salesman gets commission on the basis of his daily sales an
the rate of commission is as follows:
Total sales made Commission rate
Below 5000 1.5%
Equal or more than 5000 3%
34 A Refresher Manual of Computer Science for Grade (ll
void main ( )
7.
Ans:
8.
Ans:
Enter any two numbers =20 3 A is the greatest number.
Write a program asking his total sales and calculate his commission amount.
Aita: #include<studjoh>
#include.econjoh> void main()
mt sales, totalsales, commission; printf (“Enter sales amount=”); scanf(”%d”, & sales); if (sales < 5000)
commission = sales * 3/100; totalsales = sales + commission; printf (“Totalsales = %d”, totalsales);
getch Q;
10 Write a program that asks cost of price(CP) and selling price(SP) and determine whether there is gain or loss.
[HSEB-2066}
Aiim: #include<stdjoh> #jncludecconjoh> void main()
mt CP,SP,loss,gamn; printf(”Enter value of CP and SP:”):
scanf(”%d%d”, &CP,&Sp); if(SP>CP)
gain=SP-CP;
printf(”GamnRs%d”,gain);
else
Computer Science
rResult: .
Enter sales amount =4000 Lrtal sales=4060
commission = sales * 1.5/100; totalsales = sales + commission; printf (‘Total sales = %d”, totalsales);
else
36 A Refresher Manual of Computer Science for Grade XII -
loss=CP-SP;
printf(”LossRs%d”l0ss);
}
getchO;
7Write a program of NTC to enter number of calls and find oul total, vat (10% of total), telecom service charge (10% of total i tsc) and total amount. The rate of total is given below:
Number of calls
number of call <=175
otherwise, number of call is more than 175 Ans: #include<stdio.h>
#include<conio.h>
void main()
mt nbc;
float total, vat, tsc, tarnt;
printf (“Enter total number of calls =
scanf (“%d”, &noc); if(noc <=175)
{
I
total = 200;
tsc = total * 101100;
vat = (total + tsc)* 10/100; tamt total + vat + tsc;
printf (“Total amount = %f”, tamt);
else
total = 200 + (nec — 175) 2; tsc = total * 10/100;
vat = (total + tsc) * 10/100;
tamt = total + vat + tsC;
printf (“Total amount = %f’, tamt);
getch( ); -
Ratu
minimum Rs. 200/ Rs. 2 per cal
I
Computer Science 37
12. Citizen are eligible to cast vote if they are 18 years or above and must be nepali. Write a program for this purpose.
AnN: #include<stdio.h> #include<conio.h>
void main (
mt age;
char nep;
printf (“Enter the age =
scanf(”%d”, &age); V
printf (“Enter ‘y’ if nepali citizen, otherwise enter ‘n’“) scanf(”% c”, nep);
if (age >= 18) V
if (nep = = ‘y’)
printf (“ok, you are eligible to cast vote”); else
else
printf (“Nepali citizen, not be other”);
printf (“You are not eligible to cast vote”); getch ( );
Write a program to enter any three numbers and one is greater among them.
#include<stdio.h #1 nclude<conio.h>
Void main(
jut a, b, c; V
printf (“Enter any three numbers =
scanf(”%d %d %d”, &a, &b, &c); V
if(a> b && a> c)
printf (“A is greater”);
else if (b>a && b>c)
printf (“B is greater”);.
cisc
printf(”C is.greater”); getch ( );
check whfth
Result:
Enter any three numbers —23 8 C is greater
38 A Refresher Manual of Computer Science for Grade XII
Write a program to enter any three numbers and find out th middle number.
#include<stdio.h>
#include<conio.h>
void main ( )
Result:
Enter any three numbers=2 3 8
B icrnid,Ji”nurnhr
mt a, b, C;
printf (“Enter any three numbers = “); scanf(”%d %d %d”, &a, &b, &c); if((a>b && a<c) (a < b && a> c)) printf (“A is middle number”); else if((b>a && b<c) II (b<a && b>c)) printf (“B is middle number”); else if ((c>a && c<b) j (c<a && c>b)) printf (“C is middle number”); else
getch ( );
Write a program whose input is a month entered as a numbi from 1 to 12 and whose output is the number of days in th month as [use if else or switch case]
Month input output
1,3,5,7,8,10,12 the month has 31 days
2 the month has 28 days or 29 days in leap yea
4,6,9,11 the month has 30 days
the month is not entered in our calender
other
Ans: #include<stdio.h> #includecconio.h> void main()
mt m; printf(”Enter any number”); scanf(”%d” ,&m);
if(m==1 II m==3 m==5 m==7 j m==8 m==IO j m==12) printf(”The month has 31 days”);
else if(m==2)
printf(”The month has 28 or 29 days”); else if(m==4 m==6 m==9 rn==1 1) printf(”The month has 30 days”);
14.
Ans:
Result:
Enter any number= 8 The month has 31 days
1
Write a program to test whether the entered character is alpha digit or alpha character or special character on the basis of given
ondition.
character
09
U -z
others
An. #include<stdio.h> Ni nd udecconio.h>
void main(
char ch; printf (“Enter scanf (“%c”, ch);
if(ch.> ‘1’ && ch <= ‘9’) printf (“Alpha digit”); else if (ch>= ‘a’ && ch <= ‘z’) printf (“Alpha character”); else
printf (“special chapacter”); getch( );
Write a program to find age group on the basis of age.
Age Group
1)10 Child
Teenage
Young
Old
10-19
19-40
Above 40 #include<stdio.h>
*include<conio.h> void main(
mt age;
printf (“Enter age of person =“); scanf (“%d”, &age); if (age <=10)
Computer Science 39
else
printf(”The month is not included in our calender”); getchO;
message
Alpha digit
Alpha character
Special characters
Result:
Enter character= 8 Alpha digit
character =“);
Result:
Enter age ofperson=15 Teenage
40 A Refresher Manual of Computer Science for Grade XII
printf (‘child”); else if (age < = 19) printf (“Teenage”); else if (age <=40) printf (“young”);
else -:
printf (‘old”); getch ( );
Write a program to input name, ciass and marks in five subject like english, math, nepali, account, computer science. Find to percentage, division, remarks. The condition of division is
percentage division
per> = 75 Distinction
per> = 60 AND per < 75 First
per> 45 AND per < 60 Second
per> = 35 AND per <45 Third
Below 35 Fail
Ans: #include<stdjo.h> #include<conio.h> void main(.)
char name [30];
mt class, eng, nep, math, acc, cscience, total; float per; printf (“Enter name of a student = “); scanf(”%s”, name);
printf (“Enter class =“); scanf (“%d”, &class);
printf (“Enter marks in english, nepali, math, account an csciencç =“);
scanf (“%d %d %d %d %d”, & eng, & nep, & math, & ao & cscience);
total eng + nep + math + acc + cscience;
per totall5;
printf (“Name = %s\n”, name); printf (“Class %d\n”, class); printf (“Total =%d\n”, total); printf (“Percentage = %dn”, per);
Computer Science 41
if(eng> = 35 && nep> = 35 && math> = 35 && acc> = 35 && cscience > = 35)
printf (“Remarks = passed\n”);
else
printf (“Remarks = failecfln”); -
if(per>=75)
printf (“Division = distinction\n”); else if (per> = 60)
printf (“\n Division = first\n”); else if (per> = 45)
printf (“\n division = second\n”); else if (per> = 35)
printf(”\n Division = third\n”);
else
printf (“\n Division = fail\n”); getch ( );
Write a program to input time in second and convert it into hour, minute and second.
Ai: #include.czscdio.h> #jncludecconjoh> /
void main( ) -
mt t, rn, s, h, r; printf (“Enter time in seconds”); scanf (“%d”, &t); ii(t <60)
printf (“hh:mm:%c{”, t);
else if(t >60 && t < = 3600)
m = t/60;
s t%60;
printf(”hh:%d:%d”, m, s);
else
ii t/3600; r. t%3600; in r/60;
— r%60; 42 A Refresher Manual of Computer Science for Grade XII
printf(”%d:%d:%d”, h,m, s);
getch Q;
} /
20. Write a program to enter a character from a-z or A-Z and convert it into lowercase and vice-versa.
Ans: #include<stdio.h>
#include<conio.h> void main()
{
}
char ch;
printf (“Enter a character =“); scanf (“%c”, ch); if(ch>64 && ch<91) printf (“%c”, ch+32);
else
printf (“%c”, ch-32); getch();
Write a program that accepts a single character & gives output as: [Use if-else or switch-case]
Character Color
rorR Red
White
Blue
No more primary color
Ans: #include<stdio.h> #include<conio.h>
void main()
char ch;
printi(”Enter a character:”);
scanf(”%c” ,ch); switch(ch)
{
case ‘r’: case
printf(”The color that you have choosen is red”); break;
case ‘w’: case’W’:
getchO;
J2, Write a program that accepts two integer and an operator (÷, -, , I or %). And the program should calculate the value as directed by the operator and display the result. [Use Switch- Case]
iii: #include<stdio.h> #include<conio.h> #nclude<process.h> void main ()
inta,b,c;
char ch;
printf (‘Enter any two numbers ‘); scanf (“%d%4”,&a, &b); printf (‘Enter your choice (+I_/*III%):_); scanf (‘%c”, ch);
switch (ch)
case
c a + b; break;
case
if(a>b)
C = a — b; else
c=b-a;
break;
case
c = a * b; break;
case ‘I’
Computer Science 43’
printf(”The color that you have choosen is white”); break;
case ‘b’: case’B’:
printf(”The color that you have choosen is blue”);
break; .
default:
printf(’Please choose a proper character “);
Result:
Enter a character=C
21.
w or W
b or B
Other
{
Result:
Enter a character=r•
The color that you have chosen is red.
[44 A Refresher ManuJ of Computer Science for Grade Xli
c = a/h; . break i
‘0/ ‘/
case /0/.
defa,s1t:
/printf (“You have to type the given options”);
// exit (o);
printf(”Result:%d”,c);
/getch ( );
23. Write a menu driven program which has the following option
I .Perimeter of circle
2.Perimeter of rectangle
3.Perimeter of triangle Ans: #include ‘conio.h”
#include “stdio.h”
mt main()
I
mt choice;
printf(”Enter choice 1 for perimeter of circle\n”); prmntf(”Enter choice 2 for perimeter of rectangle\n”); printf(”Enter choice 3 for perimeter of triangle\n”); perintf(”Enter your choice:\n”); scanf(”%d”,&choice);
switch(choice)
{
case 1:
{
I
float rad, per; printf(”\nEnter the radius of circle”); scanf(”%f’ ,&rad); per=(2*22*rad)17; printf(”\nThe perimeter of circle is: %f’,per); break;
mt b,l,per;
printf(”\nEnter the breadth of rectangle:\t”); scanf(”%d” ,&b);
case 2: getchO; return 0;
mt a,b1c,per; print(”\nEnter the sides of the triangle\n”); printjf(”\nEnter the first side:\t”); scan(”%d”,&a); prinf(”\nEnter the second side:\t”); scasf(” %d”, &b); pri’uf(”\nEnter the third side:\t”);
per=a+b÷c;
prinrf(”\nThe perimeter of triangle is: %d”,per); break;
Write a program to find sum of 1 to 100 numbers.
#includecsrdjoh>
#irIcIude<conioh>
void main()
mt n, sum = 0; for (n = 1; n < = 100; ÷÷n)
sum = sum + n;
printf (“sum =%d”, sum); getch ( );
printf(” scanf(”%d”
per 2* printf( “\n break;
‘the length of rectangle:\t”);
}
case 3:
perimeter of rectangle is: %d”,per);
I
default:
I
printf(”Wrong choice”);
;1]
ograrnmings3;0] 46 A Refresher Manual of Compute’r Science for Grade XII
Computer Science 47
2. Write a ‘C’ program to print all fromAtoZ. ‘,
Ans: #include<stdio.h> #include<conio.h>
void main()
char chi;
for (chi = ‘A’; chi <= ‘z’; chi = chi 1)
printf (“%d\t”, chi);
getch();
3. Write a program to compute factorial for a given number i where n is a non-negative integer,[n!=1*2*34 (n1)*n].
Ans: #include<stdio.h> #include<conio.h>
void mainO
{
mt n=1,fact=l,num; printf(”Enter a number:”); scanf(”%d”,& num);
if(num<O)
printf(”Error.Plz enter positive only.”); else if(num==O)
printf(”The factorial of the given no is:%d”,fact);
else
{
while(n<num)
I
fact=fact*n;
n=n+l;
getchO;
}
printf(”The factorial of the given no is:%d” ,fact);
4. Write a program to print the series 1,5,9,13 upto 10th terfl Ans: #include<stdio.h>
#include<conio.h>
void main()
mt cnt=1,i; printf(”%d\t” ,cnt);
for(i=O;i< 1 0;++i)
{
cnt=cnt+4;
printf(”%d\t”,cnt);
I
getchO;
Write a program to calculate the area of n number of circle where radius of circle is input by user.
A ,i,: #include<stclio.h>
#i nclude<conio.h>
void mainO
mt n,i,r; float a;
printf(’Enter number of circle=”); scanf(”%d”,&n);
for(ir 1
(. Write a program to find sum of odd and even numbers upon 1-100 numbers.
Aii: #include<stdio.h> #include<conio.h>
void main( )
the ASCII codes for aiphabe
printf(”Enter value of radious of circle=”); scanf(”%d” , &r);
a=3.1416*r*r;
printf(”Area%fn”,);
getchO;
mt n, esum = 0, osum = 0;
for (n = 1; n < = 100; ÷+n) I
{
I
if(n% 2 1) osum = osum + n;
else
esum = esum + n;
printf(”n sum of odd numbers = %d”, osum); printf(’\n sum of even numbers = %d”, esum); getch();
7. Write a C program to read any number and entered number is palindrome or not.
Ans: #include<stdio.h> #include<conio.h>
void main(
{
mt n,num,rev=0,r; printf(”Enter any number”); scanf(”%d”,&num);
n=num; while(num!=0)
{
r=num% 10;
rev=rev”lO+r;
num’numf 1 0;
if(n==num)
printf(”The enterd number is palindrome”);
else
check whether the
printf(”The entered number is not palindrome”); getchO;
8. Write a program to check whether a number is Armonstrong or not. [Armonstrong no: - An Armonstrong number is that whose sum of cube of digits is equal to number itself. e.g. 371 33 + 73 +ij
Ans: #include<stdioh> #include<conio.h>
void main()
mt i,n,sum=O,r; printf(”Enter any nuber=”); scanf(”%cl”,&n);
i=fl;
do{
r=n%10;
sum=sum+r*r*r;
n’nhlO;
I while(n>0);
if(sumzj)
printf(”Armonstrong%d\n” ,sum); else
printf(’Not armonstrong”); getchO;
Write a program to display fibonacci series upto 10 terms. Ie.g.0112358 I
i: #include<stdjoh>
#include<conjoh>
void main()
mt a, b, c, j; printf (“\n theeries’); a = 0;
b = 1;
printf (“%d \t%d\t”, a, b); for(j = 0;j <10;j+ +)
{
C = a + b;
printf (“%d\t”, c);
a = b; b = C;
getch ();
Write a ‘C’ program to read positive integers less than 20 and
4Iisplay its multiplication table.
lliriciude<stdjoh>
Iliiiclude.cconjoh>}
I
mt n, i, mul;
printf (“Enter no:-”); scanf (“%d”, &n); if (n> 20)
else
I
for(i=1;i<10;i++)
{
mul=n*i;
printf (“\n %d X %d = %d’, n, i, mul);
getchO;
11. Write a program to input an integer number and checks wheth
it is prime or not. [HSEB-206
Ans: #include<stdio.h> #include<conio.h>
void main ( )
I
mt a, n, j;
printf (“Enter any number =“); scanf (“%d”, &n);
a=n;
for(j=2;j<n;j+÷)
{
I
if(n%j==0) I
if (a==j)
printf (“\n Prime no=%d “, a);
getchO;
printf(’Not prime”); break;
12. Write a program to calculate the value of a raised to b. [e.g. 2 = 8]
Ans: #include <stdio.h> #jnclude <conio.h>
void main ()
mt a, b, c = 1, i;
printf (“Enter the value of base =“); scanf (“%d”, &a);
printf (“Enter value of exponent =“); scanf (“%d”, &b);
for Ci = 0; i < b; ++i)
C = c’a;
printf (“Power = %d”, c); getchO;
13. Write a program to accept any integer and print it in reverse order. For example,if number is 542 then reverse order is 245.
Ans: #include <stdio.h> #include <conio.h>
void main ()
mt n, r;
printf(”\n enter any number :-“); scanf(”%d”, &n);’
while (a > 0)
{
r = n%10;
printf (“%d”, r);
n n/10;
I
getchO;
14. Write a program to accept any number and find sum of digit of that number. [e.g. 275, sum = 2 + 7 + 5]
Ans: #includc <stdio.h> #include <conio.h>
void main C)
void main ()
goto x;
{
I
I
mt n, sum = 0, r; 52 A Refresher Manual of Computer Science for Grade XII
}
printf (“Enter any number =“); scanf (“%d”, &n); while (n> 0)
{
}
r = n%10;
sum = sum + r;
n = nIlO;
printf (‘Sum of digit of number =%d” ,sum); getch 0;
15. Write a program to read ‘n’ different numbers and picks largest of them.
Ans: #include <stdio.h> #include <conio.h,
void main ()
}
mt n, max = 0, no, count; printf (“Enter how many numbers “); scanf (“%d\n”, &n);
for (count = I; count < = n; count +
{
printf (“Enter the number =“); scanf (“%d”, &no); if(no > max)
max = no;
printf (“\n maximum ro %d”, max); getchO;
16. Write a program to enter a decimal number and converts it into binary number.
Ans: #include <stdio.h> #include <conio.h>
void main ()
mt p , t = 0, n,r;
printf (“Enter decimal number =
scanf(”%d”, &n); while (n! = 0)
r
t = t + (r * p);
n=n/2;
p p*lO;
printf (“Binary number = %d”, t); getchO;
17. Write a program that reads 10 integer value and prints the total of all non negative numbers in the list.
Ans: #include<stdio.h> #include<conio.h>
void main()
mt i,n,sum=0; for(i= 1 ;i<=10;++i)
{
printf(”enter no=”); scanf(” %d” ,&n);
if(n>0)
sum=surn+n;
printf(”sum=%d” ,sum); getchO;
(8. Write a program to enter highest and lowest number and find the sum of lowest to highest number.
Ans: #include <stdio.h> #include <conio.h>
void main ()
mt high, low, sum = 0, temp, num; printf (“Enter a high number =“); scanf ( /od , &high); printf (“Enter a low number =“); scanf (“%d”, &low);
if (low> high)
Computer Science 53
}54 A Refresher Manual of Computer Science for Grade XII
}
temp = low; low = high; high = temp;
for (num = low; num < = high; num + sum = sum + num;
printf (“High no is %d\n”, high); printf (“Low no is %d\n”, low); printf (“Sum of high & low: %d”, sum); getch();
19. Write a program to read ‘n’ numbers,count +ve and -ye numbers.
Ans:
#include<stdio.h> #include<conio.h> void main()
mt n,no ,i,pcount=O, ncount=O;;
printf (“Enter the value of n =\n”); scanf (“%d”,&n);
for (i =1;i<=n;i++)
printf (“Enter numbers :
scanf (“%d”,&no);
if(no>O)
pcount = pcount + 1; else
ncount = ncount + 1;
printf (“Total number of ÷ve no. = %d\n”, pcount); printf (“Total number of-veno. = %d”, ncount);
getchO;
20. Write a program to reserve any given integer number and als find their sum.[Example: if number input=294, then outp must be 492 and sum=15].
Ans: #include<stdio.h>
#jncjudecconjoh> void main()
mt n,r,sum=O; printf(”enter any no=”); scanf(”%d “,&n);
while(n>O)
{
}
r=n%1O;
printf(”%d”,r);
n=n/1O;
sum=sum+r;
prmntf(”sum%d”,sum);
getchQ;
Write a menu driven program which has following options:
1. Factorial number
2. Prime or not
3. Oddoreven
4. Multiplication table
5. Exit IIs: #include <stdio.h>
#include <process. h>
void main ()
mt choice, num, i; long mt fact; printf (“\nn 1. Factorial number”); printf(”2. Prime \n”); printf (“3. Odd or evenn”); printf (“4. Multiplication Table”); printf(”5. Exit \n”); printf (“Enter your choice (1/2/3/4/5):-”); scanf (“%d”, &choice); switch (choice)
case 1:
printf (“Enter number =“); scanf (“%d”, &num);
Computer Science
55
1. 56 A Refresher Manual of Computer Science for Grade XII Computer Science 57
fact = 1; default:
for (i = 1; i <= num; i + +) printf (“You are not allowed to type other);
fact = fact * i; exit (0);
•printf (“Factorial no % id’, fact); }
break; getch ( );
case 2:
printf (“Enter number =“); 22. Write C programs to display the following series:
scanf(”%d”, &num); 1+l!x+11x2+1/x3+ +1Ix
for (i = 2; i < num; i + +) Ans: #include<stdio.h>
{ #include<conio.h>
if (num % i = = 0) void main()
{ {
printf (“\n Not Prime”); mt n,i;
‘break; flaot sum=1,term=1,x;
} printf(”Enter value of n and x:”);
if (i = = num) scanf(”%d%d”,&n,&x);
printf (“\n Prime number”); for(i= 1 ;i<n;++i)
break;
term=term*1/x;
case3: sum=sum+term;
printf (“Enter number =“);
scanf (“%d”, &num); printf(”Sum%.2f’,sum);
if(num%2 = = 0) getchO;
printf (“\n even number”);
else
printf (“\n odd number”); break;
• case4:
printf (“Enter no =“); scanf(”% d”, &num); for(i= 1;i<= 10;i+-i.)
{
V V mt mult num * i;
printf(”\t %d X %d %d n”, num, i, mult);
break;
case 5
exit (0);
;1] C Programmirigs—4_(Nested Loop);0]
Write a program to print multiplication table of first 10 natural number.
Ans: #include<stdio.h> #include<conio.h>
void main()
mt i,j,c;
for(i= 1 ;i<= 1 0;++i)
for(i= 1 ;j<=10;++j)
C=i*j;
printf(%d*%d=%d\t”,i,j,c); 58 A Refresher Manual of Computer Science for Grade XII Computer Science 59
printf(”\n’); 4. Write a program to generate the following:
} 1
getchO; 22
} 333
4444
2. Write a program to display factorial number of first 10 natur Ans: #include<stdio.h>
number.
I. #include<conio.h>
Ans: #incluae<stalo.n>
void mainQ
#lncluae<conlo.n>
void main()
mt 1,);
• . • for(i=1;i<=5;÷+i)
mt
for(i=1;i<=10;÷+i) . .
forO1;j<=i;++j)
f=i; • printf(’%d’,i);
for(j=m;pO;--j) }
ff*.. printf(’\n’);
getchO;
printf( %d=%d\n ,i,f);
getchO; 5. Write a program to display the following series:
1
22
3. Write a program to display prime number upto 500 numbers. 3 3 3
Ans: #include<stdio.h> 4 4 4 4
#include<conio.h>
void main() Ans: #include <stdio.h>
#include <conio.h>
t voidmain()
in l,J,
for(i=2;i<=500;++i)
{ mntn,a,J;
for(a=1;a<=5;a+÷)
forO=2;j<=m;+-m-j) {
if(i%j--0) for Q 0; j < = 5-a ; i +
—— printf C
break; •
for(j=1;j<=a;j++)
• . . printf (%d “, a);
if(m==;) .
prmntf ( \n );
prmntf( %d\t ,i); }
getch ();
getchO; }
}60 A Refresher Manual of Computer Science for Grade XII
Computer Science 61
6. Write a program to generate the following:
1
12
123
1234
12345
Ans: #include<stdio.h> #include<conio.h> void main()
7.
{
mt i,j; for(i=1 ;i<=5;++i)
for(j= 1 ;j<=i;++j)
I
printf(” %d” ,j);
printf(’\n);
getchO;
Write a C Program to display ythe following:
55555
4444
333
22
1
Ans: #include<stdio.h> #include<conio.h>
void mainO
{
mt i,j; for(i=5;i>=0;--i)
{
I
for(j= 1 ;j<=i;++j)
printf( %d” ,i);
priritf(\n”);
getchO;
V.,
8. Write a program to display the following table:
10 20 30 40
20 30 40 50
30 40 50 60
4050 60 70
Ans: #include<stdio.h> #include<conio.h>
void main()
I
mt i,j; for(i=0;i<=4;÷+i)
{
I
for(j= 1 ;j.<=4;+÷j)
printf(%d\t,(i+j)* 10);
prmntf(”\n”);
getchO;
9. Write a C program to display the pyramid of numbers for a given number.
1
121 *
1 23 21
1 2 34 32 1
123454321
1 2345654321
12 345 67654321 Ans: #include<stdio.h>
#include<conio.h>
void main()
mt n,a,j,k;
printf(”Enter a number to form a pyramid:”); scanf(”%d”,&n);
printf(”\n\t\n\t”);
for (a = 1; a < =n; a ÷
for(j = 1;j<=n-a;j +÷)
I62 A Refresher Manual of Computer Science for Grade XII
}
printf (““);
for (k=1 ;k<=a;k++) printf (“%d’, k);
for (k=a-1 ;k>0;k--) printfC’%d ‘, Ic);
printf (“\n\t\t”);
}
getch Q;
10. Write a program to display the following series
1
23
45 6
78 9
11 12 13 14 15 [i.e.Floyd’s Theorem]
Ans: #include<stdio.h> #include<conio.h>
void main()
{
mt i,j=l,k; {
for(i= 1 ;i<=5;+-i-i)
for(k I ;k<=i;j++,k÷+) printf(” %dt’,j);
sumsum+ 1;
printf(”\n’); printf(”%d\t”,sum);
getchO; }
printf(”\ntt);
}
}
getchO;
}
Computer Science 63
What is an array? Write down its syntax with examples.
Ans: An array can be defined as a set of finite number of homogeneous elements or data items.It means an array can contain one type of data only,either all integers,all characters,all floating point etc.The individual data items are represented by their corresponding array elements(i.e.first data item is represented by first array element,second data item is represented by second array element and so on). The individual array elements are distinguished from one another by the value that is assigned to a subscript.
Declaring of an array
mt a[5];
Where mt specifies data type of elements array,”a” is the name of array and number specified inside the square brackets is number of elements an array can stores.
Followings are some of the concept to be remembered about arrays:
a) The individual element of an array can be accessed by specifying name of array,followed by index or subscript inside square brackets.Example:int 45];
b) The first element of array has index zero[0J.It means first element and last element will be specified as a[0] and a[4] respectively.
c) The elements of array always be stored in consecutive memory locãtionq.
d) The size of array is given by (Upperbound-lowerbound)+1
(4-0)+ 1 =5.
where O1owerbound and 4=upperbound.
e) Arrays can be read or written through loop.If we read a one- dimensional array,it requires one ioop for reading and writing.
If we are reading or writing two-dimensional array it would require two loops.Sirnilarly array of n dimension would require n loops.
There are two types of array and these are
(a) One-dimensional array
(b) Two- dimensional array
(a) One dimensional array: It consists only either rows or columns.
syntax> data — type array_name [expression];
e.g. mt marks [500];
I’
10
Or, #include<stdio.h> #include<conio.h> void main()
mt i,j,sumo; for(11 ;i<5;++j)
{
for(j0;j<i;++j)
{
}64 A Refresher Manual of Computer Science for Grade XIJ
Computer Science 65
char sentence [100];
float percentage [8]; etc.
(b) Two dimensional array: It consists both rows and columns. syntax> data — type array name [expression 1] [expression2];
e.g.
mt matrix [5] [51;
char name [10] [30]; etc.
Differentiate between one-dimensional and two-dimensional array.
Differentiation between one-dimensional and multi-dimensional array:
2.
Ans:
name);
printf (“Age:%d”, age); getch();
scanf(”%d”,&matrixa[i] [ii);
//Displaying data
for(i=0;i<2;÷+i)
for(j=0;j<2;++j)
printf(”%d\t”,matrixa[i] [j]); printf(”\n”) ;}
getchO;
- One-Dimensional array
Two-dimensional array
a)
Only one subscript is used in
Two subscript is used in two-
one-dimensional array
dimensional array.
b)
c)
Syntax>data_type array_name [subscript];
Examples:
char name[20];
mt marks[5]; etc
Here, subscript is used to denote either rows or columns.
Only one loop statement is used to create or retrieve array elements,
Syntax>data_type array_name [subscript 1] [subsc ript2];
Examples:
mt marks[100][5];
mt matrix[5][5]; etc. Here, subscriptl is used to denotes rows and subscript2 denotes columns. Two looping statements are used to create or retrieve array elements, i.e. first loop for rows and second loop for columns.
d) Example: Display name & age of a student. #include <stdio.h> #include <conio.h> void main ()
{
char name [20]; mt age; printf (“Enter name:”); gets (name); printf (“Enter age \n”); scanf(”%d”, &age);
— printf (“\n Name :%s”,
Example: Display elements of a matrix:
#include <stdio.h> #include <conio.h> void main ()
{
mt
matrixa[2] [2],i,j;
printf(”Enter elements of a matrix:”):
for(i=0;i<2;++i)
{
for(j=O;j<2;++j)
,
3. What is a string?Explain,how string is declared?
Ans: A string is a group of characters of any length. The string enclosed within double quotation marks is known as a literal. For example, “Hello” is literal. We can use such strings in our programs to display various kinds of messages on the screen. The strings can be stored and manipulated as array of characters in C and C++. The last character in a string is always ‘\0’, a null character. For example, the string “PROGRAM” can be stored in an array as
0 1 2 3 4 5 6 7
items RIO I GIRIAIMI\0 I
The string requires total 8 locations of array item: seven for the alphabets in the string PROGRAM and one for the null character. The array jj can be declared as:
char item[8];
Other examples of array declarations are:
mt x[25];
char name [20];
float sal[15];
Array declarations that include the assignment of initial values are
mt x[5] = { 56, 42, 90, 65, 55 };
x[0] x[1] x[2] x[3] x[4]
or char text[61 = { “today”}; 66 A Refresher Manual of Computer Science for Grade XII
Computer Science 67
;1] C Programmings—5;0]
Write a program to display the following numbers.
3,56,76,5,90
Ans: #include <stdio.h> #include <conio.h>
void main ()
mt i,num[5]={ 3,56,76,5,90};
printf(”List of number\n”); for(i=0;k4;++i)
printf(”%d” ,num[i]);
4.
Ans:
(ii) Two-dimensional array:
data_type array_name[expl] [exp2]; e.g. char name [5] [25]; It contains rows & columns.
};
union user_defined_name
van, var2
syrpoqs4dnt {
éhar name [20]; mt age;
union student one;
Example : Display name & age:
#include <stdio.h> #include <conio.h> void main ()
{
char name [20]; mt age; pnintf (“Enter name:”); gets (name); printf (“Enter age \n’); scanf (“%d, &age); pnintf (“\n Name :%s”,
name);
printf(’Age:%d”, age); getch.(j; ,
}
Example: Display name & age:
#include <stdio.h> #include <conio.h> void main ()
{
union student
{
char name [20]; mt age;
} one;
printf (“Enter name scanf (“%s”, one.name); printf (“\n Enter age:”); scanf (‘%d”, &one.age); printf (“\n Name : %s”,
one.name);
printf (“Age :%d”, one.age); getch();
char text[6] = { ‘t’‘o’‘d’‘a’‘y’‘\0’ };
text text text text text text
[0] [1] [2] [3] [4] [5]
intA[4][3] = { 5, 2, 7,
3, 9, 6,
1, 7, 8
9, 2, 3};
mt list[5][10] = { “Ram”,
“Shyam”,
“Han”,
“Gopal”,
“Rampayri” I;
Write differences between array and unions with syntax.
Differentiation between structure and unions:
Array
Union
Array is the collection of
Union is a collection of
data items which will have
hetrogeneous data types
the same name.
Each element has specific
Each element has no specific
memory space
memory space but space
allocated for largest elementis is
utilized by other sized element.
Keyword is not required to
Keyword is required to declare
declare array,
union
Array has its type and these
Union has no type
are:
.
(i) one dimensional array
‘
(ii) multi dimensional array
The syntax of array:
Syntax of union:
(i) One dimensional array:
union user_defined_name
data_type array_name [size
{
of array];
data_type member 1;
It consists only rows or
data_type member2;
columns
i.e. char name [20];
data_type
membern;
getchO: 68 A Refresher Manual of Computer Science for Grade XII Computer Science 69
2. Write a C program to read age of 100 person from keyboard, 4. Write a program to store ten different constant variables in any
display it in proper format. array and print out the greatest number. [HSEB-2064]
Ans: #includeestdio.h> Ans: #include <stdio.h>
#include<conic,.h> #include <conio.h>
void main () void main ()
mt i,num[100j; mt a[lOj={100,1,23,43,56,21,80,54,67,2};
I/Giving input from keyboard jflt i, large;
for(i=0;klOO;++i)
{ large. a [0];
for(i=0;i<10;i+÷)
printf( Enter age of 100 persons: .
scanfC’(”%d”,&num[il);
if (large < a [i])
large = a[i];
I/Displaying age of 100 persons printf (“\n largest no = %d”, large);
printf(”List of number\n”); getch ();
for(i=0;i<100;++i)
printf(”%d” ,num[i]);
getchO: 5. Write a ‘C’ program to read salaries of 200 employees and count
the number of employees getting salary between 5000-10000.
[HSEB-2062j
3. Write a C program to read 10 numbers and print them in reverse Ans: #include <stdjo.h>
order #include <conio:!i>
Ans: include<stdio.h> void main ()
#include<conio.h>
void main() mt count = 0, salary [200], i;
II Reading salary of 200 employees
for (i= 0; i< 200; i+
mt num[10],i;
for(i=0;klO;i+-m-)
printf ( Enter salary : );
1 ,, scanf (“%d’, & salary [i]);
printf( Enter a number: );
scanf(”%d”,&num[iD; ii counting number of employees getting salary between
//5000 - 10000
printf(’The number in reverse order are: for (i = 0; i < 200; i +
for(i=9;i>0;i--) {
printf(”%d\n\t\t\t\t”,num[il); if (salary [ij > 5000 && salary [ii < 10000)
getchO; count + +;
1 }70 A Refresher Manual of Computer Science for Grade XII
Computer Science 71
- printf (“Total number of employees getting salaries between 500-10000 = %d”, count);
getch();
The marks obtained by a student in a 7 different subjects are entered through the keyboard. The student gets a division as per the following rules:
Percentage greater or equal to 60 First division Percentage between 45 and 59 Second division Percentage between 35 and 44 Third division
Percentage less than 35 Fail
Write a program using C language to process result of all’ students based on specification stated above.
#include <stdio.h> #include <conio.h> void main ()
{.
char name [20];
mt i;
float x [71, per, total = 0; printf (“Enter name =“); scanf (“%s”, name); for (i= 0; i< 7; i+
printf (“Enter mark of a subject =“); scanf (“%f’, &x [i]);
total = total + x [ii;
printf (“\n\n”); per = totai/7;
printf (“Name %s\n”, name); printf (“Total = % f\n”, total); printf (“Percentage = %fn”, per);
if (per>60)
printf (“First division\n”); else if (per> = 45)
printf (“Second division\n”); else if (per> = 35)
printf (“Third division”);
I
lse printf (“Fail\n”); getch ();
7. Write a program using C language to read the age of 100 persons and count number of persons in the age group between 50 and 60. Use “For” and “Continue” statements. [HSEB 2061]
Ans: #include <stdio.h> #include <conio.h>
void main ()
mt age [100];
mt i, count 0;
II Reading the age of 100 persons for(i=0;i<100;j-i--i-)
printf (“Enter age of a person :“); scanf(”%d”, & age [i]);
II Comparing age group between 50 & 60 for (i= 0, i< 100; i+
if (age [I] > = 50 && age {i] .çi6O)
count + +; continue;
printf (“Total number of persons in the age group between 50 and 60 are: %d’, count);
getch.Q;
8. Write a program to find whether the given number is palindrome or not.
Ans: #include <stdio.h> #include <conio.h>
void main ()
{
mt a[10],num,i=0,result=O,n; printf(”Enter the number:”); scanf(”%d”,&n);
num=n;
6.
Ans:
4•. *
I72 A Refresher Manual of Computer Science for Grade Xli
Computei Science 73
while(num!=0)
result=result* 10; a[i]=num%1O; num=num/ 10; result=result÷a[i];
9. Write a ‘C’ program to input greatest and smallest number.
Ans: #include <stdio.h> #include <conio.h>
mt n, i, max, a[100], mm; printf (“How many nos ?“); scanf (“%d”, &n);
II Reading numbers for(i=0;i<n;i++)
printf (“Enter numbers :“); scanf(”%d”, &a [ij);
/1 Finding the greatest and smallest number. max=aIO];
mina[0];
for(i=0;i<n;i++)
{
if (a [ij > max) max = a[iJ;
else if( a[i]<min)
mm = a[i];
}
printS (“The greatest number %d\n”, max); printf (“The smallest number = %d”, mm); getch 0;
10. Write a program, which reads marks of N studeilts in an array and add a grace of 10 marks to every element of the array.
Ans: #include<stdio.h> #include<conio.h>
void main()
intn,i,mark[ 10] ,sum[1 0]; printf(”Enter how many students:”); scanf(”%d” ,&n); printf(”\n\n”);
for(i=0;i<n;ii-÷)
printf(”Enter mark:”); scanf(”%d”,&mark[i]); sum [i]=mark[i] + 10;
printf(”\n\n”);
for(i=0;i<n;i+÷)
printf(”The mark of studit after adding a grace 0f 10 marks:%d\n”,sum [ii);
getchO;
11. Write a program to enter ‘n’ numbers into one dimensional array and sort and display them in ascending order.
[I4SEB-2065]
Ans: #include <stdio.h>
#incluçle <conio.h>
#define MAX 500
void main ()
mt a [MAX], i, j, n, temp; printf (“How many numbers ?“); scanf (“%d”, &n);
/1 Entering set of numbers for(i=0;i<n;i++)
if(result==n)
printf(”The number is palindrome”); getchO;
}
void main ()
‘n’ numbers and find out the
[HSEB 2O62]
}
else
}74 A Refresher Manual of Computer Science for Grade XII
Computer Science
printf (“Enter numbers =“); scanf (“%d”,& a [ij);
II sorting in ascending order for(i=O;i<n;i++)
{
I
for (j = i+1; j < n; j +
if(a [ii> a [ii)
temp = a[i]; a[il=a[j];
a [ji = temp;
{ I
I
printf (‘Sorted array\n”); for(i=0;i<n;i÷+)
printf (“%d\t’, a[i]); getch();
12. Write a program to read a set of ‘n’ numbers from the standard input device and to sort them in descending order.
Ans: #include <stdio.h> #include <conio.h>
void main ()
mt a [1001, i, j, n, temp;
printf (“How many numbers ?“); scanf (“%d”, &n);
II Entering set of numbers for (i = 0; i <n; i +
I
printf (“Enter numbers =“); scanf (“%d” ,&a [ii);
II sorting in ascending order for(i=0;i<n;i++)
{
for (j = i-i-i; j <n; j +
13. Write a C program that reads name and mark of 10 different students and prints them in tabular format.
Ans: #incjude<stdjo.h> #incjude<conio.h>
void mainO ( 4J’ (,J3 2i
char name[1 0] [101; ‘ mt mark[10],i;
for(i=0;i< 1 0;i++)
{
printf(”Enter name:”); scanf(”%s”, &name[i]); printf(”Enter mark:”); scanf(”%d” ,&mark[i]);
I
printf(”\nName\tMark\n”);
printf(”\n \t for(i=0;i< 1 0;i++) printf(”%s\t%d\n”,name[j] ,mark[j]);
getchO;
H
75
if(a [ii <a [jJ)
temp =
a [iJ a[j];
a [j] = temp;
printf (“Sorted array\n”); for (i = 0; i < n; i +÷) printf (“%d\t”, a[iJ); getch();76 A Refresher Manual of Computer Science for Grade XII
Computer Science 77
14. Write a program to input names of ‘n’ number of students and
sort them in alphabetical order. [HSEB-20621
Ans: #include <stdio.h>
#include <conio.h>
#include <string.h> void main ()
char name [100] [100], temp[100]; mt i, j, n;
prmntf (“Enter number of students =“); scanf(”%d’, &n);
// Data putting for n students for(i=0;i<n;i++)
printf (“Enter name :“); scanf (‘%s”, name [ii); fflush (stdin);
// sorting methods for(i=0;i<n;i-’-+)
{
for (j = + l;j <n;j +
{
I
if(strcmpi (name [ii, name [j]) > 0)
strcpy(temp, name [ii); strcpy (hame [i], name U]); strcpy (name [j], temp);
II Printing sorted list in alphabetical order for(i=0;i<n;i++)
printf (“%s\n”, name [1]);
getch();
15. Write a C program to read anme and address of 5 different students,sort them in alphabetical order.
Ans: #include<stdio.h> #include<conio.h> #includecstring.h> void mainO
char name[5] [80] ,add[5] [80] ,temp[80],temp 1 [80]; mt i,j;
printf(”enter name and age:”); for(i=0;i<5 ;i++) scanf(”%s%s” ,name[i] ,add [i]);
for(i=0;i<5 ;i++)
for(j=i+ I ;j<5;j++)
if(strcmp (name [i] ,name [3]) >0)
strcpy(temp,name[i]);
strcpy(name [i] ,name[j]); strcpy(name[j] ,temp);
strcpy(temp 1 ,add[i]);
strcpy(add[i],add[j]);
strcpy(add [j] ,temp 1);
printf(”The result\n”); for(i=0;i<5 ;i÷+) printf(”%s\t%s\n” ,name[i] ,add[i]);
getchO;
16. Write a C program to read elements of any two matrices and sum of them.
Or,
Write a program to add two matrices.
Ans: #include <stdio.h> #include <conio.h>
void main ()
{
I
[HSEB 2065]
I{
{
for(j=O;j<5;j+ +) scanf (“%d”, &a [ii [jI);
for(j=O;j<5;j++)
scanf (“%d”, &b[i] [jI);
II Finding sum of matrices for (i= 0; i< 5; 1+
for (j 0; j <5; j+ +) c [ii [j] = a[i] [j] + b[i] [ii;
II Printing the results for (i= 0; 1<5; ii-
{
for(j=0;j<5;j++)
printf (::%t” c[i] [jI); printf( \n );
getch();
I
for(j =0;j <n;j ÷+) scanf(”%d”, & mat [iJ [3]);
II Finding row sum of matrix for(i0;i<m;i÷+)
{
for(j =0;j<n;j+÷) printf(”%d\t”, mat[iJ [3]); printf (“%d\n’, rsum [ii);
for(j 0;j <n;j+÷)
printf (“%d \n”, csum[j};
getch 0;
78 A Refresher Manual of Computer Science for Grade Xli mt a[5][5], b[5][5], c[5] [5], i, j;
II Entering the elements of matrix A Printf (“Enter the elements of matrix A = “); for (i= 0; i< 5; i+
II Entering elements of a matrix for(i=O;i<m;i+÷)
I
j
II Entering the elements of matrix B
printf (“Enter elements of matrix B =“);
for (i= 0; i< 5; 1+
Computer Science 79
r sum [i] = 0;
for (j = 0; j n; j +
rsum [i] = rsum [i] + mat [ij [j];
II Finding column sum of matrix for(j=0;j<n;j+ +)
csum [jJ = 9;
for(i=0;i<m;i++)
csum [j] = csum [jj + mat [ii [3];
II The matrix with row sum & column sum for(i=0;i<m,i÷-t-)
17. Write a program to find row sum and column sum of a matrix. Ans: #include <stdio.h>
#include <conio.h>
void main ()
mt mat [10] [10], m, n, i,j, rsum [10], csum [10]; printf (“Enter order of matrix:”);
scanf (“%d%d”, &m, &n);
printf (“\n”);
18. Write a program to obtain transpose of a 3X3 matrix. Ans: #include <stdio.h>
#include <conio.h>
void main ()
mt mat [3] [3], i, j;
II Entering elements of a matrix for(i=0;i<3;i-,--i-)80 A Refresher Manual of Computer Science for Grade XII
Computer Science 81
{
for (j0;j<3;j ÷+) scanf(”%d’, & mat [ii [ji);
printf (“\nn”)
II The entered matrix is for(i=0;i<3;i++)
{
for(j=0;j<3;j÷+)
printf (“%d \t”, mat [ij [ii); printf (“\n);
II Finding transpose for(j =0;j <n;j++)
for(i0;i<m;i++)
printf (“%d \t”, mat [1] [ji); I printf (“n’);
getch();
19. Write a program to read a set of numbers from keyboard and to sort out the given array of elements in ascending order using a function.
Ans: #include<stdio.h> #include<conio.h> #define MAX 100 mt a[MAX void main ()
I
void inputO; //function declaration input();
getchQ;
void input ()
{
void output (mt a [1 mt n);
mt sort (mt a [1 mt n); inta[MAXJ;
mt n;
printf (“How many nos ?“); scanf (‘%d”, &n);
/1 Entering elements of array printf (Enter elements \n”); for(int i = 0;i<n;i++)
I
scanf (‘%d”, &a[i]);
printf (“Unsorted array\n”); output (a, n);
sort (a, n); printf (“Sorted array \n”); output (a, n);
void output (mt a[j, mt n)
printf (‘\n”);
For (mt i0;i<n;i++)
{ I
printf (“%d\t” a[i]);
mt sort (mt a[ j, mt n)
{
mt temp; for(int i=0;i<n;÷+i)
for(int j =i+l;j<n;+÷j) if (a[iJ>a{j])
{
I
temp a
a [i] = au 1;
a [j] = temp;
20. Write a C program to pass ‘n’ different numbers to the function named “arrayfunction” ,find maximum number among them
Ans: #include<stdio.h> #include<conio h> void arrayfunction(int[] ,int); void mainO82 A Refresher Manual of Computer Science for Grade XII
Computer Science 83
mt i,a[100],n; printf(’Enter n:”); scanf(”%d” ,&n); printf(”Enter number=”); for(i=O;i<n;+i-i)
scanf(”%d” ,&a[i]); arrayfunction(a, n); getchO;
void arrayfunction(int x[J ,int n)
mt j,max=O; for(j=O;j<n;j++)
{
if(x[j] >max) maxx[jJ;
printf(”maximum no:%d\t”,max);
21. Read the maximum and minimum temperature of 7 days of Kathmandu Valley and creates a function to calculate minimum and maximum temperature, also find the average temperature.
Ans: #include <stdio.h> #include <conio.h> mt maximum (mt max [71); mt minimum (mt mm [71);
void main () j
{
mt maxm [7], minm [7], mt avgmaxm, avgminm, avg, i; printf (‘Enter temperature in”); for (i= 0; i< 7; i÷
printf (‘Maximum temperature of day %d”, i + 1); scanf(”%d”, & maxm [i]);
printf (‘Minimum temperature of day %d”, i + 1); scanf(”%d”, & minm [ii);
avgmaxm = avgmaxm + maxm [ii; avgminm = avgminm + minm [i];
I
I
mintemp = minimum (minm); printf (“\n maximum temperature: %d”, maxtemp); printf (‘n minimum temperature: %d”, mintemp); avg = (avgmaxm + avgmmnm)/2; printf (“ \n average temperature: %d”, avg); getch 0;
mt maximum (mt max [7])
{
I
mt I, maxt;
maxt = max [0]; for (i= 0; i< 7; +
if (maxt < max) maxt = max [i];
return maxt;
mt minimum (mt mm [7])
mt i, mint; mint = mm [0]; for (i= 0; i< 7; i+ +)
I
if (mint> mm [i]) mint = mm [ml;
return mint;
22. Design a. program to enter 5 1ifferent numbers in array variable and findout whether individual number is even or odd.
Ans: #include <stdio.h> #include <conio.h> void checic (mt n); void main ()
{
irn i, num [5];
II Entering 5 different numbers for (i = 0; i < 5; i +
maxtemp = maximum (maxm);
prmntfC’Enter %d number :\n”, I + 1); 84 A Refresher Manual of Computer Science for Grade XII
Computer Science 85
scanf(”%d \n”, & num[i]); check (num [ii);
I
getch();
void check (mt n)
if (n% 2 = = 0) printf (“Even); else
printf (“odd”);
23. Write a program to enter 10 different number in array variable and check whether the entered number is prime or not usin function.
Ans: #include <stdio.h>
#include <conio.h> #include <process.h> void check (mt n);
void main ()
{
mt n[10], i;
II Entering 10 different numbers for (i=0;i< 10;i++)
{
printf (“Enter 10 different numbers :“); scanf(”%d”, &n [i]);
check (n [ij);
I
I
getch();
void check (mt n)
mt i;
for (i = 2; i < = n/2; i +
if (n % i = = 0)
24. Write a program to enter first name, last name and telephone number between 20000 - .799999 of 5 different students and print them in tabular form.
Ans: #include <stdio.h>
#include <conio.h> void main ()
charfname[5] [15], Iname [5] [15]; mt phone [5], i;
II Entering data
for(i0;i<5;i÷÷)
printf (“Enter first name \n”); scanf (“%s”, fname [i]); printf (‘!Enter last name scarif (‘%s”, Iname [i]); do
printf (“Enter phone number: \n”);
scanf(”%d”, &phone [ii);
while (phone [ii <20000 phone [ii > 799999); printf (“\n\n”);
II printing in tabular form
printf (“\n First name \t last name \t phone number \n”);
pnintf (“ \t \t
for (i= 0; i< 5; 1+
printf(”%s \t% s \t% d \n”, fname [iJ, iname [ii, phone [i]); getch 0;
25. Write a program to enter a string and count total number of alphabet “A” occured in the string.
Axis: #include <stdio.h> #include <conio.h>
void main ()
exit (0);
printf (“\n Prime number”);
/
printf (“Not prime”); 86 A Refresher Manual of Computer Science for Grade Xli
Computer Science 87
char sen [50]; mt count = 0; printf (“Enter a sentence:”); gets (sen);
II Counting total member of A for (i = 0; sen [i] ! = ‘\O’, i + i-)
if(sen [i] = = ‘A’ N sen [iJ = = ‘a’)
count=Couflt+ 1;
printf (“Total no. of alphabet of occured in a sentence : %d” count);
getchO;
}
26. Write a program to read a line and replace space by “. Ans: #include <stdio.h>
#include <conio.h>
void main C)
char line [201;
mt i;
printf (“Enter a line :“); gets (line);
II Replacing space by * for (i = 0; line [ii! = ‘\O’; i +
if (line [i] =
line [i] =
puts (line);
}
getch ();
27. Write a program to enter a string and convert it into uppercase and vice-versa.
Ans: #include <stdio.h> #include <conio.h>
void main ()
mt i;
printf (“Enter a string :“); gets (str);
II Converting uppercase to lowercase & vice versa for (i = 0; sen [ii! = ‘\O’, i++)
if(str [ii > = 65 && str [i] <97)
{
str [i] = str [ii + 32; printf(”%s”,str[il);
else if (str [ij > = 97 && str [i] <123)
I
str [i] = str [ij — 32; prinntf(”%c”,str[i]);
else;
getch ();
28. Write a program to input a message from keyboard and display
the menu.
1. Print message length in terms of characters
2. Print the message in re’’erse order
3. Print the message in capital letters
4. Copy the message from one location of screen to another location
5. Check the palindrome
6. Exit
Ans: #include <stdio.h>
#include <conio.h>
#include <string.h>
#include <process.h>
void main ()
C
char str [40], dest [40], dest2 [401;
mt choice 1; printf (“Main menu
printf (“1. Print message length \n”); printf (“2. Print message in reverse order \n”); printf (“3. Print the message in capital letters \n”);
char str [40]; 88 A Refresher Manual of Computer Science for Grade Xli
Computer Science 89
printf (“4. Copy the message from one location to another\n”); printf (“5. Check the palindrome \n”);
printf (“6. Exit \n\n”); printf (“Enter your choice (1/2/3/4/5/6):”); scanf (“%d”, & choice); switch (choice)
case 1:
printS (“Enter a string\n”); gets (str);
= strien (str);
printf (“Length of message = %d”, 1); break;
case 2
printf (“Enter a string \n”);
gets (str);
printf (“String in reverse order \n”); printf (“%s”, strrev (str)); break;
case 3:
printf (“Enter a string \n”); gets (str);
printf (“%s”, strupr (str)); break;
case 4
printf (“Enter a string \n”); gets .(str);
strcpy (dest, str);
printf (“copied string : %s”, str); break;
case 5
printf (“Enter a string :
gets (str);
strcpy (dest, str);
strcpy (dest2, strrev (dest)); if (strcmp (str, dest2) = = 0)
printf (“Palindrome \n”); else
printf (“Not palindrome”); brealq
case 6:
exit (0);
29. Write a menu drIven program which has the following options:
1. Reverse order
2. Ascending order
3. Descending order Ans: #include <stdio.h>
#include <conio.h> #include <process.h> void main ()
mt i, num [101, ch, temp; printf (“Enter 10 numbers \n”); for (i= 0; i< 10; i+ scanf(”%d”, & num [i]); printS (“Main menu printf(”l. Reverse order \n”); printS (“2. Ascending order \n”); printf (“3. Descending order \n”); printf (“4. Exit \n”); printf (“Enter your choice (1/2/3/4):”.); scanf (“%d”, & ch);
switch (ch)
case 1
for(i = 9; i >= 0; i——) printf (“ % d\t”, num [ij); break;
case 2:
for (i= 0; i < = 9; i +
for(j=i+1;j<9;j++)
if(num [i] > num [ji)
{
temp = num [iJ; num [ii = num [j]; num [jj = temp;
default:
printf (“You aren’t allowed to type otheis\n”); exit (0);
getch();
1}
for (i= 0; i<= 9; i+
I
for(j =i÷ 1;j<=9;i++) if (num [1] <num [ii
I
temp = num [ii; num [ii = num [j]; num [j] = temp;
printf (“%d \t’, num [ii);
break;
case 4
exit (0); default:
printf (\n Not allowed to type other’); exit (0);
getchO;
Write a program to read 10 different names and age into an array and sort them in ascending order by age and print sorte4 list.
Ans: #include<stdio.h> #include.cconio.h> #include<string.h> void main ()
char name [10] [30], namel [30]; mt age [10],i, j, temp;
II Entering 10 different names and age for(i=0;i< 10;i++)
fflush (stdin);
printf (“Enter name \n”); scanf (“%s”, name
printf (“Enter age \n”); scanf(”%d”, &age [i]);
I
}
II sorting data on the basis of age for(i=0;i< 10;i++)
{
forQ=i÷1;j < 10;j +
I
if (age [ii > age [ji)
I
temp = age [ii; age [i] = age [ji; age [j] = temp;
strcpy (namel, name [ii); strcpy (name [ii, name strcpy (name [jJ,namel);
II Printing the sorted list print1 (“ \n Name \ t \tAge \n”); for(i=O;i< 10;i-q-+)
printf(” % s t \t %çl\n”, name [ii, age [i]);
getch ();
31. Write a program to enter a string and check whether the entered string is palindrome or not using library function. [Palindrome:
A string is said to be palindrome if it remains same if we reverse
it. e.g. ADA, MALAYALAM]
Ans: #include <stdio.h> #include <conioh> #include estring.h> void main()
char str [30], temp [30]; printf (“Enter a string\n”); scanf (“%s”, str);
strcpy (temp. str); strrev (temp); if (strcmp (temp, str) = = 0)
90 A Refresher Manual of Computer Science for Grade XII
printf(”%d\t”, num [i]);
break;
case 3:
Computer Science 91
4
30.
J
I92 A Refresher Manual of Computer Science for Grade XII
Computer Science 93
printf (“String is palindrome”); else
printf (“String is not palindrome”); getch();
32. An organization has 5 stores and it deals in items. The stock A position of these items shown below:
Item 1 Item 2 Item 3 Item.4
Storel 30 35 0 45
Store2 24 35 12 0
Store3 0 34 8 19
Store4 12 0 34 18
Store 5 10 10 17 45
Develop a computer program in any of HLL you are taught in your class, to input this table and indicate the items that are completely out of stock at store i, where the value of i may be input from the keyboard.
Your program should calculate the total stock of each item, in the organization and total items in store number 5.
Ans: #include <stdio.h> #include <conio.h> #include <ctype.h> void main ()
mt stock [5] [4] = {30, 35, 0, 45, 24, 35, 12, 0, 0, 34, 8, 19, 12, 0, 34, 18, 10, 10, 17, 45};
mt i, j, csum [4], sum;
II Displaying items
printf (“\t Itemi \ t Item 2\ t Item 3\ t Item 4\ n’);
for (i=0; i< 5; i++)
printf (“Store %d \t’, i + 1); for(j=0;j<4;j÷-i-)
printf (“%d\t”, stock [ii [ii); printf (“\n”);
printf(”\n\n Enter the store no scanf (“%d”, &i); i=i—1; for(j=0;j<4;j+÷)
if (stock [ii [jj = =0)
printf (“\n Item %d of store %d is out of stock \n”,j+l,
printf (“\n None of item is out of stock’);
II Finding total item in columnwise for(j =0,j <4;j +
csum [ii = 0;
for(i =0; i< 5;i ÷
csum [j] = csum [j] + stock [i] [j];
II Finding total stock in store 5
= 4;
sum = 0;
for(j=0;j<4;j÷+)
sum = sum + stock [ii [j];
printf (“ \n Total stock in store 5 is %d\n”, sum);
for(j 0;j <4;j + ÷)
printf (“Total stock of item %d is %d \n”, ji-1, csum[j]);
getch 0;
33. Write a program that reads a line and count the number of letters, vowels, consonants, words and blank spaces present in the line.
Ans: #include <stdio.h> #include <conio.h> #include <string.h> void main ()
{
char sen [100];
mt i, n, vcount=O, ccount=0, wcount=0, scount=0, lcount=0;
printf (“\n Enter a sentence \n”); gets (sen);
n = strien (sen);
// comparing and counting the totals number of
i+1);
I94 A Refresher Manual of Computer Science for Grade XII
II vowel, consonant etc. for(i=O;i<n;i++)
if (sen [i] = = ‘a’ sen [ii = = ‘e’ sen [i] = = ‘0’ N Sen [ii = = sen [ii = ‘A’ sen [i] = = ‘E’ II sen [i] = = ‘I’ sen [i] = ‘0,11
sen [i] = = ‘U’ II sen [iJ = = ‘i’)
vcountvcount÷ 1;
else if(sen [ii = ‘
I
{ I
scount = scount + 1; wcount=wcount+ 1;
else
ccount = ccount + 1;
ccount = icount + 1; printf(”No. of vowels = %d \n”, vcount);
printf (“No. of consonants = %d \n”, count); printf(”No. of words = %d n”, wcount + 1); printf (“No. of space = %d \n”, scount); printf (“No. of letters = %d \n”, Icount); getch();
I
34. Write a program which will ask the user to input a single character and then a string and will count the occurrence of that character in that string.
Ans: #include <stdio.h> #include <conio.h>
void main ()
char sen [40], ch; mt count = 0, i;
printf (“Enter a sentence :
scanf(”%s”, sen); printf (“Enter a character \n”); scanf (“%c”, ch);
1* comparing and counting the occurrence of entered character / for (i = 0; sen [i] ! = ‘\o’ ; i +
{
if(sen [ii = = ‘ch’) count = count + 1;
}
printf (“The total number of entered character in a sentence = %d”, count);
getch
35. Write a program that reads a string and prints the string in
1. UPPER CASE
2. Sentence case
3. Title Case
4. toGGLE cASE
Ans: #include<stdjo.h> #include<conjoh> #include<process.h> #include<ctype.h> #include<string.h> void main ()
mt i, n, ch, j; char sen [50];
printf (“Enter a string :
gets (sen); n = strlen (sen);
printf (“Main Menu: \n”); printf (“1. UPPER CASB \n”); printf (“2. Sentence case printf (“3. Title Case \n”); printf (“4. toGGLE CASE \n”); printf (“ n \n”);.
printf (“Enter ypur choice (1/2/3/4/)! \n”);
scanf (‘%d”, &ch);
switch (ch)
{
{
for (i = 0;i<n;i÷+)
{
Sen [i] = toupper(sen[iJ); printf (“%c”,sen[i]);
I
I
Computer Science 95
I
L
Case I96 A Refresher Manual of Computer Science for Grade XII
{
for (i = 0;i<n;i++) sen[i] =tolower(sen [ii); sen[0] =toupper(sen[0]); for(i=0;i<n;i++)
{
}
if(sen[i]==’‘)
sen [i+ 1] =toupper(sen [i+ 1 ]);
else;
puts (sen);
break;
{
for (1 = 0; i < n; i+÷) sen [ii = toupper (sen [i]); sen [01 = tolower(sen[0]); for (i=0;i<n;i++)
{
}
if(sen[i]==’‘)
sen[i+1]=tolower(sen[i+ 11);
else;
puts (sen);
break;
default:
{
printf (“Wrong choice \n”); getch();
36. Write a program that will print all the
into it. [e.g. space, paces, acesp, cespa,
Ans: #include <stdio.h> #include <conio.h> #include <string.h> void main ( )
char name [15]; mt i, j, n; printf (Enter name :“); gets (name); n = strien (name); for(i=0;i<n;j+÷)
{
}
temp = name [0]; for(j =0;j<ii_ 14j++) name [j] name [j + 1); name (n — 1) = temp; puts (name); printf (“ \n”);
getch ();
37. Write a program that reads the name,
5 different subjects of 10 students,
total marks obtained by each student in
Ans: #jnclude<stdioh> #jnclude<corijoh>
void main ()
break;
case 2:
for(i=0;i<n;i++)
sen [i] =tolower(sen [ii);
sen [0] =toupper(sen[0]);
printf (“%s” ,sen);
break;
case 3:
exit (0);
getch();
}
case 4:
mt i,j,roll[10],total[1 0] ,mark[1 0] [5]; —
98 A Refresher Manual of Computer Science for Grade XII /
}
char name [101 [201; II Reading data for (i 0; i < 10; i÷+)
{
I
printf (“Enter name :“); scanf (“%s \n”, name[iJ); printf (“Enter roll number :\n”); scanf (“%d”, &roll[i]);
printf (“Enter marks in 10 different subjects :“); total [ij =0;
for(j0;j<5;j++)
{
I
scanf (“%d’, &mark[i] [ii); total [ii = total [ii + mark[i] [ii;
II Displaying results.
printf (“\n Name \t Roll number \t Total \n”); printf (“
for (i = 0; i < 10; i++)
printf(”% s t % d \ t% d\n”, name [iJ, roll [i], total [ii); getch();
38. An array J has numeric elements J(i) held in ascending order in the memory of computer, when J ranges from 1 to thousand (1 000). Describe either in flowchart or write a program, if any, element has value N using method known as binary search (binary loop).
Ans: #include <stdio.h>
#include <conio.h>
#define max 1000
void main()
mt j[maxj, n, i, first, last, pos = o, x, mid, temp, k; printf (“Enter n:”);
scanf (“%d”, &n);
II Entering the elements printf (“Enter elements :“); for(i=0;i<n;i++)
scanf(”%d”, & j [i]);
II Arranging in ascending order for(i=0;i<n;i÷÷)
{
for(k=i÷ 1;k<n;k÷+){ if (j [i] > j [kJ)
{
I
temp = j [ii; [ii = j [k];
[k] = temp;
printf (“The numbers entered in ascending order are:\n”); for (i = 0; i < n; i ++)
printf(”%d it”, j[i]);
printf(” \n \n”);
fi Process for searching a I?iumber
Printf (“Enter the number to be searched :\n”); scanf (“%d, &x);
first = 1; last = n;
while (first < = last) && (pos = = 0))
mid = (first + lasr/2; if(j [mid] = = x)
pos = mid;
else if(j [mid] <x)
first = mid + 1;
else
last = mid — 1;
Computer Science 99
I
if (pos > 0) 100 A Refresher Manual of Computer Science for Grade XII
Computer Science 101
printf(Position is %d”, pos); {
else . ,,
printf( Enter name,roll,marks: );
printf( Not found ); scanf(”%s%d%d”,name[i],&roIl[ib&marks[iD;
getchO;
I/Alphabetical sorting
for(i=0;i<n;i++)
39. Develop a program that will read and store the details of a list of
students in tabular format and produce the following outpui
lists: forQ=i÷1;j<=n;++) H
1. Alphabetical list of names, roll number and marks obtaind.
2. List sorted on roll numbers. if(strcmp(name[iJ,name[jl)>O)
3. List sorted on marks. {
Ans: #include<stclio.h> strcpy(templ ,name[i]);
#include<conio.h> strcpy(name[i],name[jJ);
#include<string.h> strcpy(name[j} ,temp 1);
#define MAX 100
void mairi() temp=roll[iJ;
{ roLl[ij=roll[j];
char name[MAX)[20],templ [20); roll[jJ=temp;
mt i,j,roll[MAX] ,marks[MAXJ ,temp,choice,n;
temp=marks[i);
printf(”Enter number of students:’); marks[i] =marks [ji;
scanf(”%d”,&n); marks[jl=temp;
printf(”\n\n”);
printf(” I .Alphbetically sorting\n”); I
printf(”2.List sortd on roll number\n”); printf(”The name in reverse orders are:\n\n”);
printf(’3.List sorted on rnarks\n”); for(i=0;I<n;÷-i-i)
printf(” \n”); printf(”%s\t%dt%d\n”,nawe[iJ ,rolI[iJ ,marks [ii);
printf(”Enter ur choice’);
scanf(”%d”,&choice); break;
printf(”n\n\n”); case 2:
switch(choicc) for(i=0;i<n;i++)
{ {
case 1: printf(”Enter na.me,roll,marks:”);
{ scanf(”%s%d%d”,name[iJ ,&roll [1) ,&marks [ij);
for(i=0;i<n;i÷+) }102 A Refresher Manual of Computer Science for Grade XII Computer Science 103
//Rollwlse sotting forO=i+ 1 ;jc=n;j+÷)
for(i=O;i<n;j++)
{ if(marks[i]>marks[j])
for(J=i+1;Ji=nj++) {
{ temp=marks[i];
if(roll[i]>roll [j]) marks [ii =marks[jj;
marks[j]=temp;
temp=roll[i];
temp=roi1[i] roll [1] =roll[j];
roll[ij=roll[jJ; roll[jJ=temp;
roll[j]=temp;
strcpy(temp 1 ,name[i]);
strcpy(temp I ,namc[i]); strcpy(name[i] name[jJ);
strcpy(name(i] ,name[j]); strcpy(name[jj ,temp 1);
strcpy(name[j] ,temp 1); 1
ternp=rnarks[i]; I
marh[il=marks[j]; printf(”The marks in reverse orders are:\n\&);
marks[jJ=temp: for(i=O;i<n;i++)
I printf(”%d\t%s\t%d\n” ,marks[ij ,name[i] ,roll[i]);
I
break; .
printf(”The roll in reverse orders are:\n\n’); default:
for(i=0;i<n;i÷+) printf(’Wrong choice”);
printf(”%d\t%s\t%d\n”,roll [ii ,name[iJ ,marks [iJ); break;
I
break; getchO;
case 3:
for(i=0;i<n;i÷+) 40. Write a program to display the following patters:
H
printf(Enter name,roll,marks:”); H H
scanf(”%s%d%d”,namefi] ,&roll [ii ,&marks[i]); E E E
LLLL
0000
//Markswise sorung w w w w w
for(i=0;i<n;i÷÷) Ans: #include<stdio.h>
#include<conio.h>41. Write a program to display the following patters:
HE
HEL
HELL
HELLO
H E L L 0 W Ans: #includecstdio.h>
#include<conio.h>
Computer Science 105
LFunctio
1. ‘What is a function? List its advantages.
Axis: A function groups a number of statements into a unit and gives it a name. Then the unit can be inoveked from some other parts of the program. We can avoid rewriting of a group of codes by defining them within a function block and use them by simply calling the function name.
Advantages of function:
(a) Easy to write a correct small function.
(b) Easy to read, write and debug function.
(c) Easier to maintains or modify such function.
(d) Small function tend to be self documenting and highly readable.
(e) It can be called any number of times in any place with different parameters.
2. What is modular programming? What are the advantages and disadvantages of modular programming?
Ans: When a program becomes very large and complex, itbecomes very difficult task for the programmer to design, test and debug such a program. Therefore, a long program can be divided into a smaller programs called modules. As the modules can be designed, tested and debugged separately, the task of programmer becomes easy and convenient. The divi,sion of a long program into a smaller programs (or modules) is called modular programming. Advantages.
(a) It is easier to design, test and debug a single modules as compared to an entire program.
(b) Usually, a module of general nature is prepared so that it can be used elsewhere.
Disadvantages:
(a) Since separate modules map repeat certain functions, the modular programming often need extra time and memory.
3. Why programmer want to do program in modular style? Explain.
Axis: There are many good reasons to program in a modular style:
— Don’t have to repeat the same block of code many times in• your code. Make that code block a function and call it when needed.
— Function portability: useful functions can be used in a number of programs.
I
104 A Refresher Manual of Computer Science for Grade XII
void main()
{
char str[j=”HELLOW”; mt i,j; for(i=O;i’<=6;i++)
for(j=0;j<”i;j++)
printf(”%c” ,str[il);
printf(’\n”);
getchO;
}
H
void main()
char str[j =“HELLOW”; mt i,i; for(i=O;i<=6;i++)
for(j=0;j<’i;j÷÷)
printf(”%c”,str[j]);
printf(”\n”);
}
getchO; 106 A Refresher Manual of Computer Science for Grade XII
Computer Science 107
— Supports the top-down technique for devising a program algorithm. Make an outline and hierarchy of the steps needed to solve your problem and create a function for each step.
— Easy to debug. Get one function working well then move on to the others.
— Easy to modify and expand. Just add more functions to extend program capability
— For a large programming project, you will code only a small fraction of the program.
— Make program self-documenting and readable.
4. What do you know about function declaration, function call and function definition? Explain clearly.
Ans: Function declaration: It specifies function name, argument types and return value. Alerts coniputer (and programmer) that function j is coming up later.
Examples: void displayQ; mt sum (int, int, int);
etc.
Function call : It is also a component of the function and causes the function to be executed.
Examples: display ();
result = sum(a, b, c);
etc.
Function definition : The function itself contains the lines of code that constitute the function.
Examples: void display()
5. What do you know about function parameter and function return?
Ans: Function parameter : The parameter specified in function call are known as actual parameter and the parameter specified in function declaration are known as formal parameter
Example: res = sum(a, b, c);
Here a, b, c are actual parameter mt sum (jot x, mt y, jot z)
Here x, y z are formal parameter.
Function return: Function can be organized into two type.
(a) Function that do not have a return type i.e. void function.
(b) Function that do have a return value (i.e. return (res);)
6. What is recursion? Give its example.
Ans: Recursion is a process of a function calling itself again and again until some condition has been satisfied. Using recursion, two condition must be satisfied.
(a) The program must be written in a recursive form.
(b) The problem statement must include a stopping condition. If not, computer will hang.
Example: To calculate factorial using recursion #include <stdio.h>
#include <conio.h> mt factorial (int);
void main ()
}
mt n;
printf (“Enter a number =“); scanf (“%d”, &n);3 printf (“Factorial no = %d, factorial (n)); getch ()
mt factorial (jot n)
{
if(n < = I)
return 1.; else
return (n * factorial (n - 1));
Explain the difference between ‘call by reference’ and ‘call by value’.
Differentiation between ‘call by reference’ and ‘call by value’:
CaR by reference Call by value
a) Example: Example:
{ #include <stdio.h>
mt a 5, b = 10; #include <conio.h>
for(inti=O;i<9;i+-i-)
printf (“+“);
mt sum(int x, mt y, jot z)
res = x÷ y + z;
return res;
7.
Ans: 108 A Refresher Manual of Computer Science for Grade XII
;1] CIrogrammings —6;0]
fun (a, b); printf(”a = %d,b = %d”.
a, b);
getchO;
void fun (mt x, mt y)
x=x+ 100;
y=y+ 100;
Result:a=5,b= 10 We passed the arguments ‘a’ & ‘b’ by value i.e. their values are copied to the variables ‘x’ & ‘y’ in the function “fun( )“. Thus the statements “x = x ÷ 100” and “y = y+100” only changes the values of their copies and doesn’t affect their original value.
void fun (mt “, mt *); void main ()
mt a = 5, b = 10; fun (&a, &b);
printf (“a = %d, b = %d”, a,
getchO;
}
void fun (mt x, mt *y)
100;
= + 100;
Result:a= 105,b= 110
We passed the address (memory location) of variables ‘a’ and ‘b’ by statement “fun (&a, &b)”. The address operator (&) is used to denote the address of a variable. The address of these variables here are pointed by the pointers *x,
*y The statements = +
100” and “ = ‘y + 100” here changes the original value of variables ‘x’ and ‘y’ since these pointers are directly pointing the memury locations of ‘a’ & ‘b’. The pointer declaration and initialization during function call here will look like:
int*x = &a; and
Computer Science 109
Write a program to calculate the area and circumference of a circle using a function where radius of circle is input by user and define ‘ii’ as constant.
Ans: #include <stdio.h> #include <conio.h> #define pie 3.14 void findarea (int); void findcircum (int); void main ()
mt r;
printf (“Enter the value of radius =“); scanf (“%d”, &r);
findarea (r);
findcircum (r);
getch();
void findarea (mt r)
float a;
a = pie * r * r;
printf (“Area of a circle = %f”, a);
} .
void findcircum (mt r)
float C;
c = 2*pie * r;
printf (“\n circumference of a circle = %f’,c);
2. Write a program to print all even numbers from 2-40 using nonreturnable function.
Ans: #include<stdio.h>
#include<conio.h>
void print_even 0;
void main ()
printf (“Here are even numbers from 2 to 40”); print_even 0;
printf (“You got the result”);
getch 0;
b)
call by value:
Call by reference: definition
value of actual argument
address of actual argument
parameter is copied into the
parameter i assigned to the
formal parameter of the
formal argument parameter.
function. 110 A Refresher Manual of Computer Science for Grade XII
Computer Science Ill
void print_even ()
for (a = 2;a<=40;a+2) I
printf (“%d\n” a);
3. Write a program to find sum of’n’ different numbers using non- j returnable function.
Ans: #includecstdio.h> #include<conio.h> void sumofint(int); void main()
{
mt n;
printf(”Enter,how many number?:”); scanf(”%d” ,&n); sumofint(n);
getchO;
void sumofint(int n)
mt x,sum=0,num; for(x=0;x.cn;++x)
printf(”Enter number:”); scanf(”%d” ,&num); sum=sum+num;
printfC’Sum of integer=%d”,sum);
4. Write a program to find sum of square numbers using functions.
Ans: #include <stdio.h> #include <conio.h> voidsum( ); void main ( )
printf (‘Sum of square of first 10 natural nos\n”); sum ( );
mt a;
I
printf (“You got sum of first 10 natural nos\n”); getchQ;
void sum()
I
mt a, sum = 0; for (a = 1; a < = 10; a +
sum = sum + a* a;
printf (“Sum of square of first 10 natural nos = %d\n”,
sum);
5. Write a program to find multiplication table of any number using function.
Axis: #include<stdio.h>
#include<conio.h> void numbers(int);
void main() ()
{
I
mt n; printf(”Enter sny number=”); scanf(”%d”,&n); numbers(n); getchO;
void numbers(int n)
{
mt x,m;
for(x= 1 ;x<z 1 0;++x)
m=n*x;
printf(”%d x %d=%d\n”,n,x,m);
6. Write a program to count the positive and negative numbers from ‘n’ entered numbers using functions.
Axis: #include<stdio.h> #include<conio.h> void numbers(int no[100],int n); void main ()
I
of first 10 naturaLi
{112 A Refresher Manual of Computer Science for Grade XII
Computer Science 113
mt n,no[100J,i;
printf (“Enter the value of n =\n”); scanf (“%d”, &n);
for (i = 1; i<n; i++)
I
printf (“Enter numbers scanf (“%d”, &no[i]);
numbers(no,n);
printf (“You got ÷ve & -ye numbers\n”); getch 0;
void numbers(int no[1001,int n)
{
mt pcountO, ncount=O; for (mt i 1;i<n;i÷+)
{
if(no [i]> 0) pcount = pcount + I; else
}
ncount = ncount ÷ 1;
I
printf (“Total number of +ve no. = %d\n”, pcount); printf (“Total number of-ye no. = %d”, ncount);
7. Write a c program to read two numbers x and y multiplication of them using function.
Ans: #include <stdio.h> #include <conio.h> mt multiplication (int,int); void main()
mt x,y,z;
printf(”Enter value of and b:”); scanf(”%d%d”,&x,&y); z=multiplication(x,y); printf(”Greater number=%d”,z); getchO;
mt multiplication(int x,int y)
8. Write a program to find the greatest number among any two numbers.Define the function greaterO.
Ans: #include <stdio.h> #include <conio.h> mt greater (int,int); void main()
{
mt a,b,c; printf(”Enter value of and b:”); scanf(”%d%d”,&a, &b); c=greater(a,b); printf(”Greater number=%d”,c); getchO;
mt greater (mt x,int y)
if(x>y)
return x;
else
return
9. Write a program to calculate the factorial number of any number entered through the keyboard by using returnable function.
Ans: #include <stdio.h> #include <conio.h> long mt factorial (int); void main ()
mt n; long mt fact; printf (“Enter a number =“); scanf (“%d”, &n); fact = factorial (n);
printf (“Factorial number of %d = %ld”, n, fact); getch 0;
{
mt z; z=x*y; return z;
11
,find
long mt factorial (mt n) }
long mt fact= 1;
for (inti= 1;i<n;i÷÷)
fact = fact *
return fact;
10. Write a function power (a, b), to calculate the value of a raised to
b.
Ans: #include <stdio.h>
#include <conio.h>
mt powl (mt x, mt y
void main ()
}
mt x, y;
jut pow 1, power 0; printf (‘Enter two numbers scanf (“%d %d”, &x, &y); powl = power (x, y); printf(”\n %d to the power %d = %d”, x, y, powl); getch();
mt powl (mt x, mt y
{
}
mt i;
longp= 1; for(i= 1;i<=y;i++) p = p * x;
return p;
11. A digit positive integer is entered through the keyboard, write a function to calculate sum of digis of number.
(a) Without using recursion.
(b) Using recursion.
Ans: #include <stdio.h> #include <conio.h> mt wsum (int); jut rsum (int); void main ()
A
jut s, rs; Int n;
printf (“Enter number =“); scanf (“%d”, &n); s = wsum (n);
printf (“Sum of digits without recursion = rs = rsum (n);
printf (“Sum of digits using recursion = %d\n”, rs); getchO;
mt wsum (mt n)
{
jut r, sum 0; while (n> 0)
{
r= n%10;
}
sum = sum + r; n = n/10;
return sum;
mt rsum (mt n)
mt r, sum = 0; if(n! = 0)
{ I
}
r=n%10;
sum = r + rsum (n/l0);
return sum;
12. Write a program to print 10 positive integers and their factorials.
[HSEB-2062j
Ans: #include <stdio.h> #inclucle <conio.h>
long mt factorial (int);
void main ()
jut ,num[10J,i; long mt fact; printf (“Enter any 10 numbers =“);. for(i=0;i< 10;i++)
{
}
{116 A Refresher Manual of Computer Science for Grade XII
Computer Science 117
}
{
}
printf (“Enter numbers\n”); scanf (“%d”, &nUm [ii); &ct = factorial (num [1]);
printf (“Factorial no. of %d is %ld”, num [iJ, fact);
getchO;
long mt factorial (long mt n)
{
I
long mt fact= 1;
mt i;
for(i=O;i<n;i++)
fact = fact *
return fact;
13. Write a c program to find sum of ‘n’ numbers which is divisibi by 5 using function.
Ans: #include<stdio.h> #include<conio.h>
mt sum(int,
void main ()
I
mt x, y;
printf (“Enter two numbers = scanf (“%d”, &x); y=sum(x); printf(”sum=%d” ,y); getch();
mt sum(int x)
{
I
mt i,s=O; for (i =1; i<=x; i++)
if(i%5==0)
S=s-t-i;
return s;
14. Write a program to read 100 different number from users, store them in an array, passes the array through function and,flnd maximum number among them.
Axis: #includecstdio.h>
#include<conio.h>
mt numbers(int no[100],int n); void main ()
I
mt n,no[100],i;
printf (“Enter the value of n =\n”); scanf (‘%d”, &n);
for (i = 1; i<n; i++)
printf (“Enter numbers : \n”); scanf(”%d’,&no[i]);
printf(”Maximum number=%d’,numbers(no,n)); getchO;
mt numbers(int no[100],int n)
I
mt max=O; for (mt i=1;i<n;i-i-÷)
I
return max;
if(no [i]> max) max=no [ii;
15. Write a program to find sum of given non-negative integer numbers using a recursive function.
[i.e.sum=1+2+3+ +n]
Ajis: #include <stdio.h> #include <conio.h> mt sum (int); void main ()
{
mt n, result;
printf (“Enter how many terms :-“); scanf(”% d’, & n);
result = sum (n); mt sum (mt n)
{
mt sumi = 0;
if (n = = 0)
return sum 1;
else
sum 1= n + sum (n — 1); fi return sum 1;
16. Write a program to find factorial number of given number using recursive function.
Ans: #include<stdio.h> #include<conio.h> long mt factorial(int); void mainO
{
I
mt n; long mt x; - printf (“Enter any number =“); scanf (“%d”, &n);
x = factorial (n);
printf (“Factorial no = %ld”, x); getchO;
long mt factorial (mt n)
{
mt fact=1; if(n==1)
return fact;
else
fact=n*factorial(n_ 1); return fact;
void main ()
}
mt n, res;
printf (“Enter number”); scanf (“%d”, &n);
res = fibonacci (n);
printf(’Fibonacci number = %d”, res); getchQ;
iTrm?t1
I. ‘What is a structure? How structure is declared’Explamn.
Ans: A structure is a collection of one or more variables grouped under a single name for easy manipulation. The variables in a structure, unlike those in an array, can be of different variable types. A structure can contain any of C’s data types, including arrays and other structures. Each 3variable within a structure is called a member of the structure.
syntax > struct user_defined_name
{ ‘— tag or structure name
char name [201; mt class; mt age;
data_type member I; data_type member 2;
+— structure members
structure type variables
118 A Refresher Manual of Computer Science for Grade XII
printf (“Sum of non-negative nos=%d”, result); getch();
Computer Science 119
I
mt fibonacci (mt n)
if (n < = 2)
return 1;
else
return (fibonacci (n — 1) + fibonacci (n — 2));
I
I
17. Write a program to print all fibonacci numbers upto a numb ‘II’ recursively.
Ans: #include <stdio.h> #include <conio.h>
mt fibonacci (mt n)
structure user_defined_name van, var2 Declaration of a structure
e.g. struct student120 A Refresher Manual of Computer Science for Grade Xli
Computer Science 121
struct date char month[2]; char day[2]; char year[4];
} current_date;
array];
It consists only rows or columns
i.e. char name [201;
(ii) Multi-dimensional array:
data_type array_name [exp 1] [exp2];
e.g. char name [5] [25]; It contains rows and columns.
age:
#include <stdio.h> #include <conio.h> void main ()
char name [20]; mt age; printf (“Enter name:”); gets (name); printf (“Enter 1age \n”); scanf (“%d”, &age); printf(”\n Name :%s”, name); printf (“Age:%d”, age); getchO;
}
data_type member 1; data_type member2;
daa_type membern;
struct user_defined_name van, var2 e.g. struct student
struct student
{
char name [20]; mt age;
struct student
char name [20]; mt age; one;
printf (“Enter name scanf (“%s”, one.name); printf (“\n Enter age:”); scanf (“%d”, &one.age); printf (“\n Name : %s”, one. name);
printf (“Age :%d”, one.age); getch();
struct student a; In the above example, struct = keyword
student = structure data type name name[20] ,class and age =Member name a=declaring structure variable
The data members are accessed by structure variables with followed by a. (period sign), called dot operator.
The data of structure can be accessed in the way a. name;
a. class;
a. age;
with the help of dot operator.
Example:
/* Declare a structure and initance together *1
one;
e) Example : Display name & Example : Display name &
{
2. Differentiate between array and structure with examples.
[HSEB-2O6
Ans: Differentiation between array and structure:
Array Structure
age:
#include <stdio.h> #include <conio.h> void main ()
a) Array is the collection of data items which will have the same name.
It is a kind of user define data type which can store the data of various type such as character, integer etc.
b)
c)
The individual array elements are distinguished from one another by value that is assigned to a subscript or index.
Array has its type and these
Structure is not represenrc by index or subscript.
Structure has no type
are:
(i) one dimensional array
d)
(ii) multi dimensional
array
The syntax of array: Syntax of structure:
(i) One dimensional array: struct user_defined_name datatype array_name [size of
3. Differences between structure and union with examples.
[HSEB-2065]
Ans: Diffreences between structure and union:
Structure
Union
a)
It is a kind of user defined data type which can store the data of various type such as character, integer etc.
Union is a collection of hetrogeneous data types
. 122 A Refresher Manual of Computer Science for Grade XII
Computer Science 123
scanf
(“%d”,
one.name);
&one.age);
printf (Age :%d’,
printf (“\n Name
: %s”,
one.age);
one.name);
getch 0;
printf (‘Age
:%d”,
}
one.age);
getch();
Ld(.41)a1U1IIT
Write a program to read roll number,name and age of a student
and display it in proper format.
Ans: #include<stdio.h> #include<conio .h>
struct student{
mt roilno;
char name[20];
mt age; Ja;
void main()
printf(”Enter roll number:”):
scanf(”%d”,&a.rollno);
printf(”Enter nape:”):
scanf(”%s”,a.name);
printf(”Ent’er age:”):
scanf(”%d”, &a.age);
print f(”%d\t %s\t %d”,a. rollno,a.name,a.age);
getchO;
2. Write a program to enter name,address and age of 5 different persons,print it in tabular format.
Ans: #include<stdio.h> #include<conio.h>
struct student{
char name[20];
char add[20]; mt age;
b)
Each element has specific memory space and takes more memory space than union.
Each element has no specific
memory space but space
allocated for largest elementis is
utilized by other sized element.
c)
Keyword,i.e.struct is
required to declare structure,
Keyword ,i.e.union is required to declare union
d)
Syntax of structure:
struct user_defined_name
{
data_type member 1; data_type member2;
data_type membern;
};
struct user_defined_name van, var2 e.g. struct student {
char name [20];
mt age;
I;
struct student one;
Syntax of union:
union user_defined_name
1 4
data_type member 1; data_type member2;
data_type membern;
};
union user_defined_name van, var2 e.g. union student {
char name [20]; mt age;
};
union student one;
e)
Example : Display name & age:
#include <stdio.h> #include <conio.h> void main ()
{
struct student
{
char name [20]; mt age; one;
printf (“Enter name :\n”);
scanf (“%s”, one.name);
printf(”\n Enter age:”);
Example: Display name & age:
#include <stdio.h> #include <conio.h> void main ()
{
union student
I
char name [20]; mt age;
} one;
printf (“Enter name :\n”); scanf(”%s”, one.name); printf(”\n Enter age:”); scanf (“%d”, &one.age); printf (“\n Name : 124 A Refresher Manual of Computer Science for Grade Xli
void main()
mt i; for(i=0;i<5;++i)
{
printf(”Enter name:”); scanf(”%s”,a[i] .narne); fflush(stdin); printf(’ Enter address:”); scanf(”%s” ,a[ij .add); printf(”Enter age:”); scanf(”%d”,&a[i] .age);
}
printf(”\n\n”);
printf(”Name\tAddress\tAge\n”);
printf(”
for(i=0;i<5;++i)
printf(” %s\t %s\t %d\n”,a[iJ .name,a[i] .add,a[ij .age); getch();
3. Write a program to enter name, price and pages of 10 different books and display them in tabular format.
Ans: #include<stdio.h> #include<conio.h>
void main ()
struct book
{
char name [15]; float price;
mt pages; } list [101;
mt i;
II Entering data from keyboard for(i=O;i< 10;i++)
printf (“Enter name, price & pages of %d bq9k:”,(i + 1)); scanf (“%s %f %d”, list [ij.name, &list [ii. price,&list [i].
pages);
II Displaying data
Computer Science 125
printf (“Name \t price \t pages \n”);
for (i=0;i< 10;i++)
printf(”%s \ t % f\t % d\n”, list Ji].name, list [i].price, list
[ii. pages);
getch 0;
Write a C program to read name,marks in 5 different subjects of a student, find total, percentage. Print name, marks, total and percentage in tabular format.
#include<stdio.h>
#include<conio.h>
struct student{
char name[20]; mt mark[5];
}list;
void main()
{
mt tot=0,per,i; printf(”Enter name:”); scanf(”%s” ,list.narpe); for(i=0;i<5;i++)
printf(”
printf(”%s” ,list. name); for(i=0;i<5 ;i++) printf(”%d\t” ,list.mark[i]); printf(”%d\t%d\n’,per,tot); getchO;
Ans:
I
printf(”Enter mark:”);
scanf(’%d”,&list.mark[i]);
tot=tot÷list.mark[i];
per=tot/5;
printf(”NAME\tsub 1 \tsub2\tsub3\tsub4\tsub5\tTOTAL\t per\ n”)
—\n”); Computer Science 127
126 A Refresher Manual of Computer Science for Grade XII
5. Write a program in which you have to enter name, address and phone number of 5 different students and display all those information in tabular form. Phone number should be in between 5000000 and 9777777.
Ans: #include <stdio.h> #include <conio.h>
struct student
{
char name [20], address [15]; long mt phone;
list [5];
void main ()
mt i;
II Entering name, address & phone number of 5 diff. I/students
for (i=0;i<5; i ÷+)
{
printf (“Enter name :“); scanf(”%s”,list [i] .name); printf (“Enter address:”); scanf(”%s”,list [i] .address);
do {
printf (“Enter phone number:”); scanf (“%ld”, & list [i].phone);
}while(list[i] .phone<5000000 Ilmst[i] .phone> 9777777);
II Displahing data
printf (“Name \t Address \t Phone number \n”);
for(i=0;i<5;i+÷)
printf (“% s \ t% s \t% id \n”, list [i]. name, list [i].addre4 list [i]. phone);
getchO;
6. Program that reads the name, roll number and marks in different subjects of 10 students and prints name, roll and total marks obtained by each student.
Ans: #include <stdio.h> #include <conio.h>
struct student
mt roll; char name [201; float mark [5], total;
void main ()
mt i, j;
struct student list [10]; II Entering data for (i= 0; i< 10; i+
{
printf (“Enter name scanf(”%s”,list [i].name); prinft (“Enter Roll number \n”); scanf (“%d”, &list [ii. roll); list [i]total = 0;
printf (“Enter marks in 5 different sub jects:\n”); for(j=0;j<5;j+÷)
I
scanf(”%f”, & list [ii. mark[j]);
list [i].total = list [i].total + list [i]. mark [ji;
II Displa’ing result
printf(”\ n Roll number \t Name \t Total \n”);
printf (“ \n”);
for (i= 0; i< 10; i+
printf (“%d \t % s \t %f’, list [i]. roll, list [i].name, list [i].total);
getchO;
7. Write a program that reads different names and addresse into
• the computer; and sorts the name into alphabetical order using
structure variables. [HSEB-20641
Ans: #include<stdio.h> #include<conio.h> #include<string.h> struct stud{
char name [80] ,add[80] ,temp[80] ,temp 1 [801;
Ia[51;
{
void main()128 A Refresher Manual of Computer Science for Grade XII
Computer Science 129
mt i,j;
printf(”enter name and age:”); for(i=0;i<5 ;i++)
scanf(’%s%s’ ,a[i] .name,a[i] .add);
for(i=0;i<5;i÷+)
{
for(j=i+1;j<5;j-t-÷)
if(strcmp (a[i] .name,ã[j] .name) >0)
{
strcpy(a[il .temp,a[i] .name); strcpy(a[i] .name,a[j] .name); strcpy(a[j] .name,a [i] .temp);
strcpy(a[i] .temp 1 ,a[i] .add); strcpy(a[i] .add,a[j] .add); strcpy(a[jj .add,a[i] .temp 1);
}
printf(”The result\n”); for(i=0;i<5;i+÷)
printf(”%s\t%s\n” ,a[i] .name,a[i] .add); getchO;
(ii) Print out the data for students scoring more than 7.9. (iii) Print out the average class marks.
Ans: #include<stdjo.h> #include<conio.h>
struct student
mt roll; char name [25]; float mark; list [100];
void main ()
mt n, i, total’= 0; float average;
printf (“Enter number of students \n”); scanf (‘%d’, &n);
II Entering data
for (i = 0; i < n;i+÷)
printf (“Enter roll number :
do
scanf (“%d”, &list[iJ.roll);
}while (list[i].rll < 1 list [i]. rçill > 99);
fflush (stdin); printf (“Enter name scanf (“%s”, list [i]. name); printf (“Enter mark : \n”);
do
scanf(”%f’, & list [i].mark); }while (list [i].mark < 0 list [i].mark > 10); total = total + list [i]. mark;
average = total/n; II Displaying results for (i = 0; i < n; i++)
if (list [ii. mark <4. 0)
printf(”Roll = %d \n Name = % s \n Mark = % f “,list i].roll, list [ii. name, list [ii. mark);
8.
A higher secondary school has asked to write HLL program to
help them analyze their class test scores. The program must first
ask for the number of students ‘n’ and should have a looping
structure that loops through ‘n’ times to accept, validate and
store the data in array. The structure for each student is givéii below:
Field name Field type J Size Validation rule
Roll
numeric
121
1-99
Name
alphanumeric
25
Marks
numeric
2.1 0.0 — 10.0
IThe program must do
(i) Print out the data for students who have failed (obtained marks <4.0)
i130 A Refresher Manual of Computer Science for Grade XII
else if (list [ii .mark> 7.9) {
printf (“Roll = %d \n Name %s \n Mark = %f \t
mark is more than 7.9”, list [i]. roll, list [ii. name, list [i]. mark else;
printf (“Average marks = %f”, average); getch();
9. A higher secondary school in Kathmandu is in the process d computering its examination system. The following is the date structure for students marks processing.
Field Name
Field Type
Size
Validation
Rule
Regno
Numeric
6
030099-
060099
Name
Alphabetic
20
-
Year
Numeric
2
98-99
Sub ject 1
Numeric
3
0-100
Subject 3
Numeric
3
0-100
Subject 4
Numeric
3
0-100
Subject 5
Numeric
3
0-100
Develop a computer program in any of the high level 1angu you are taught in your class. The program should produce following outputs using menu system.
List all students with subjectwise marks, total mark, percenta and result.
Conditional Rules:
(a) Student must secure mark> or = 40 in order to pass each subject, failure subject should be marked with * adjacent Ii mark.
(b) Student securing > or = 50 and <65 percent marks iii aggregate but without failing in any subject should br declared II division.
(c) Student securing> or = 65 percent in aggregate should br declared in first division.
(d) Student securing> or = 40 and < 50 percent marks should be declared as third division.
#includeestdio.h> #includecconio. h> #include.cstring.h> struct student
mt regno, year;
char name [201, result [101, div [10]; float mark [51, total, per;
}list [50];
void main ()
mt n, i, j;
printf (“How many students ?“); scanf (“%d”, &n); for (i = 0; i < n; i÷+)
{
list [i] total = 0;
printf (“Enter registration number =‘);
do
scanf (“%d”, &list [ii. regno); }while (list [i].regno <30099 list [i].regno >60099); ifiush (stdin);
printf (“Enter name :“); gets (list [ij .name); printf (“Enter year:”); do
scanf (“%d”, &list[i]. year);
}while (list [i]. year <98 list [ii. year> 99); for(j=0;j<5;j++)
printf (“Enter marks :“);
do
scanf(”%f”, &list [I]. mark [j]);
}while (list [ii .mark[jl <Oil list [i]. mark [jj>100); list [i].total = list [i]. total + list [ii. mark [j];
for(j =0;j<5;j++)
if (list [ii. mark [j] < 40)
{
strcpy (list [1]. result, “failed”); goto down;
Computer Science
131
Sub frct 2 Numeric
3
0-100
Ans:
}struct employee mt emp_id;
char name [15], post [15]; float salary;
void main ()
struct employee rec[l00], temp; mt i, j, N;
printf (“How many employee ?“); scanf( /od , &N);
1/ Reading data
for (i = 0; i < N; i++)
printf (“Enter employee id :“); scanf (“%d” ,&rec [ii. emp_id); printf (“Enter name:”);
scanf(”%s”,rec [i]. name);
fflush(stdin);
printf (“Enter post:”);
scanf(”%s”,rec [i]. post);
fflush(stdin);
printf (“Enter salary :“);
scanf(”%P’, &rec[il.salary);
If Sorting
for(i=0;i<N;i÷+)
Computer Science 133
132 A Refresher Manual of Computer Science for Grade XII
else
strcpy (list [i]. result, “Passed”);
down:
if (strcmp (list[i].result, “passed”) == 0)
list [i].per = list [i]. total/5;
else
list [iJ.per = 0;
if (list [i]. per == 0 list [i]. per < 40)
strcpy (list [i].div, “*‘);
else if (list [i] per < 50)
strcpy (list [i]. div, “third”);
else if (list [i]. per < 65)
strcpy (list [i]. div, “second”);
else
strcpy (list[i]. div, “first”);
II Displaying results
printf (“\n Registration Number \t Name \t Year \t English \t Nepali \t Computer Science \t Maths \t Account \t Total \t Result \t Percentage \t Division \n”);
printf(” :
for (i = 0 i < n,i÷÷)
printf (“%d \t % \t %d”, list [iJregno, list [i].name, list[i]. year);
for (j =0; j <5; j+÷)
printf(”%f\t”, list [i]. mark [ji);
printf(” \f\t %s \t %f\t %s \n”, list [i]. total, list fi]. result, list [i]. per, list [i]. div);
getch 0;
10. Write a program that reads employee id, name, post and salary of N employee, sorts them in ascending order on the basis of employee id and prints them in appropriate format using structure variable.
Ans: #include<stdio.h> #include<conio.h>
for(j=i÷l;j<N;j÷÷)
if (rec[i] .emp_id < rec j]. emp_id)
temp = rec [i] ; rec [i] = rec [j]; rec [3] = temp;
else
II Displaying data134 A Refresher Manual of Computer Science for Grade Xli
Computer Science 135
printf (“\n Employee Id \t Name \t Post \ Salary \n”); printf(”
for (i= 0; i< N; i++)
printf(’%d\t%s\t %s\t
rec [i] .name, rec [ii. post,rec[i]. salary);
getch 0;
%.2f\n”,rec[i] .emp_id,
11. Write a program to read a set of names, roll number, sex, height
• and weight of the students from the keyboard and to sort them in ascending order using a structure within an array data type.
Ans: #include<stdio.h> #include<conio.h> #include.cstring.h> #define MAX 250 mt i, n;
struct school
char name [25]; mt rolino;
char sex [7];
float height;
float weight;
}student [MAX];
void main ()
I! school student [MAX];
void output (school student [MAX], mt n); void sort (school student [MAX], mt n);
printf (“How many data ?“); scani (“%d”, &n);
II Reading data
for (i = 0; i < n; i++)
{
printf (“Record = %d \n”, i + 1); printf (“Enter name : \n”); scanf(”%s”, student [i].name);
fflush(stdin);
printf (“enter roll number \n”); scanf(”%d”, &student[il. roilno);
printf (“Enter sex scanf(”%s”, student [i].sex); printf (“Enter height:\n”); scanf (“%f’, &student[i]. height); printf (“Enter weight : \n”); scanf (‘%f’,&student[i]. weight); printf (“\n n”);
// Calling function printf (“Unsorted data \n”); output (student, n); printf (“Sorted data \n\n”); output (student, n); getchO;
II Displaying result.
void output (school student [MAX], mt n)
{
printf (“Name \t Roll no \t Sex \t Height \t Weight \n”);
printf(” \n”);
for (i = 0; i < n; i+i-)
{
printf(”%s \t % d \t % s \t %f\t %f\t \n”, student [i]. name, student [ii. rolino, student [I]. sex, student [i]. height, student [i]. weight);
I
II Sorting
void sort (school student [MAX), mt n)
struct school temp; mt i, j;
for (i = 0; i < n; i++)
{
{
for (j = i-i-i; j <n;j++)
if (strcmp(student[i] .name, student[j] .name)<=O)
I
temp = student[i]; student [i] = student [j]; student [j] = temp;
I
I
fflush(stdin);
I136 A Refresher Manual of Computer Science for Grade XII
•12. Write a C program to pass structure as parameter to function.
Ans: #jnc u e<stdio.h> #include<conjo.h>
struct data{
float amount;
char fname[30}; char iname [301;
} rec;
void print_rec(struct data x); main()
{
printf(”Enter the donor’s first and last names,\n”); printf(”separated by a space: ‘); scanf(”%s %s”, rec.fname, rec.lname);
printf(’\nEnter the donation amount:
scanf(”%f’, &rec.amount); print_rec( rec);
getchO;
void print_rec(struct data x)
}
printf(”\nDonor %s %s gave Rs%.2f.\n”, x.fname, x.lname, x.amount);
1. What is a pointer?What are the advantages of pointer?
Ans: A pointer is a variable which stores the address number of reference number of a cell, instead of storing the actual value of the cell. It is really a very powerful variable which is used tø directly deal with memory of computer. A pointer is denoted by
(indirection operator) and has to be declared in the similar way as we declare other ‘ariables.
e.g. mt a; f/A normal variable
mt *p; I/A pointer that will point to an integer data
p = &a; I/Assign address of ‘a’ to ‘p’, pointer ‘p’ will II Point I/to the value of variable ‘a’.
Advantages of pointers are:
(a) It allows us to pass variables, arrays, functions, string and structures as function arguments.
(b) Pointers are more in handling the data table.
Computer Science 137
(c) They increase the execution speed.
(d) Pointer reduce the length and complexity of a program.
(e) It supports dynamic memory allocation and de allocation of memory arguments.
(f) The use of a pointer array to character strings results in saving of data storage space in memory.
2. What are the uses of pointer? How to declare pointer? Explain.
Ans: Uses of Pointers:
- Pointers are more efficient in handling the data array. They are used to manipulate arrays more easily by moving pointers to them instead of moving the arrays themselves.
- Pointers reduce the length and complexity of a program.
- Pointers are used to return more than one values from a function.
- Pointers are used to create complex data structures such as linked lists, trees etc.
- Pointer increases the execution speed.
- Pointers are used to communicate information about memory, which returns the location of free memory.
Eg. Using function like mallocO; Declaration of pointer variables
A pointer should be declared before its use like any other variable. Data type of the pointer is the data type of the variable to which it is pointing.
Pointer variable is defined by using an indirection symbol “. Using this operator, it becomes possible to point to the address of other variable. A pointer variable is declared as follows;
Syntax: Data_type ‘ variable_name; Eg; mt *ptr;
Here mt indicates that the pointer will point to variablçs of integer type. ‘“ indicates the pointer variable and ptr is the name of pointer variable that points to integer variable.
‘When pointer is declared, it doesn’t points to anywhere. #include<stdio.h>
#include<conioh>
void mainO
mt a,*p,*q;
printf(”Enter the value of a:”);
scanf(”%d”,&a);
-
p=&a; 138 A Refresher Manual of Computer Science for Grade XII
q=&p;
printf(”Value of a=%d\t Address=%d\n”,a,&a); printf(”Value of a=%d\t Address=%d\n”,*p,p); printf(”Value of a=%d\t Addrcss=%d\n,**q,*q); getchO;
3. Explain the meaning of each of the following declarations:
(i) mt *p;
(ii) mt * [10];
(iii) mt (*p) [10];
(iv) mt *p [void];
(v) mt [char *a]; [HSEB-2061]
Ans: Meaning of declared pointer statements are:
(a) mt *p; A point that will point to an integer data.
(b) mt [10]; p is 10-element array of pointer to integer data.
(c) mt (*p) [10]; P is a pointer to a 10-element integer data.
(d) mt *p [void]: P is a function that returns a pointer to an integer data.
(e) mt “p (char*a); P is a function that accepts an argument which is a pointer to a character and returns a pointer to an integer data.
4. What is the relation between array and pointer?Explain.
Ans: In fact, the compiler translate array notation into pointer notation when compiling. Since the internal architecture of the microprocessor understands pointers but doesn’t understand arrays.
To make clear the relationships between pointer and arrays here is
a simple program.
1* Print values from array*/
#include<stdio.h>
#include<conio.h>
void main()
{
mt i,num[5]={42,89,65,74,25}; for(i=0;i<5;i÷+)
printf(”Value=%d\t”,num [i]); getchO;
This is straight forward program. Array notation is used to access individual elements of the array in the expression num [i]. This expression can be replaced by *(num÷i) as:
#include<stdio.h>
#include<conio.h>
void main()
{
mt *piflum[5]{42 89 65 74 25}
for(i=0;i<5;i÷+)
printf(”Value=%d\t”,*(num÷i)); getchO;
Since array elements are always stored location a pointer then incremented immediately next location of its type. Here, num[i]=*(num÷i);
&num[i] =num+i
42
89
4001 4003 4005 4007 4009
if each elements of the array is an integer it takes up to two bytes.Here num points to the address,4001, which contains the value 42. On increasing num it points to the next memory location of its type. (i.e. address 4003, which contains the value 89, and so on)
Write a program to print values and addresses of 10 elements stored in an array.
Ans: #include<stdio.h> #include<conio.h>
void main()
mt i,n;
mt *p,*q,a[10]; p=&a[0];
q=p;
printf(”enter the value of N:’); scanf(”%d”,&n);
printfC’enter the %d numbers:\n”,n); for(i=0;i<n;i÷+)
Computer Science 139
in contiguous memory always points to an
65 74 I
251
;1] CIrogramming - 8;0]
j140 A Refresher Manual of Computer Science for Grade XII
2. Write a program to swap the values of two members using functions.
Axis: #include <stdio.h> #include <conio.h> void fun (mt “, int*); void main ()
mt a, b;
printf (“Eiter two integers :“); scanf (“%d%d”, &a, &b);
fun (&a, &b);
printf (Now, a %d \t b = %d”, a, b); getchO;
void fun (mt ‘x, mt *y)
I
3. Write a program that reads N integers and prints them ascending order using pointer and user defined function.
Ans: #include<stdio.h> #include.cconio.h> void arr(int 4’); mt i,j,n;
void main()
q=p;
printf(”enter the value of N:”); scanf(”%d”,&n);
printf(”enter the %d numbers:\n”,n); for(i=O;i<n;j++)
{
scanf(”%d”,p);
arr(q);
Computer Science
printf( “the array elements after sorting:\n”); for(i=O;i<n;i÷+)
printf(’%d\tI,*q);
q++;
getchO;
void arr(int *b)
{
for(i=0;i<n;i++}
for(j=i÷1 ;j<n;j++)
if(*(b÷j)>*(b+j))
{
mt temp=4’(b÷i);
*(b+j)=temp;
I
return;
4. Write a program to print values and address of 10 elements stored in an array. [use pointer].
. Axis: #include <stdio.h> #include <conio.h>
scanf(”%d” ,p); p+-i-;
printf(”the array elements after sorting:\n”); for(i=O;i<n;i++)
printf(”Address=%d\tValue=%d\n” ,q,*q); q++;
getchO;
}
141
)
I
mt temp; temp =
=
= temp;
in
mt *p,*q[ft]; Computer Sdence 143
142 A Refresher Manual of Computer Science for Grade XII
void main ()
{
}
mt *p i, a [10]; p = &a [10];
printf (“Enter 10 elements :
for(i=0;i< 10;i÷+)
{
}
scanf(”%d”, & p); p = p + 1;
p= &a[0];
for(i=0;i< 10;i++)
{ I
printf(”%d \t %d \n”, p);
p = p + 1;
getchO;
5. Write a program that reads computer marks of N different student and prints them. [Use malloc 0 function]
Ans: #include <stdio.h> #include <conio.h> #include <malloch> void main ()
{
mt p, *q, i, N; printf (“Enter N:”); scanf(”%d”, & N); p = (mt *) malloc (size of (int)*N);
q = p;
printf (“Enter computer marks of %dstudent”, N);
for (i= 0; i< N; i+
{
I.
scanf (“%d”, &p); p=p+l;
printf (“The elements are:
for (i= 0; i< N; 1+
printf (“The elements are :\n”); for (i=0;i<n;i++)
6. ‘,Write a program that reads roll, name and marks in 5 different subjects of N different students and prints them in appropriate ormat [Use structurepointer & malloc () function]
Ans: include<stdio.h>
\ I#include<conio.h> \#include<stdlib.h>
truct student
mt roll;
char name[25];
float mark[5];
mt n,i,j;
float total[5];
printf(”enter the no of student:”);
canf(”%d” ,&n);
J p=(struct student *)malloc(sizeof(struct student)*n); q=p;
4
for(i=0;kn;i÷+
{ total[i]=0;
printf(’enter the record ofstd[%d]:\n”,i+l); printf(”enter the roll:”);
scanf(”%d” ,&p->roll);
fflush(stdin); printf(”enter the name:”); gets (p->name);
I
printf (“%d *q); q = q + 1;
getchO;
I
I.
V
)id main()
struct student * *
q, p;
) Computer Science
145
printf(”enter the marks in 5 subjects:\n”); for(j=0;j<5;j++)
{
scanf(’%f” ,&p->mark[j]); total [ii =total[i] +p.->mark[j];
}
p++;
}//end of for i loop
clrscrO; printf(”\nRoll\tName\tSUB 1\tSUB2\tSUB3\tSUB4\tSU l\tDivi\tRemarks\n”); printf(”
I/to print the roll and name of student
printf(”%d\t%s\t” ,q->roll,q->name); I/to print the marks of 5 subjsects
for(j=0;j<5;j÷+)
I
if(q->mark[j] <40)
printf(”%O. 1 f”\t”,q—>mark[j]);
else
printf(”%. lf\t”,q->mark[j]);
I/to print the marks of particular student printf(”%O. 1 f\n”,total[i]);
q++;
I
getchO;
7. Write a program that will print out all the rotations of a string typed into it. For example, the rotations of the word “empty” are empty mptys ptysm tysmp ysmpt [use pointer]
Ans: #include <stdio.h>
#include <conio.h>
void main ()
I
inti,j,fl; -
char *S;
printf (“Enter a string :“); scanf (“%s”, str); n = strlen (str); for (i= 0; 1< n; i+
s = &str [i];
for (j 1; j < = strien (str); j +
printf (“%c”, *S);
s+÷;
if (‘i’s = = ‘\o’)
s = str;
printf (‘\n”);
printf (‘\n \n”); getchO:
8. Write a program which concates a string to other [use pointer]. Ajis: #include <stdio.h>
#include <conio.h> •
void main ()
{
char stri [20], str2[20];
mt i;
II Entering two strings :
printf (“Enter two strings :“); scanf (“%s %s’, strl, str2);
II Add two strings jreconcatenate (str2, str I); printf (“ \n \n After adding str2 to other”); printf (“ \n The new string : %s”, str2); getch 0;
preconcatenate (char ‘i, char *s);
while (*)
i ++;
while (*s)
144 A Refresher Manual of Computer Science for Grade XII
for(i=0;i<n;i++)
I
{
char str [20]; 146 A Refresher Manual of Computer Science for Grade XII
Computer Science 147
+ + = s + +;
* i = ‘\o’ ; II string termination character
9. Write a program to delete all vowei from a sentence. [Use pointer]
Ans: #include <stdio.h>
#include <conio.h> -
void main ()
char str [801, stri [80]; char *s, *p; printf (“Enter a sentence:”); gets (str);
s = str; II Base address of string p = stri; II Base address of new string while (*)
if(*s = ‘a’ s = = ‘e’ s = = ‘i’ Il*s = = ‘0’ S = = ‘u’)
s++;
else
.if(*s = = ‘A’II *s = = ‘E’ N*s ‘I, I s = = ‘0,11 *s = ‘U’)
else
I
=
= ‘\o’; -
printf (“ \n sentence removing after all vowels”); puts (stri);
getchO;
10. Write a program to enter a line of text and findout
(a) total number of vowels
(b) total number of constant
(c) total number of digit
(d) total number of space
(e) total number of other
Ans: #include <stdio.h> #include <conio.h> #include <ctype.h>
void sen(char line [], mt mt mt *d mt *w flt *0);
void main ()
void
char line [801;
mt v 0,c = 0,d = 0,s = 0,o = 0; printf (“Enter a line of text:”); gets (line);
Sen (line, &v, &c, &d, &w, &o); I/calling function printf (“ \n Number of vowels = %d”, v); printf(”\n Number of consonant = %d”,c); printf(” \n Number of digits = %d”, d); printf(” \n Number of space characters = %d”, s); printf(” \n Number of other = %d”, o); getch();
sen (char line [ 1’ mt *v, mt *c, mt *d mt iflt *0)
char c;
mt count = 0;
while ((c = toupper (line [count])) ! =
if(c = ‘A’ c = = ‘E’ c = = ‘I’ c = = ‘0,11 E = = ‘U’)
+ +
else if(c> ‘A’ && c < ‘z’)
1-
,1
else if(c> = o’ && c < = ‘9’)
+÷
else if(c = = ‘‘ c = = ‘ \t’)
++
else
++ 0;
++ count;
11. Write a program to find sum of three numbers using a pointer to function method.
Ans: #include <stdio.h> #include <conio.h>
void main ()
{
float sum (float, float, float); I/f” dccl” float a, b, c, avg; 148 A Refresher Manual of Computer Science for Grade XII
Computer Science 149
float (‘‘ptr) (float, float, float); II p?inter to f” dccl”
ptr = &sum; printf (“Enter three nos:”);
scanf(”%f%f%f”, &a, &b, &c); avg = (*ptr) (a, b, c); printf (“ \n Average = % 2f”, avg); getch();
float sum (float x, float y, float z)
{
}
float temp;
temp=(x÷y+z)/3.O; return temp;
ii:wiiif
What is data file ? Explain its type. Write down its mode.
Ans: It is a data structure which help us to store our data on the secondary storage media (i.e. hard disk, floppy disks etc.)
and to access and alter information whenever necessary. C programming has different types of library functions for creating and managing data files. Types of data files are:
A. High Level
Types of high level files are:
a. Text files
A text file file is a human-readable sequence of characters and words they form that can be encoded into computer-readable formats such as ASCII. A text file is also known as ASCII file and can be read by any word processing package. There is no sound or video files or graphical files.
b. Binary files
It organizes data into blocks containing contiguous bytes ofi information.It consists sound, images, graphical files etc. A binary file is made up of machine-readable symbols that represent l’s and, 0’s.
B. Low Level
Operation ‘modes’ of files are:
(i) r: open file for reading or display
(ii) w: open file for writing
(iii) a: open file for appending
2. Write down syntax of character input/output,string input/output,word input/output and formatted input/output.Also write the syntax of block read and write.
Ans: a) Character input/output
a.getcQ
It is used to read a single character from a file and returns the value of EOF.
The statement is ch=getc(fr); b.putc()
It is used to write a single character into a file. The function normally returns the character written but will return value of EOF if error is encountered.
The statement is putc(ch,Jj);
b) String input/output
a.fgetsO
It is used to read a set of characters as a string from a given file and copies the string to a given memory location normally in array. The general format of fgetsO is
fgets(sptr, n,ptr);
Where sptr=pointer to the location to receive string
n=count maximum number of character to be in the string
ptr=pointer to the file to be read
,1
bfputs
It is used to write a string to a given file. The general format of
fputs() is
fputs(sptr,ptr);
where sptr=pointer to the string to be written ptr=file pointer to file
c) Word input/output
a.getwO
It is used to read an integer value from a given file. The format of getw() is
getw(); b.putwO
It is used to write an integer quantity on the specified file. The syntax of putw() is
putw(w,fp);
where w is an integer value and fp is file pointer. 154 A Refresher Manual of Computer Science for Grade XII
printf(”Rojl numbertName\tMarks\n”);
FILE *fp; printf(”
mt st&no[MAXJ ,marks[MAXJ; for(i=O;j< 1 O;++i)
char name[MAXI[20]; I I
mt i,n; fscanf(fp, “%d%s%dfl,&rofl
Printf(”%d\t%s\t%d\n”,roll_number[i]
printf( How many data? ); }
scanf( /od ,&n); £1
ICJoserp);
fpfopen( record.dat , w+ );
getch
for(i=O;i<n;÷-i-i)
printf(”Enter roll number:”);
scanf(’%d”,&std_no[iJ); 6. Write a program to enter
fflush(stdin); students and store them in the
prmntf(”Enter name”); Axis: #inckide<stdio.h>
scanf( %s” ,name[i]); #include<conio.h>
printf(”Enter marks:”); void main()
scanf(’%d”,&marks[i]); {
fprintf(fp,”%d%s%d”,std_no[iJ ,name[lJ ,marks[iJ); FILE *fp;
• char name[JO][20J
rewind(fp);
printf(”Roll number\tName\tMarks\n”);
printf(” \n”); mt roll_number[IOJ,marks{IOJ;
for(iO;i<n;÷+i) mt i,n;
fscanf(fp,”%d%s%d”,&std_no [i] ,name[i] ,&marks[iJ); fpfopen(”c:\play.dat’, “w”);
printf(”%d\t%s\t%d\n’ ,std_no [i] ,namei1 ,marks [i}); for(iO• I O;++i)
fclose(fp); printf(”Enter roll number:”);
(L scanf(”%d”, &roll_number[j]);
fflush(stdjn);
5. Write a program for reading a data file. [HSEB-2064] printf(”Enter name”);
Ans: #include<stdio.h> scanf(’%s”,name{j]);
#include<coriio.h> printf(”Enter marks:”);
void main() scanf(”%d’&marb[jJ);
* fprintf(fp, “%d%s%d,roII number[i}
FILE fp;
mt roll number[IOJ,marks[1OJ;
— fclose(fp);
char name[IO][20];
getchO.
tnt i,n;
InJoncn(”c:\play.dat”,”r”); 154 A Refresher Manual of Computer Science for Grade XII Computer Science 155
printf(”Rojl numbertName\tMarks\n”);
FILE *fp; printf(”
mt st&no[MAXJ ,marks[MAXJ; for(i=O;j< 1 O;++i)
char name[MAXI[20]; I I
mt i,n; fscanf(fp, “%d%s%dfl,&rofl numberiji ,name [ii ,&marks [iJ);
Printf(”%d\t%s\t%d\n”,roll_number[i] ,namc[iJ ,marks [ii);
printf( How many data? ); }
scanf( /od ,&n); £1
ICJoserp);
fpfopen( record.dat , w+ );
getch
for(i=O;i<n;÷-i-i)
printf(”Enter roll number:”);
scanf(’%d”,&std_no[iJ); 6. Write a program to enter name,roll_number and marks of 10
fflush(stdin); students and store them in the fi1e- [HSEB-2065]
prmntf(”Enter name”); Axis: #inckide<stdio.h>
scanf( %s” ,name[i]); #include<conio.h>
printf(”Enter marks:”); void main()
scanf(’%d”,&marks[i]); {
fprintf(fp,”%d%s%d”,std_no[iJ ,name[lJ ,marks[iJ); FILE *fp;
• char name[JO][20J
rewind(fp);
printf(”Roll number\tName\tMarks\n”);
printf(” \n”); mt roll_number[IOJ,marks{IOJ;
for(iO;i<n;÷+i) mt i,n;
fscanf(fp,”%d%s%d”,&std_no [i] ,name[i] ,&marks[iJ); fpfopen(”c:\play.dat’, “w”);
printf(”%d\t%s\t%d\n’ ,std_no [i] ,namei1 ,marks [i}); for(iO• I O;++i)
fclose(fp); printf(”Enter roll number:”);
(L scanf(”%d”, &roll_number[j]);
fflush(stdjn);
5. Write a program for reading a data file. [HSEB-2064] printf(”Enter name”);
Ans: #include<stdio.h> scanf(’%s”,name{j]);
#include<coriio.h> printf(”Enter marks:”);
void main() scanf(”%d’&marb[jJ);
* fprintf(fp, “%d%s%d,roII number[i} ,flame [ij marks [i])•
FILE fp;
mt roll number[IOJ,marks[1OJ;
— fclose(fp);
char name[IO][20];
getchO.
tnt i,n;
InJoncn(”c:\play.dat”,”r”); 152 A Refresher Manual of Computer Science for Grade Xli
Computer Science 153
I
printf (“\n\n Data input \n \n \n”); fp fopen (“INFO.TXT”, “w”); while (ch = getchar Q! EOF) putc (ch, fp);
fclose (fp);
II Data output
fp fopen (“INFO.TXT”, “r”); while (ch = getc (fp) ! = EOF) printf(”%c”, ch); fclose (fp);
getch 0:
2. Write a program to enter name, address and telephone numbJ
10 number of students write them on STUD.DAT ifie and display them after reading from file.
Ans: #jndude <stdio.h> #include <conio.h>
void main ()
{
char name [30], add [20], long mt phone;
II File pointer declaration, FILE *fp;
II Open file for mode fp = fopen (“STUD.DAT”, ‘w÷”);
“
for (i = 0; i < 5; i+÷)
{
printf (‘Enter name :
scanf (“% s”, name [iJ); printf (“Enter address :
scanf(”% s”, add [i}); printf (“Enter phone:
scanf (“ %ld”, &phone [i]);
fprintf(fp,”%s%s%d”,name[i] ,add[i] ,phone[i]);
rewind (fp);
II Reading from file for (i = 0; i < 5; i++)
{
fscanf (fp, “%s %s %ld’, name, add, &phone),
printf (“Name = %s \t Address = %s \t phone = % \d”, name [iJ, add [i], phone [i]);
fclose (fp);
getchO;
3. Write a program to create a data file, inserts the characters into the file and prints the contents of file. [Use getc( ) and putc( ) functions I
Ans: #include<stclio.h> *
#includecconio.h>
void main()
FILE *fl; char ch; printf(’enter your text here:\n”); fl=fopen(’input.txt’,’w”); while(ch!=’.)
I
{
ch=getcharQ; putc(ch,fl);
fclose(fl);
j
printf(”\n data output\n”); fi ‘=fopen(”input.txt”,”r”); while(ch!=EOF)
ch=getc(fl); printf(”%c”,ch);
fclose(fl); getchO;
4. Write a program to store std_no,name and marks of ‘n’ students in a data fileDisplay the records in appropriate format reading
from file. [HSEB-2066]
Ans: include<stdio.h>
#include<conjo.h>
#define MAX 500
void main()156 A Refresher Manual of Computer Science for Grade XII
Computer Science 157
7. Develop a program that accepts a sentence for a data file. The
program also reads the data from that file and changes it into . ,, uppercase and lowercase text for uppercase file and lowercase file tf( %c ,ch);
respectively. Finally, the program prints all the contents of tclose(f2);
different files. [Use getc() and putc() functions] getchO;
.Ans: #include<stdio.h> }
#include.cconio.h>
#include<string.h> 8. Write a program that reads ‘n’ integers for a fit d
#include<’ctype.h> Integer from file to store in odd file (if odd) and even file
void main() A even) and fInally prints all the file in console.
.itS. #include <stdio.h>
* * . #include .cconio.h>
FILE fi, void main ()
charch; I
printf(”enter lowercase sentence:\n”); FILE *fp, *fpo *fpe.
fl=fopen(”upper.txt”,”w”); mt n, num, i;
do fp = fopen (“MAIN.DAT”, “W’);
printf (How many numbers i”);
ch=getcharO; scanf (“%d”, &n);
putc(toupper(ch),fl);/*writing the uppercase character in file*/ If Entering nos
}while(ch!=’\n’); printf (‘Enter %d number, n);
fclose(fl); for (i = o <n; i++)
printf(”\nData output\n”); SCaflf(”%d”, &num);
fi =fopen(”upper.txt”,”r”); Putw (mim,fp);
while((ch=getc(fl))!=EOF)
printf(”%c”,ch); fclose (fp);
printf(”\n”);
fclose(fl); fp = fopen (“MAIN.DAT”, “r”);
fpo = fopen (“odd.dat”, “w”);
printf(”ENTER UPPERCASE SENTENCE\n”); fpe fopen (“even.dat”, “w”);
for (i 0; i < n; i+÷)
f2=fopen( lower.txt , w ); {
do num = getw (fp);
( if(num%20)
ch=getcharO;
putc(tolower(ch,f2);/*writing the lowercase character in fij*/ else
} while(ch!=’\n’); putw (num, fpo);
fclose(f2); . }
fclose (fp)
f2=fopen(”lower.txt”,”r”); fclose (fpo);
prmntf(”\nData output\n”); fclose (fpe); 158 A Refresher Manual of Computer Science for Grade XII
printf (‘Content from MAIN.DAT”); fp = fopen (“MAIN.DAT’, “r”); while ((num = getw (fp))! = EOF) printf (‘%d \t”, num);
fclose (fp);
printf (‘content from odd.dat”); fpo = fopen (“odd.dat”, “r”); while ((num getw (fpo))! = EOF) printf(”%d \t”, num); fclose (fpo);
printf (“Content from even.dat”); fpe = fopen (“even.dat”, “r”); while ((num = getw (fpe))! = EOF) printf (“%d \t”, num); fclose (fpe);
getch();
9. Write a program that reads name, rank and country of N different players for a data file and prints all the information in descending order on the basis of rank.
Ans: #include<stdio.h>
#include<conio.h> #include<string.h> #define MAX 500 struct player
{
mt rank;
char name[1 5j,country[l 5 }list[IvIAX];
void main()
{
FILE *fp;
mt i,j,rtemp;
char ntemp[15],ctemp[1 5];
mt n;
printf(”How many records?:):
scanf(”%d”,&n); printf(”ADD RECORDS\n\n”); fp=fopen(”data.txt”,”w”); for(i=0;i<n;i++)
printf(”enter the record of player[%d]n “,i+ 1); fflush(stdin);
printf(”Enter the Name:”);
gets (list[i] .name);
printf(”Enter the rank”);
scanf(”%d’,&{jst[j] .rank);
fflush(stdjn);
printf(”Enter the country:”);
gets (list[iJ .country);
}
for(i=0;i<n;ji-÷)
{
for(j=i+ 1 ;j<n;j+÷)
if(list[i] .rank>list[j] .rank)
{
rtemp=list[i] .rank; strcpy(ntemp,list[jJ .name); strcpy(ctemp,Iist[i} .country);
list[i] .rank=list[j] .rank; stipy(1ist[i] .narne,Iist[jJ.name);
srrcpy(list[i] .côuntry,list[j].country);
list[j] .rank=rtemp;
strcpy(list[j] .name,ntemp); strcpy(list[j] .country,ctemp);
Svrite(&Iist,sjzeof(ljst), I ,fp); fclosc(fp);
clrscrQ;
fp=fopen(”data.txt”, “r”); prinrf(”Rank\tName\tcountryressn “); while(fread(&ljst,sjzeof(ljst)1 ,fp) == 1)
Computer Science 159
I160 A Refresher Manual of Computer Science for Grade XII for(i=O;i<n;i++)
printf(”%d\t%s\t%s\n”,list[i] .rank,list[i] .name,list[i] .country);
I
fclose(fp);
getchO;
I
10. Write a program that ask the user to input Name, Age of N different film actors for a file and prints them in appropriate format. [Use fwrite() and fread() functions]
Ans: #include <stdio.h.> #include <conio.h>
struct actor
{
}rcc;
mt age; char name [251;
void main ()
{
FILE *fp; mt i, N;
fp =. fopen (“dec.dat’, “w+”); printf (‘Enter how many :“); scanf(’% d”, &N);
II Entering data
for (i = 0; i <N; i+÷)
printf (“Enter name : \n”);
gets (rec.name); printf (“Enter age : \n”); scanf (“%d”, &rec.age);
fwrite (&rec, size of(rec), 1, fp);
rewind (fp);
II Displaying records
printf (“Name \t Age \n”);
printf (“
while (fread (&rec, sizeof (rec), 1, fp) = = 1) printf (“%s \t %d \n”, rec.name, rec.age);
I
fclose (fj3);
getch();
11. Develop a menu driven program to create a sequential data ifie
called employee.dat with following fie1ds Emp_code,
Emp_name, post and Salary. The program should work on
option as given below:
1. Add Record
2. Display Record
3. Search Record
4. Delete Record
5. Update Record
6. Exit
Ans: #include<stdio.h’ #include<conio.h> #include<process. h> #mnclude<string.h> struct employee
char name[201,post[1 51;
mt ecode; float salary;
I;
void main()
{
FILE *fp,*fpt;
struct employee list, temp;
mt ch,emco;
while(l)
printf(”\tMAJN MENU\n”); printf(” 1 .Add record\n’); printf(”2.Display record\n”); p rintf(” 3. Search record\n”); printf(”4.Delete record\n”); printf(”5.Update record\n”); printf(”6.Exit\n”); printf(”\n\n”); printf(”Enter your choice:”);
Computer Science 161162 A Refresher Manual of Computer Science for Grade XII Computer Science 163
scanf(”%d” ,&ch); printf(”Enter employee code:”);
scanf(”%d” ,&emco);
switch(ch) while(fread(&list,sizeof(list), 1 ,fp)== 1)
{
case 1: if(emco==list.ecode)
fp=fopen(”employee.dat”“a”); printf(”%dt%s\t%s\t%f\n”,1ist.ecode,list.name,list.post,list.sa1ary
printf(”Enter ecode:\n”); }
scanf(”%d”,&list.ecode); if(emco==O)
fflush(stdin); printf(”File not found”);
printf(”Enter Name:\n”); fclose(fp);
scanf(”%s”,&Iist.name); }
printf(”Enter post:\n”); break;
scanf(”%s”,&list.post);
printf(”Enter salary:\n”); case 4:
scanf(”%f’,&list.salary); {
fwrite(&list,sizeof(list), 1 ,fp); mt j=O;
fclose(fp); fp=fopen(”employee.dat”,”r”);
fpt=fopen(”temp.dat”, “w”);
break; fflush(stdin);
printf(”Enter employee code to delete:”);
case 2: scanf(”.%d”&emco);
{ while(fread(&list,sizeof(list), 1 ,fpt)== 1)
fp=fopen(”employee.dat” ,“r”); {
printf(”Ecode\tName\Post\Salary\n”); if(emco==Iist.ecode)
printf(” \n”);
while(fread(&list,sizeof(list), 1 ,fp)== 1) else
fwrite(&list,sizeof(list),1 ,fpt);
printf(”%dt%s\t%s\t%f\n” ,list.ecode,list.name,list.post,list.saláry fflush(stdin);
); }
fclose(fp); if(==O)
printf(”Record not found”);
break;
fclose(fp);
case 3: fclose(fpt);
{ remove(’employee.dat”);
fp=fopen(” employee.dat” ,“ r”); rename(” temp.dat”, “employee.dat”);
printf(”Such record has deleted\n”); 164 A Refresher Manual of Computer Science for Grade XII Computer Science 165
} rename(”temp.dat” ,“employee.dat”);
break;
case5: }
{ }
fp=fopen(”employee.dat” ,“ r”); break;
fpt=fopen(”temp.dat”,”w”); case 6:
fflush(stdin); exit(O);
printf(”Enter employee code to update”); default:
scanf(”%d”,&emco); printf(”Invalid Option”);
exit(O);
while(fread(&list,sizeof(list), I ,fp)== 1) 1
{ getchO;
if(emco==list.ecode) I
{ I
1.vrite(&list,sizeof(list),I ,fpt);
fflush(stdin);
printf(’Such record is not available\n”); 1) List some of graphics functions. Write a program that draws
1 different symbols such as circle, rectangle, line, ellipse and arc.
Ans:Some of graphics functions are:
else
(a) getmaxx Q— gets maximum number of column
(b) getmaxy () — gets maximum number of rows
fflush(stdin); ,, (c) line (xi, y, X2, y2) — draws a line starting from the coordinate
printf( Enter new name: ); 1 (xi, yi) to (X2, y2)
gets(temp.name); (d) circle (c, y,’I) — draws a circle with coordinate of center as x
printf(”Enter new post:”); & y and radius
gets(temp.post); (e) arc (x, y, stan, endan, hr, vr) : draws an arc with the center at
printf(’enter salary:”); x & y coordinate, starting angle (stan), ending angle (endan),
scanf(’%f’,&temp.salary); horizontal radius (hr) & vertical radius (vr).
(f) ellipse (x, y, stan, endan, hr, vr)
strcpy(list.name,temp.namc); where, x & y = screen coordinate
strcpy(list.post,tmp.post); stan = starting angle
list.ecode=emco; endan = ending angle
list.salary=temp.salary; hr = horizontal radius
yr = vertical radius
fwrite(&temp,sizeof(temp), I ,fpt); (g) rectangle (left_x, top_y, right_x, bottom...y)
(h) setcolor (color name) — color name means name of color i.e.
prlnu( The record is modified.\n); RED, GREEN etc. —
1 (i) Cleardevice 0 — clear graphics screen
fclose(fp); . .
fclose(fpt); ( ) — use to close all graphics driver using’ this
remove(”employee.dat”); 166 A Refresher Manual of Computer Science for Grade XII
Computer Science 167
L!l.iJ
1. Write a program to display circle using function of graphics.
Ans: #include<stdio.h> #include<conio.h> #includeczgraphics.h> void main ()
{
mt gd = DETECT, gm; initgraph (&gd, &gm,” \ tc \\ bgi”); setcolor(GREEN);
circle (300, 250, 40); getch();
closegraph ();
I
2. Write a program to display rectangle using function of graphics. Ans: #include<stdio.h>
#include<conio.h> #mnclude<graphics.h> void main()
{
I
mt gd = DETEcT, gm; initgraph (&gd, &gm, “ \\ tc \\ bgi’); setcolor(GREEN);
reectangle(5O, 10,260,180); getch (); closegraph 0;
3. Write a program to display ellipse using function of graphics. Ans: #include<stdio.h>
#include<conio.h>
#includeegraphics.h>
void main ()
mt gd = DETECT, gm; initgraph (&gd, &gm, “\ tc \\ bgi”); setcolor(GREEN);
ellipse (100, 100, 0, 360, 30, 20); getch();
closegraph 0;
jCIiT I I9S DLC)
1. What is a system? ‘What are the characteristics that must be idcntified before dealing with a particular system?
Ans: The word system is derived from the Greek word Systema which means an organized relationship among the functioning components. A system can be defined as any set of bjects and ideas, and their interrelationships, which are ordered to a common goal or purpose. Examples:-Computer system, library management system, account system, production system, respiratory system etc.
Simply, it is a set of elements joined together for a common objective. It can also be defined as the combination of people, devices and methods interrelated in working towards a common goal. Any system can not do any jobs without sub-systems. A subsystem is a part of large system. For example, an organization is a system and the parts like departments, accounting, information units etc are sub-systems.
Examples:business system, computer system, information system, solar system etc. Every system has boundary within, which it lies and outside of which is its environment.
In dealing with a system, it is possible to identif5 the following characteristics:
a) There is some specific purpose or function that must be fulfilled or performed.
b) There are a i’ikimber of components that can be identified as the necessary ingredients of the problem; each component has a variety of attributes that implicitly, physically and behaviorally are necessary for description.
c) These components are inter-related in some manner, satisfljing interface consistency between the components.
d) These are constraints that restrict the system’s behavior and the individual component response.
2. What is meant by MIS? Why do we need a computer-based information system?
Axis: The system in which data is converted to information is called information system. So, data is the major raw material in information system. MIS (Management Information System) is the system which provides the information for decision-making, organizing and controlling operation regarding the integration of the organization through the process of management. It helps manager of company to plan and control operation. MIS are made of people, computers, procedures, database and so on.
I
I168 A Refresher Manual of Computer Science for Grade XII
Computer Science 169
MIS
I ____ ___
Management Information System
We need computer-based information system because:
o Thesize. of organization is becoming large. Computer-based information system helps to run organization efficiently.
o Same data can be processed in different ways, i.e., manager can look at the performance of an organization in different angles.
o Organizations are distributed with many branches. So, exchange of information between branches and organization is essential.
o Account package can maintain, update and retrieval of data.
o Processing of data in high speed.
3. What is feasibility study ? For what purpose feasibility study used.
Axis: The process of analyzing whether the proposal is feasible, or not is called feasibility analysis. If it is not feasible, we need to look other alternatives. Feasibility study mainly focus on the demand of the system that affects the overall development of the information system.
The aims of feasibility study are:
(a) To determine whether the objectives stated in the assignment brief are reasonably attainable within the limitations and financial constraints period.
(b) To define major problem areas, so that the system analyst can plan the strategy for the field investigation.
(c) To find areas where potential exists for making saving in money, time or effort.
(d) To determine the approximate time required for the full:
investigation and cost.
(e)’ To discover the areas where some specialist knowledge is needed for the full investigation.
The different levels of feasibility snidies are Technical feasibility, Economical feasibility, Behavioural feasibility, Schedule
4. What is feasibility study? Explain different levels of feasibility study?
Ans: The different levels of feasibility studies are:
(I) Technical feasibility.
(2) Economical feasibility
(2) Behavioural feasibility
(4) Schedule feasibility
1. Operational feasibility: It is a measure of how well the solution of problems or a specific alternative solution will work in the organization. It is also measure of how people feel about the system. [If the system is not easy to operate, then operational process would be difficult. The operator of the system should be given proper training. The system should be made such that the user can interface the system without any tensional job.J
2. Technical feasibility: It is a measure of the availability of technical resources (hardware components or technical equipment). It also studies the availability of the technical manpower for the project. [If the work performances of the technical manpower are not experienced, the entire system will be certainly insufficient.)
3. Economical frasibility: Economical feasibility measures whether finances (investments) are available for proposed solution, i.e., it looks at the financial aspects (cost/effectiveness) of the project. This is often called a cost-benefit analysis.
4. Schedule feasibility: If a deadline (time-limit) is established, it is called schedule feasibility, i.e., the deadline of the project is studied under the schedule feasibility. The schedule feasibility is also depends upon available manpower and economical condition as well.
5.What is prototyping?
It is a method of developing software. It is new idea which is economic, easy and powerful. I*ototype means the duplication which may be complete or incomplete. Prototyping is not a complete program but it is a portion (skeleton) of any program. It does not contain any logic but only the inputs and outputs. “Prototype is an extra job in the development” but it helps us when there is missing data, when we implement system, to avoid the extra money and time.
The concept of prototyping is that it is practical to test portion of the system with the ultimate users before the total system is complete.
Management is the process or operation carried out by managers.

No comments:

Post a Comment