You are on page 1of 29

1901006 – PROGRAMMING IN C

(COMMON TO AGRI, CIVIL, MECH, EEE AND EIE)


UNIT – 1 QUESTION BANK QUESTIONS WITH ANSWER
1. Define programming paradigm
Programming paradigms are the different patterns and models for writing a program.
The programming paradigms may differ in terms of the basic idea which relates to the
program computation.

2. Write the advantages of flowchart.


i. Flow charts are better way of communicating the logic of a system to all
concerned.
ii. With the help of flowchart, problems can be analysed in more effective way.
iii. The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
iv. Flowchart provided efficient program maintenance.

3. Distinguish between character and string.


A character literal constant can have one or at most two characters enclosed within
single quotes. Example: ‘A’, ‘\n’, ‘c’, ‘\f’
A string literal constant consists of a sequence of characters enclosed within double
quotes. Each string literal constant is implicitly terminated by a null (‘\0) character.
Example: “Rajesh”, “ “, “Akila”

4. What are keywords? Give an example.


Keyword is a reserved word that has a particular meaning in the programming
language. The meaning of keyword is predefined. A keyword cannot be used as an
identifier name in C language. There are 32 keywords available in C.
Example: auto break char int long else if for

5. What do you mean by expression?


An expression is a combination of values, variables and operators. There are many
forms of expression.
i. Arithmetic expression - 2+3*5-2/2
ii. Relational Expression - (a + b) < (c *d)
iii. Logical Expression - (a > b) && (a > c)

6. Identify the use of ternary or conditional operator.


Conditional operator is the only ternary operator available in C. The general form of
the conditional operator is as follows:
Exp1 ?Exp2 : Exp3
Where Exp1, Exp2, Exp3 are sub expressions. The expression Exp1 is evaluated first.
If it evaluates true then Exp2 is evaluated and Exp3 is ignored. If Exp1 is false then
Exp3 is evaluated and Exp2 is ignored.
Assume Let A = 10, B = 30.
Example: if(A > B) ? “A is big” : “B is big”

 
7. What is mean by Operators precedence?
Operator precedence defines the priority of the operators and the order in which the
expression will be evaluated containing operators. C operators have two properties
namely priority and associativity. Associativity indicates the order in which the
operators of equal precedence in an expression are evaluated.

8. What is the use of sizeof()?


The sizeof operator is a unary operator used to calculate the size of data types. This
operator can be applied to all datatypes. When using this operator, the keyword sizeof
is followed by a type name, variable or expression. The size of operator is used to
determine the amount of memory space that the variable or expression ordatatype
will take.
Example: int a = 10;
unsignedint result;
result = sizeof(a);
output = 2 bytes

9. How to create enumeration constants?


The enumerated data type is a user-defined type based on the standard integer type.
An enumeration consists of a set of named integer constants. In enumerated data type,
each integer value is assigned an identifier. The syntax of creating an enumerated data
type can be given as follows:
enumenumeration_name {identifier1, identifier2, identifier3 …… identifier n};
Example: enumColors{ Red, Blue, Green, Yellow, Black, White}

10. Differentiate between variable and constant.


A variable is defined as a meaningful name given to a data storage location in
computer memory.
A variable is an entity whose value can vary during the execution of a program.
Variables can be classified as Numerical variables and Character variables.
A constant is an entity whose value remains the same throughout the program.
The value of the constant is known to the compiler at the compile time.
Constants can be integer, floating, character and String types.
11. What is the output of the programs given below?
#include <stdio.h>
main()
{
int a = 20, b = 10, c = 15, d = 5;
int e;
e = (a + b) * c / d;
printf("Value of (a + b) * c / d is : %d\n", e );
}
Output: Value of (a+b) * c / d is : 90


 
12. Generalize the types of I/O statements available in ‘C’.
The I/O statements available in C are printf( ) and scanf( ) functions. The printf( )
function is used to display information required by the user and also prints the values
of the variables. The syntax of printf( ) function is
printf (“control string”, variable list);
Example: printf(“%d”, Reg_no);
The Scanf( ) function used to read formatted data from the keyboard. The syntax of
the scanf( ) function can be as follows:
scanf (“control string”, arg1, arg2, arg3 ………. argn);
Example: scanf(“%d %f”, &Rollno, &average)
13. What is header file? Why they are important?
A header file is a file with extension .h which contains C function declarations and
macro definitions to be shared between several source files. There are two types of
header files: the files that the programmer writes and the files that comes with your
compiler. Example stdio.h, conio.h, math.h

14. Show the difference between while and do-while.


While loop do-while loop
It is an entry-controlled loop It is an exit-controlled loop
It checks the condition first, if it is true It allows to execute the statements once
then it allows to execute the statements and then checks the condition.
inside the while body
Syntax: while (condition) Syntax:
{ do{
Statements; statements;
} }while (condition);

15. Invent the difference between ++a and a++.


++a is a pre-increment operation. It increments the operand value by one and then
assign to the operand.
a++ is a post-increment operation. It assigns the initial value to the operand and then
increment.
++a and a++ both are equal to a = a+1
Example:
void main()
{
int a=2, b= 2, c,d;
c = ++a;
d = b++;
printf(“%d%d%d%d\n”, a, b, c, d);
}

The output will be a=3, b=3, c=3, d=2.


The value of a is incremented and then it is assigned to c as a is pre-incremented.
The value of b is assigned to d before it is incremented as b is post-incremented.

 
16. Differentiate switch and nested-if statement.
Nested if else statement Switch Statement
It becomes complicated for multiple It is easy to understand for multiple
selections. selections.
It uses an independent expression for It uses single expression for all cases, but
each case each case must have a constant value of
integer type or character type.
The test condition can be given in a Only a single expression is given in the
special range of value. If the given switch statement which returns a single
condition matches then the statements value. The test condition cannot be given
under it will be executed. in s specified range.

17. Summarize the various types of C operators.


Operators in C
i. Arithmetic operators
ii. Relational operators
iii. Equality operators
iv. Logical operators
v. Unary operators
vi. Conditional operators
vii. Bitwise operators
viii. Assignment operators
ix. Sizeofopertor

18. Recommend the suitable example for infinite loop using while.
Infinite loop example:
Void main( )
{
Inti = 1;
While ( i< 10 )
{
printf(“%d\n”, i);
}
}
Here we are not updating the value of i. So after each iteration, the value of I remains
the same. As a result the condition (i< 10) will always be true. For the loop to work
correctly add i++;, just after the printf( ) statement.

19. Classify the narration of compiler and interpreter.


An interpreter translates high level instructions into an intermediate form, which it
then executes. In contrast, a compiler translates high-level instructions directly into
machine language. Compiled programs generally run faster than interpreted programs.

20. Distinguish between break and continue.


Break Continue
The break statement can be used in both The continue statement can appear only
switch and loop statements in loops.

 
When a break statement is encountered, it When a continue statement is
terminates the block and gets the control encountered, it gets the control to the next
out of the switch or loop iteration of the loop.
Example: Example:
for(I = 1; i<10; i++) for(I = 1; i<10; i++)
{ {
printf(“%d\t”, i); printf(“%d\t”, i);
if(i == 5) if(i == 5)
break; continue;
} }
Output: 1 2 3 4 5 Output: 1 2 3 4 6 7 8 9

PART – B
1. Describethestructure of a C program with an example.
Structure of a c program
Every c program consists of one or more functions, one of which must be called main. The
program will always begin by executing the main function. Additional function definitions
may precede or follow main. A function is a sequence of statements than can process the
given set of data according to the user’s requirements and may or may not provide outputs.

Comments may appear within a program, as long as they are placed within the delimiters /*
and */.
Each function should have a function name followed by list of parameters (which is optional)
within parenthesis.
Global declaration may be given outside all functions, usually at the beginning of the
program.
From a structural point of view, c consists of the following components:
1) Program comments (this can be placed anywhere)-optional.
2) Preprocessor directives(inclusion of header files)
3) Named constants –optional
4) Type declaration(various identifiers)
5) Function declarations(prototypes)
6) Statements(body of the main)
7) Function definitions
8) Function calls

In general, a c program will have the following structure


File Inclusion
Constant Definitions
External Variables Declarations
main()
{
Variable declarations;
Program statements;

 
}
User- defin
ned functioons

Example:
/*A simple Program*/
#include<sttdio.h>
#define MA AX 10
Int sum1,suum2;
main()
{
intaa,b;
floaatx,y;
….
….
}

2. Discuss about the con nstants, exp pressions an


nd Decisionn making sstatements in ‘C’.
Constants
A constantss is a quanttity that remmains unchaanged durinng the execuution of a program.
p
In c languaage, differennt types of constants are
a used. Thhey are inteeger, floatin
ng point,
character, string
s and symbolic
s tyype constan
nts. The octtal and hexxadecimal constants
are also useed as integeer constants..

CONSTANTS

NUMERIC  CHARACTOR 
CONSTANTS CON
NSTANTS

INTEGER  REAL  SINGLE 


CHARACTTOR  STTRING 
CONSTAN
NTS CONSTANTS CONSTANTS
CONSTANNTS

HEXA 
DECIMAL  OCTAL  FRACTIONALL  EXPONENTT  ESCAPE 
DECIMAL  DIRECT
CONSTANTS CONSTATNS FORM FORM SEQUENCE
CONSTANTS

Integerr constant
An integer
i consstant is a seequence of digits
d witho
out a decimaal point. Coomma and blank
b spacess are
not permmitted. An integer connstant may beb preceded d by a sign. In the abssence of a sign,
s the intteger
will be assumed to be positivee.
Valid: 654 +220152 -22045
Invalid:: 6985+ 12,356 50.254
a hexadecimal constants
Octal and


 
An octal integer is formed from the octal number system(o through 7), with a leading zero.
Valid octal constants : 00 056 -0536
Invalid octal constants : 35 0784 07.46
A hexadecimal integer constant is formed from the hexadecimal number system (0 through 9 and A
through F), leading with 0x or 0X. (the characters A to F represent the values 10 to 15 respectively)
Valid hexadecimal constants : 0x0 0x12A 0x35BC -0xAB8
Invalid hexadecimal constants : ox31A 0x41A.6 0XCPR
Floating point constants
Any number with a decimal point is called a floating point constant or a real constant it may
be written in the decimal form or exponential form.
Valid : 0.0 3.015 25. .25 -52.00F 0.4e-6f 1.33E+2
Invalid : 98 82.25E1.56 5642e-05
Character constants
The character data type is used to represent a single character. The qualifier signed or
unsigned may precede char to represent signed char or signed char. To store a char type of data, 8
bits (one byte) of memory is required whether it is signed or unsigned. The signed char values range
from -128 to 127 and the unsigned char values from 0 to 255. The implementation of char type is
machine dependent.
A character written within single quotes is called a character constant. A character constant
represent as integer value equal to the numerical value of the character in the machine’s character
code. If the system uses ASCII character code, the character constant ‘A’ represents the integer value
65.
Valid character constant: ‘X’ ‘a’ ‘8’ ‘>’ ‘+’ ‘ ‘
Invalid char constants : “a” ‘a8’ ‘}”
String constants
A string constant is a sequence of a characters enclosed with double quotes. Such a string
may or may nor convey a meaning
Valid string constants : “Valliammai Engineering College”
“Friday”
“875”
““
“-------------------------“
Symbolic constants
Inside a program certain constants may be frequently used. For instance, the constant
π=3.141592 may be used very frequently. Instead of writing the value 3.141592 each time, it may be
given a name, (say) “PI” and can be used in the place of that constant. Thus, if a constant is given a
name, it becomes a named constant or symbolic constant.
A symbolic constant is defined as follows:
#define constant_nameconstant_value
Where constant_name is and identifier used for the constant. Usually uppercase letter are
used for a constant name. blank spaces or comments should precede this name to separate it from
“define”. Constant_value can be any of the valid constant values. There is no semicolon at the end of
this statement.


 
Examples:
Valid Invalid Reasons
#define AP 3.15 #defineMM 10 No space before MM
#define MAXROW 10 #defineMAX 15; No space before MAX, and ; not allowed
#define\n ROW 10 #define MAN = 21 = is not allowed
#define\t COL 10

Expressions
An expression is a combination of identifiers and library functions using the above operators.
The final value of such expressions will be equal to a constant. The expressions can be classified as
arithmetic expressions or logical expressions depending upon the types of operators used.
Types of Expression:
i. Arithmetic Expression
ii. Logical Expression
iii. Relational Expression
iv. Mixed-mode Expression.
Decision Making Statements
A c program is normally executed sequentially in the order in which they appear. In practice, there
are a number of situations where we may have to change the order of execution of statements based
on certain conditions, or repeat a group of statements for certain number of times depending on some
conditions. This involves some kind of decision making and accordingly control is transferred to
execute some other statements in the program.
C supports a number of decision making capabilities or control structures which are used for
branching and looping. The following are the different control statements used in c language.
• The if statement
• The if-else
• The nested if statement
• The switch statement
• Break statement
• Continue statement
• The while statement
• The do statement
• The for statement

3. Illustrate about the various data types in ‘C’ and write a C program to find the
sum of 10 non-negative numbers entered by the user.
Data type or just type determines the possible values that an identifier can have and the
valid operations that can be applied on it. Data types are broadly classified as:
1. Basic data types (primitive data types)


 
a) Character (char)
b) Integer (int)
c) Single-precision floating point (float)
d) Double-precision floating point (double)
e) No value available (void)
S.No. Data type Range Memory Requirements
1. signed char or char –128 to 127 1 Byte
2. signedint or int –32768 to 32767 2 Bytes
3. shortint –32768 to 32767 2 Bytes
4. longint –2,147,483,648 to 2,147,483,647 4 Bytes
5. float –3.4 * 10–38 to 3.4 * 1038 4 Bytes
6. double –1.7 * 10–308 to 1.7 * 10308 8
Bytes
7. unsigned char 0 to 255 1 Byte
8. unsignedint 0 to 65535 2 Bytes
9. unsigned long int 0 to 4,294,967,295 4 Bytes
10. long float 8 Bytes
11. long double –3.4 * 10–4932 to 1.1 * 104932 10
Bytes
12. void Object of void type cannot be created

2. Derived data types: These data types are derived from the basic data types.
a) Array type e.g. char[ ], int[ ], etc.
b) Pointer type e.g. char *, int *, etc.
c) Function type e.g. int (int, int), float (int), etc.

3. User-defined data types: These data types can be created by using:


a) Structure
b) Union
c) Enumeration

Type Qualifiers: Type qualifiers are used to indicate the special properties of data
within an object.
1. constqualifier: Declaring an object constannounces that its value will not be
changed during theexecution of a program.
2. volatilequalifier: volatile qualifier announces that the object has some special
properties relevant tooptimization.
Type Modifiers: A type modifier modifies the range and the arithmetic properties of
the data type.
1. Signed (signed)
2. Unsigned (unsigned)
3. Short (short)
4. Long (long)
Declaration Statement: An identifier can be declared by making use of the
declaration statement. Thisstatement introduces the name of an identifier along with
its data type to the compiler before its use. Thegeneral form is:
[storage_class_specifier][type_qualifier][type_modifier] type identifier [=value[…]];
Example: int variable, int variable=20; int a=20, b=10; unsigned int variable; const
unsigned int variable;
Difference between Declaration and Definition:

 
Declaration only introduces the name of an identifier along with its type to the
compiler before it isused. During declaration, no memory space is allocated to an
identifier. Example: int variable;
Definition of an identifier means the declaration of an identifier plus reservation of
space for it in thememory. The amount of memory space reserved for an identifier
depends upon the data type of theidentifier. Example: int variable=20;

C program to find the sum of 10 non negative integers

#include<stdio.h>
#include<conio.h>
void main( )
{
inti, n, a[10], sum=0;
clrscr();
Printf(“Enter the range of the numbers…:”);
Scanf(“%d”, &n);
Printf(“\n Enter the numbers….:”);
for(i=0; i<n; i++)
{
scanf(“%d”, &a[i]);
sum = sum+a[i];
}
Printf(“\nThe sum of the numbers…%d”, sum);
getch();
}

4. (i). Explain the different types of operators used in ‘C’ with necessary program.
(ii). Write a C program to check the integer is Palindrome ornot.

(i). Different types of operators used in C


The operators can be classified basically two types:
1. Unary operators and
2. Binary operators

Unary operators contain only one operand in its preceding. The unary operators are
as follows:
i. Increment and decrement operators ( ++ and - - )
ii. size of operator (sizeof )
iii. unary minus ( - )
iv. & operator
v. * pointer operator
vi. - > indirection operator

Binary Operators are having two operands. The binary operators are as follows:
i. Arithmetic operators ( +, -, *, /, % )
ii. Assignment Operators ( =, +=, -=, *=, /=, %=)

10 
 
iii. Relational Operators ( <, >, <=, >=, != )
iv. Logical Operators (&&. ||, ! )
v. Conditional Operator (?:)
vi. Bitwise Operators ( &, |, ~, ^, <<, >> )

Explain the above all operators and give example.

(ii). C program to check whether the integer is Palindrome or Not

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,n1,s=0,r;
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
n1=n;
while(n1!=0)
{
r=n1%10;
s=s*10+r;
n1=n1/10;
}
if(n==s)
printf("%d is a palindrome\n",n);
else
printf("%d is not a palindrome\n",n);
getch();
}
Output:
Enter a number: 1546
1546 is not a palindrome
Enter a number: 12321
12321 is a palindrome
5. Explain in detail the operation of various looping statements in C with suitable
examples.(13)
The Looping statements available in C language are:
a. ‘for’ loop
b. ‘while’ loop
c. ‘do…while’ loop
The C language provides for three loop constructs for performing loop operations.
They are:
The while Statement: The simplest of all the looping structures in C is the while
statement. The basicformat of the while statement is
while (test-condition)
{
body of the loop

11 
 
}
The while is an entry-controlled loop statement. The test-condition is evaluated and if
the condition istrue, then the body of the loop is executed. After execution of the
body, the test condition is once againevaluated and if it is true, the body is executed
once again. This process of repeated execution of thebody continues until the test
condition finally becomes false and the control is transferred out of theloop. On exit,
the program continues with the statement immediately after the body of the loop. The
braces are needed only if the body contains two or more statements.

Example :The following program calculatesthe sum of squares of all integers


between 1 and 10.
main ( )
{
int n = 1, sum = 0;
while (n <= 10)
{
sum = sum + n * n;
n = n + 1;
}
printf (“sum = %d”, sum);
}
The body of the loop is executed 10 times for n = 1, 2, …, 10 each time adding the
square of the value ofn, which is incremented inside the loop.

The do-while Statement: The do-while statement takes the form:


do
{
body of the loop
}
while (test-condition);

On reaching the do statement, the program proceeds to evaluate the body of the loop
first. At the end ofthe loop, the test-condition in the while statement is evaluated. If
the condition is true, the programcontinues to evaluate the body of the loop once
again. This process continues as long as the condition istrue. When the condition
becomes false, the loop will be terminated and the control goes to the statement
that appears immediately after the while statement.

Since the test-condition is evaluated at the bottom of the loop, the do … while
construct provides anexit-controlled loop and therefore the body of the loop is always
executed at least once.
As an example, the following program prints the sum of first 10 odd numbers.
main ( )
{
inti = 1, sum = 0;
do
{
sum = sum + 2;
i = i + 2;
}
while (i< 20);
12 
 
printf (“sum = %d”, sum);
}
The loop will be executed as long as i< 20.

The For Statement: The for loop is another entry-controlled loop that provides a
more concise loopcontrol structure. The general form of the for loop is:
for (initialization; test-condition; increment)
{
body of the loop
}
The execution of the for statement is as follows:
1. Initialization of the control variables is done first, using assignment statements.

2. The value of the control variable is tested using the test-condition. The test-
condition is arelational expression that determines when the loop will exit. If the
condition is true, the body of the loopis executed; otherwise the loop is terminated
and the execution continues with the statement thatimmediately follows the loop.

3. When the body of the loop is executed, the control is transferred back to the for
statement afterevaluating the last statement in the loop. The control variable is
incremented using an assignmentstatement and the new value of the control variable
is again tested to see whether it satisfies the loopcondition. If the condition is
satisfied, the body of the loop is again executed. This process continues tillthe value
of the control variable fails to satisfy the test-condition.

Consider the following segment of a program:


for (x = 0; x <= q; x = x + 1)
printf (“%d”, x);
The for loop is executed 10 times and prints the digits 0 to 9 in one line. The for
statement allows fornegative increments also.
for (x = q; x >= 0; x = x – 1)
printf (“%d”, x);
This loop is also executed 10 times, but the output would be from 9 to 0. The braces
are optional whenthe body of the loop contains only one statement.

Additional features of for loop: The for loop has several capabilities that are not found
in other loopconstructs. For example, more than one variable can be initialized at a
time in the for statement. Thestatements

p = 1;
for (n = 0; n < 17; ++n)
can be written as
for (p = 1, n = 0; n < 17; ++n)

Like the initialization section, the increment section may also have more than one
part. For example,

for (n = 1, m = 50; n <= m; n = n + 1, m = m – 1)


{
p = m / n;
printf (“%d %d %d\n”, n, m, p);
13 
 
}
is valid. Test-condition may also have any compound relation. Consider the example
below:
sum = 0;
for (i = 1; i< 20 && sum < 100; i++)
{
sum = sum + i;
printf (“%d %d\n”, i, sum);
}
The loop uses a compound test-condition with the control variable i and external
variable sum. The loopis executed as long as both the condition i<= 0 and sum < 100
are true.
It is also permissible to use expressions in the assignment statements of initialization
and incrementsections. For example,
for (x = (m + n) / 2; x > 0; x = x / 2)
is perfectly valid. Another unique aspect of for loop is that one or more sections can
be omitted, ifnecessary. Consider the following statements:
……..
……..
m = 5;
for (; m != 100; )
{
printf(“%d\n”, m);
m = m + 5;
}
……..
……..
Both the initialization and increment sections are omitted in the for statement. The
initialization has beendone before the for statement and the control variable is
incremented inside the loop.

Time delay loops can also be set up using the null statement as follows:
for (j = 1000; j >0; j = j – 1)
;
This loop is executed 1000 times without producing any output, it simply causes a
time delay.
Nesting of For Loops: C language allows one for statement within another for
statement. The nestingmay continue upto 15 levels in ANSI C; many compilers allow
more.

The following program prints the multiplication table using nested for loops:
#define COLMAX 10
#define ROWMAX 12
main ( )
{
int row, column, y;
for (row = 1; row <= ROWMAX; ++row)
{
for (column = 1; column <= COLMAX; ++column)
{
y = row * column;
14 
 
printf (“%4d”, y);
}
printf (“\n”);
}
}
The outer loop controls the rows while the inner loop controls the columns.

6. Write a menu driven program in C to perform various arithmetic operations.

#include<stdio.h>
#include<conio.h>
Void main()
{
Intnum, sum, diff, prod, div;
Inta,b;
Printf(“Enter the values of a and b.”);
Scanf(“%d%d”, &a,&b);
Printf(“\nEnter the choice of the number…”);
Scanf(“%d”, &num);
Switch(num)
{
Case 1:
sum = a+b;
Printf(“\nThe sum of the numbers…%d”, sum);
break;
Case 2:
diff = a-b;
Printf(“\nThe difference of the numbers…%d”, diff);
break;
Case 3:
prod = a*b;
Printf(“\nThe product of the numbers…%d”, prod);
break;
Case 4:
div = a/b;
Printf(“\nThe division of the numbers…%d”, div);
break;
default:
Printf(“\nYou press other than 1,2,3,4…%d”, sum);
break;
getch();
}

15 
 
7. Illustrate a program to find out the average of 4 integers with the help of
flowchart.
#include<stdio.h>
#include<conio.h>
Void main()
{
Intno1, no2, no3, no4, sum;
floatavg;
printf(“\nEnter the values of numbers…:”);
scanf(“%d%d%d%d”, &no1, &no2, &no3, &no4);
sum = no1+no2+no3+no4;
avg = float(sum)/4;
printf(“\nthe sum of the numbers..%d”, sum);
printf(“\nthe average of the numbers..%f”, avg);
getch();
}
Draw the flowchart for the above program.

8. Discussabout pseudocodeand explain with an example (13).


Pseudo code
o Pseudo code consists of short, readable and formally styled English
languages used for explain an algorithm.
o It does not include details like variable declaration, subroutines.
o Itiseasiertounderstandfortheprogrammerornon-programmertounderstand
thegeneralworkingoftheprogram,becauseitisnotbasedonanyprogramming
language.
o Itgivesusthesketchoftheprogrambeforeactualcoding.
o It is not a machinereadable.
o Pseudocodecan’tbecompiledandexecuted.
o Thereisnostandardsyntaxfor pseudocode.

Guidelines for writing pseudo code:


o Write one statement per line
o Capitalize initial keyword
o Indent to hierarchy
o End multiline structure
o Keep statements language independent
Common keywords used in pseudocode
The following gives common keywords used in pseudocodes.
1. //:Thiskeywordusedtorepresentacomment.
2. BEGIN,END:Beginisthefirststatementandendisthelaststatement.
3. INPUT,GET,READ:Thekeywordisusedtoinputtingdata.
4. COMPUTE,CALCULATE:usedforcalculationoftheresultofthegivenexpression.
16 
 
5. ADD,SUBTRACT,INITIALIZEusedforaddition,subtractionandinitialization.
6. OUTPUT,PRINT,DISPLAY:Itisusedtodisplaytheoutputoftheprogram.
7. IF,ELSE,ENDIF:usedtomakedecision.
8. WHILE,ENDWHILE:usedforiterativestatements.
9. FOR,ENDFOR:Anotheriterativeincremented/decrementedtestedautomatically.

Advantages:
™ Pseudoisindependentofanylanguage;itcanbeusedbymostprogrammers.
™ Itiseasytotranslatepseudocodeintoaprogramminglanguage.
™ Itcanbeeasilymodifiedascomparedtoflowchart.
™ Converting a pseudo code to programming language is very easy as
compared withconvertingaflowcharttoprogramminglanguage.
Disadvantages:
™ Itdoesnotprovidevisualrepresentationoftheprogram’slogic.
™ Therearenoacceptedstandardsforwritingpseudocodes.
™ It cannot be compilednorexecuted.
™ For a beginner, It is more difficult to follow the logic or write pseudo code
as compared toflowchart.

Example: Greates of two numbers


BEGIN
READ a,b
IF (a>b) THEN
DISPLAYaisgreater
ELSE
DISPLAYbisgreater
ENDIF
END

9. Explain the following:


i. Keywords (3)
ii. Identifiers (3)
iii. C character set(3)
iv. Constants (4).
1. Keywords: Keyword is a reserved word that has a particular predefined meaning
in the programming language. A keyword cannot be used as an identifier name in
C language. There are 32 keywords available in C.

auto double int struct break else


long switch case enum register typedef
char extern return union const float
short unsigned continue for signed void
default goto sizeof volatile do if
static while

2. Identifiers: An identifier can be a variable name, a label name, a function name, a


typedef name, amacro name or a macro parameter, a tag or a member of a
structure, a union, or an enumeration. Therules to define an identifier in C are as
follows:

17 
 
1. Identifier name in C can have letters, digits or underscores.
2. The first character must be a letter (either uppercase or lowercase) or an
underscore.
3. No special character (except underscore) can be used in an identifier name.
4. Keywords or reserved words cannot form a valid identifier name.
5. The maximum number of characters allowed in an identifier name is compiler
dependent.
Example: Student_Name, StudentName, student_name, student1, _student.

3. C Character Set: A character set defines the valid characters that can be used in a
source program orinterpreted when a program is running. The set of characters
that can be used to write a sourceprogram is called a source character set, and the
set of characters available when the program is beingexecuted in called an
execution character set. The basic source character set of C language includes:

1. Letters: Uppercase letters: A, B, C, …, Z and lowercase letters: a, b, c, …, z


2. Digits: 0, 1, 2, …, 9
3. Special characters: , . : ; ! “ @ # % ^ & * ( ) { } [ ] <> | / \ _ ~ etc.
4. White space characters: blank space character, horizontal tab space character,
carriage return, newline character, form feed character.

4. Constants and Volatile Variables: Constants and volatile variables are type
qualifiers used toindicate the special properties of data within an object.
1. constqualifier: Declaring an object constannounces that its value will not be
changed during theexecution of a program.
2. volatilequalifier: volatile qualifier announces that the object has some special
properties relevant to optimization.

10. Write a C program for the following :


(i). To check whether a given year is leap or not.(5)
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf("Enter the year: ");
scanf("%d",&year);
if((year%400==0) || ((year%4==0) && (year%100!=0)))
printf("%d is a leap year.\n");
else
printf("%d is not a leap year.\n");
getch();
}
Output:
Enter the year: 2000
2000 is a leap year.
Enter the year: 1900
1900 is not a leap year.
18 
 
Enter the year: 2012
2012 is a leap year.

(ii). To find the roots of a quadratic equation.(8)


Program:
#include<stdio.h>
#include<math.h>
#include<conio.h>

void main()
{
inta,b,c,d;
float x1,x2;
clrscr();
printf("Enter the values of a, b and c: ");
scanf("%d%d%d",&a,&b,&c);
d=b*b-4*a*c;
if(d>0)
{
x1=(float)(-b+sqrt(d))/(2*a);
x2=(float)(-b-sqrt(d))/(2*a);
printf("The real and distinct roots are %.2f and %.2f.\n",x1,x2);
}
else if(d==0)
{
x1=x2=(float)(-b)/(2*a);
printf("The real and equal roots are %.2f and %.2f.\n",x1,x2);
}
else
{
x1=(float)(-b)/(2*a);
x2=(float)(sqrt(-d))/(2*a);
printf("The imaginary roots are %.2f+%.2fi and %.2f-%.2fi.\n", x1,
x2, x1, x2);
}
getch();
}
Output:
Enter the values of a, b and c: 1 -2 1
The real and equal roots are 1.00 and 1.00.
Enter the values of a, b and c: 1 -3 2
The real and distinct roots are 2.00 and 1.00.
Enter the values of a, b and c: 5 4 1
The imaginary roots are -0.40 + 0.20i and -0.40 - 0.20i.

11. Develop a C program for the following :


(i). To find the area and circumference of a circle with radiusr.(6)

#include<stdio.h>
#include<conio.h>
#define PI 3.14129
19 
 
void main()
{
floatr,p,a;
clrscr();
printf("Enter the radius: ");
scanf("%f",&r);
p=2*PI*r;
a=PI*r*r;
printf("The perimeter and area of the circle with radius %.2f are
%.2f and %. 2f.\n",r,p,a);
getch();
}
Output:
Enter the radius: 7
The perimeter and area of the circle with radius 7.00 are 43.98 and
153.94.

(ii). To find the sum of first 100integers.(7)

#include<stdio.h>
#include<conio.h>
void main()
{
inti,s=0;
clrscr();
for(i=1;i<=100;i++)
s=s+i;
printf("The sum of first 100 integers is %d.\n",s);
getch();
}
Output:
The sum of first 100 integers is 5050.

12. Write a C program for the following :


(i). To find the sum of the digits of a number. (123 =>1+2+3=6. (7)

Program:
#include<stdio.h>
void main()
{
int n,n1,s=0,r;
printf("Enter a number: ");
scanf("%d",&n);
n1=n;
while(n1!=0)
{
r=n1%10;
s=s+r;
n1=n1/10;
}
printf("The sum of the digits of the number %d is %d.\n",n,s);
20 
 
getch();
}
Output:
Enter a number: 12345
The sum of the digits of the number 12345 is 15.

(ii).To find the sum of all odd / even numbers between 1 and100. (6)

#include<stdio.h>
#include<conio.h>
void main()
{
inti,s_odd=0,s_even=0;
clrscr();
for(i=1;i<=100;i++)
if(i%2==0)
s_even=s_even+i;
else
s_odd=s_odd+i;
printf("The sum of all odd numbers between 1 and 100 is
%d.\n",s_odd);
printf("The sum of all even numbers between 1 and 100 is
%d.\n",s_even);
getch();
}
Output:
The sum of all odd numbers between 1 and 100 is 2500.
The sum of all even numbers between 1 and 100 is 2550.

13. Write a C program for the following :


(i). To generate the first n numbers in a Fibonacci series.(7)

#include<stdio.h>
#include<conio.h>
void main()
{
int n,f,f1=-1,f2=1,i;
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
printf("The Fibonacci series is...\n");
for(i=1;i<=n;i++)
{
f=f1+f2;
f1=f2;
f2=f;
printf("%d\t",f);
}
getch();
}
Output:
21 
 
Enter a number: 10
The Fibonacci series is...0 1 1 2 3 5 8 13 21 34
(ii). To find the factorial of a givennumber.(6)

#include<stdio.h>
#include<conio.h>
void main()
{
intn,f=1,i;
printf(“Enter the number…\n:”);
scanf(“%d”, &n);
for(i=1; i<=n; i++)
f = f * I;
printf(“the factorial of the number is ..%d”, f);
}

Output:
Enter the number… 5
The factorial of the number is … 120.

14. Write a C program to generate Armstrong number between 100 and 999. (13)

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
inti,s,r,n;
clrscr();
printf("The Armstrong numbers between 100 and 999 are...\n");
for(i=100;i<1000;i++)
{
n=i;
s=0;
while(n!=0)
{
r=n%10;
s=s+r*r*r;
n=n/10;
}
if(s==i)
printf("%d\t",i);
}
getch();
}
Output:
The Armstrong numbers between 100 and 999 are...
153 370 371 407

22 
 
PART-C

1. Develop a C program for the following:


(i) To check whether a number is prime or not. (8)
#include<stdio.h>
#include<conio.h>
void main()
{
intn,div;
clrscr();
printf("Enter a number: ");
scanf("%d",&n);
for(div=2;div<=n/2;div++)
if(n%div==0)
{
printf("%d is not a prime number.\n",n);
getch();
exit(0);
}
printf("%d is a prime number.\n",n);
getch();
}
Output:
Enter a number: 12
12 is not a prime number.
Enter a number: 23
23 is a prime number.

(ii). To convert the temperature given in Fahrenheit to Celsius and vice versa.(7)

#include<stdio.h>
#include<conio.h>
void main()
{
int choice;
doublef,c;
clrscr();
printf("\tTemperature Conversion\n");
printf("1. Celsius to Fahrenheit.\n");
printf("2. Fahrenheit to Celsius.\n");
printf("3. Exit.\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1 :printf("Enter the temperature in Celsius: ");
scanf("%lf",&c);
f=c*9/5+32;
printf("The temperature in Fahrenheit is %lf.\n",f);
23 
 
break;
case 2 :printf("Enter the temperature in Fahrenheit: ");
scanf("%lf",&f);
c=(f-32)*5/9;
printf("The temperature in Celsius is %lf.\n",c);
break;
case 3 :printf("Exiting...\n");
break;
default:printf("Wrong Choice...\n");
}
getch();
}
Output:
Temperature Conversion
1. Celsius to Fahrenheit.
2. Fahrenheit to Celsius.
3. Exit.
Enter your choice: 1
Enter the temperature in Celsius: 20
The temperature in Fahrenheit is 68.000000.
Temperature Conversion
1. Celsius to Fahrenheit.
2. Fahrenheit to Celsius.
3. Exit.
Enter your choice: 2
Enter the temperature in Fahrenheit: 68
The temperature in Celsius is 20.000000.

2.Compare and contrast branching and looping statements.(15).

Branching Statements:
1. Simple if statement
2. If….else statement
3. If…..else if….else statement
4. Switch statement.
Looping Statements:
1. While loop
2. Do…while loop
3. For loop

Explain the above with an example and write the answer of Question number 5 for looping
statements.

3. Design a C program to convert the given decimal number into binary, octal
andhexadecimalnumbers. (15).

#include <stdio.h>
#include <conio.h>
void swap(char *s1, char *s2)
24 
 
{
char temp;
temp = *s1;
*s1 = *s2;
*s2 = temp;
}
void reverse(char *str, int length)
{
int start = 0;
int end = length -1;
while (start < end)
{
swap(&str[start], &str[end]);
start++;
end--;
}
}
char* convert(intnum, char str[100], int base)
{
inti = 0;
if (num == 0)
{
str[i++] = '0';
str[i] = '\0';
returnstr;
}
while (num != 0)
{
int rem = num % base;
str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
num = num/base;
}
str[i] = '\0'; // Append string terminator
// Reverse the string
reverse(str, i);
returnstr;
}
void main()
{
charstr[100];
int n;
clrscr();
printf("Enter the given decimal number : ");
scanf("%d",&n);
printf("\nThe Binary value : %s\n",convert(n,str,2));
printf("\nThe Octal value : %s\n",convert(n,str,8));
printf("\nTheHexa value : %s\n",convert(n,str,16));
getch();
}

OUTPUT

Enter the given decimal number : 555


The Binary value : 1000101011
The Octal value : 1053

25 
 
The Hexa value : 22B

4. Summarize on algorithm, flowchart and pseudo code with an example.(15).

Algorithm
• Set of step-by-step instructions that perform a specific task or operation
• “Natural” language NOT programming language

Properties of Algorithms
™ Should be written in simpleEnglish
™ Eachandeveryinstructionshouldbepreciseandunambiguous.
™ Instructionsinanalgorithmshouldnotberepeatedinfinitely.
™ Algorithmshouldconcludeafterafinitenumberofsteps.
™ Should have an endpoint
™ Derivedresultsshouldbeobtainedonlyafterthealgorithmterminates.
Qualities of a good algorithm
The following are the primary factors that are often used to judge the quality of the
algorithms.
Time – To execute a program, the computer system takes some amount of time. The
lesser is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory
space. The lesser is the memory required, the better is the algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given
problem, some of these may provide more accurate results than others, and such
algorithms may be suitable.

Example
Write an algorithm to print „Good Morning”
Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop

Flowchart
• Visual program design tool
• “Semantic” symbols describe operations to be performed.

FLOWCHARTS
Definitions:
A flowchart is a schematic representation of an algorithm or a stepwise process, showing the
steps as boxes of various kinds, and their order by connecting these with arrows. Flowcharts
are used in designing or documenting a process or program.

A flow chart, or flow diagram, is a graphical representation of a process or system that details
the
sequencing of steps required to create output.

A flowchart is a picture of the separate steps of a process in sequential order.

26 
 
ADVANTAGES OF USING FLOWCHARTS
The benefits of flowcharts are as follows:
1. Communication: Flowcharts are better way of communicating the logic of a system to all
concerned.
2. Effective analysis: With the help of flowchart, problem can be analysed in more effective
way.
3. Proper documentation: Program flowcharts serve as a good program documentation, which
is needed for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis
and program development phase.
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program becomes easy with
the help of flowchart. It helps the programmer to put efforts more efficiently on that part
Logic Flowcharts are easy to understand. They provide a graphical representation of
actions to be taken.
7. Logic Flowcharts are well suited for representing logic where there is intermingling
among many actions.

Disadvantages
• Logic Flowcharts may encourage the use of GoTo statements leading to software
design that is unstructured with logic that is difficult to decipher.

• Without an automated tool, it is time-consuming to maintain Logic Flowcharts.

• Logic Flowcharts may be used during detailed logic design to specify a module.
However, the presence of decision boxes may encourage the use of GoTo statements,
resulting in software that is not structured. For this reason, Logic Flowcharts may be
better used during Structural Design

LIMITATIONS OF USING FLOWCHARTS


1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
2. Alterations and Modifications: If alterations are required the flowchart may require re-
drawing completely.
3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart
becomes a problem.
4. The essentials of what is done can easily be lost in the technical details of how it is done.

GUIDELINES FOR DRAWING A FLOWCHART


Flowcharts are usually drawn using some standard symbols; however, some special symbols
can also be developed when required. Some standard symbols, which are frequently required
for flow charting many computer programs.

27 
 
Symbols used to draw tha flowchart

Write the meaning and give one example of flowchart.

Pseudo code
o Pseudo code consists of short, readable and formally styled English
languages used for explain an algorithm.
o It does not include details like variable declaration, subroutines.
o Itiseasiertounderstandfortheprogrammerornon-programmertounderstand
thegeneralworkingoftheprogram,becauseitisnotbasedonanyprogramming
language.
o Itgivesusthesketchoftheprogrambeforeactualcoding.
o It is not a machinereadable.
o Pseudocodecan’tbecompiledandexecuted.
o Thereisnostandardsyntaxfor pseudocode.

Guidelines for writing pseudo code:


o Write one statement per line
o Capitalize initial keyword
o Indent to hierarchy
o End multiline structure
o Keep statements language independent
Common keywords used in pseudocode
The following gives common keywords used in pseudocodes.
//:Thiskeywordusedtorepresentacomment.
BEGIN,END:Beginisthefirststatementandendisthelaststatement.
INPUT,GET,READ:Thekeywordisusedtoinputtingdata.
COMPUTE,CALCULATE:usedforcalculationoftheresultofthegivenexpression.
ADD,SUBTRACT,INITIALIZEusedforaddition,subtractionandinitialization.
OUTPUT,PRINT,DISPLAY:Itisusedtodisplaytheoutputoftheprogram.
IF,ELSE,ENDIF:usedtomakedecision.
WHILE,ENDWHILE:usedforiterativestatements.
FOR,ENDFOR:Anotheriterativeincremented/decrementedtestedautomatically.
28 
 
Advantages:
™ Pseudoisindependentofanylanguage;itcanbeusedbymostprogrammers.
™ Itiseasytotranslatepseudocodeintoaprogramminglanguage.
™ Itcanbeeasilymodifiedascomparedtoflowchart.
™ Converting a pseudo code to programming language is very easy as
compared withconvertingaflowcharttoprogramminglanguage.
Disadvantages:
™ Itdoesnotprovidevisualrepresentationoftheprogram’slogic.
™ Therearenoacceptedstandardsforwritingpseudocodes.
™ It cannot be compilednorexecuted.
™ For a beginner, It is more difficult to follow the logic or write pseudo code
as compared toflowchart.

Example: Greates of two numbers


BEGIN
READ a,b
IF (a>b) THEN
DISPLAYaisgreater
ELSE
DISPLAYbisgreater
ENDIF
END

END OF UNIT – 1

29 
 

You might also like