Answer keys S1S2 CS COMPUTER PROGRAMMING

Part A
1. High level and low level Languages:

Programming languages is a means of communication used to
communicate between people and the computer.

A programmer tells a computer what he wants it to do.
Computer Languages Types:
Low level languages
-
Machine Languages
Assembly Languages
High Level Languages -
Fourth Generation Languages
Very High Languages
Low level Languages :

consists of 0’s and 1’s(Machine language) and also Mnemonic
Codes(Assembly Languages).

In machine languages, the execution time is very less compare to other
languages because; the computer can understand instructions immediately.

This machine languages are difficult in nature and occupies less space.

In Assembly language, mnemonic codes were used instead of 0’s and 1’s used
in machine language.

Here each machine instruction is represented by meaningful mnemonics such
as ADD, SUB, MUL, DIV and data are specified.

Here transulator is needed to convert assembly language into machine
language. Hence assembler is used.

Compare to machine language, it gives little more readability, and also easy to
modify and isolate errors.
High Level Languages :

looks like normal English, so programming using these languages are very
easy.

But it requires the translator to convert these programs into machine
understandable form.

These are machine independent.

A single high level statement can substitute several instructions in machine or
assembly language.

This language is used in different types of computers with little or without
modification unlike low level languages, this reducing the re-programmming
time.

Some languages are BASIC, FORTRAN, COBOL, PASCAL, C, C++, JAVA,
Ada and so on.

Errors can easily be removed; also require less time to write and maintain.

It requires more space.
2. Time Complexity of algorithm:
worst case efficiency
is the maximum number of steps that an algorithm can take for any
collection of data values.
Best case efficiency
is the minimum number of steps that an algorithm can take any collection of
data values.
Average case efficiency
- the efficiency averaged on all possible inputs
- must assume a distribution of the input
- we normally assume uniform distribution (all keys are equally probable)
If the input has size n, efficiency will be a function of n
3. Flowchart for finding FACTORIAL of N numbers.
Start
Read N
i=1
IS
i<=N
Fact = Fact * i
i=i+1
Print Fact
Stop
4. Scope and life time of variables :
Feature
static
auto
extern
register
Storage
Memory
Memory
Memory
CPU register
Default Value
Zero
Garbage value
Zero
Garbage Value
Scope
Local
Local
Global
Local
Value of the
variables persist
between
different
function call
Till control
remain within
the block in
which variable
is defined
As long as
execution does
not end
Till the control
remains with in
the block in
which the
variable is
defined.
Life
5. To find FIBONACCI series upto 200:
#include<stdio.h>
#include<conio.h>
void main()
{
int fib=0, a=0, b=1, i, num;
clrscr();
printf(“\nEnter the number”);
scanf(“%d”,&num);
printf(“\n FIBONACCI SERIES \n”);
for(i=0;i<num; i++)
{
fib=fib+a;
a=b;
b=fib;
printf(“%d\t”,fib);
}
getch();
}
6. Compare and contrast Arrays and Structures:
S.No
1.
Array
Structures
An array is a collection of similar
data items.
A structure is a collection of
dissimilar data items.
An array is derived data type
It is a user defined data type.
It behaves like a built in data type
It must be declared and defined.
4.
An array can be increased or
decreased
A structure element can be added
if necessary.
5.
The Syntax
The syntax is
struct tagname
{
Datatype member 1;
Datatype member 2;
…….
};
Eg :
struct book
{
char name[20];
float price;
int pages;
};
2.
3.
datatype array_name[size];
6.
Eg,
int marks[10];
7. UNIX Architecture:
 Interaction between user and the hardware happens through OS.
 The high level of UNIX OS contains
o Hardware
o Kernel
o Commands
o Other application programs
Various features :
Portability
Machine independent
Multi user capability
Multitasking
security
8. Command Line Arguments:


It is a parameter supplied to a program when the program is invoked.
Command line arguments allows to pass the information when we ran the
program, generally the information can be passed into programs using main
function via command line arguments.
o Syntax
int main ( int argc, char *argv[] )
here,
argc – argument counter and contains the number of parameters
passed from the command line.
Argv – argument vector, which is an array of pointers to strings.
Eg 1:
int main(int argc, char *argv[])
{
if(argc !=2)
{
printf(“forgot to type name \n”);
exit(1);
}
printf(“ Hello %s”, arg[1]);
}
The command line program as shown above can be executed from the prompt by
specifying the name of the program along with arguments to that program as
C: \ TC > sample ComputerProgramming
It displays
Hello ComputerProgramming
Eg 2:
int main( int argc, char *argv[])
{
FILE *fp;
int i;
fp=fopen(argv[1],”w”);
for(i=2;i<argc;i++)
fprintf(fp,“%s”,arg[i]);
fclose(fp);
}
On executing the program,
> sample text xx yy zz aa
// Writing to file
PART B
I i) a) Functional Units of Computer:
INPUT UNIT
Three distinct units
 Input unit
 CPU
 Output unit
Input unit : accept data from outside world
Convert it to a form that computer can understood.
Supply the converted data for further processing.
Eg : keyboard, mouse, light pen, Trackball etc,
CPU :
Subdivided into 1) Control Unit
2) ALU
3) Memory Unit ( Primary, Secondary Storage)
Perform all calculations and decisions.
Controls and co-ordinates all units of computer
Output Unit:
Used to get response or result of a process.
Flow chart to find the roots of a quadratic equation:
START
READ A, B, C
D= b2 – 4ac
IS
d=0
Root 1 = - b / 2a
Root 2 = Root 1
Print “Equal Roots”
Print Root1, Root2
IS
d >0
X = - b / 2a
Y = √(b2-4ac) / 2a
STOP
Root 1 = - b +√(b2-4ac) / 2a
Root 2 = - b - √(b2-4ac) / 2a
Print “Distinct Roots”
Print Root1, Root2
Print “Imaginary Roots”
Print x+iy, x-iy
STOP
STOP
I) ii) steps involved in computer programming:
Program planning method:
Review the specification :
Requirements
Understanding
Sufficient instructions
Informal Design
List out major and minor tasks
Met all requirements
Formal design
Recognized format (blue print)
Rough sketch
Part of programmers documentation
Code and compile the program
Translate each design structure into programming language
Compiler
Test and debug
Execute with test data
Identify bugs
Debug the program
Use and maintain
Bug free
Make changes if necessary
Satisfy user necessary
Good Program
Expected result
ii) b) Operating System :
 Used to control and co-ordinate the computer system is called
operating system.
 Kernel is the master program
 Functions of OS
o Memory management
o Process management
o File management
o Device management
o Security management
o User Interface
II) i) a) Various usages of loop parameters:
The following loop structures are
 while..
 do … while
 for..
while – top tested loop – test the condition, true, means body of the loop will be
executed.
Related example program
Do- while : bottom tested – repetitive control structure
For loop : all three things need for loop can place in a single statement.
Additional features :
Can initialize more than one variable
Can increment or decrement more than one part in its corresponding
section.
Test condition may have any compound relation.
One or more section can be omitted.
II) i) b) explicit casting:
There may be some situation where we want to force a type conversion in a
way that is different from automatic conversion
Syntax:
(type_name) expression;
Eg : ratio = (float) female_number / male_number;
Also mention its related program.
II) ii) a) Basic structure of C program:
Documentation Section
Preprocessor Section
Definition Section
Global Declaration
main()
{
Declaration part;
Executable part;
}
Subprogram Section
{
Body of the sub program;
}
II) ii) b) Program to arrange in ascending order:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,n;
float a[50], temp;
clrscr();
printf(“Enter the last term of the array”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
scanf(“%f”,&a[i]);
for(j=i+1;j<n;j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
printf(“The elements in sorted order \n”);
for(i=0;i<n;i++)
printf(“%.2f”,a[i]);
getch();
}
III)
i) a) Dynamic Memory Allocation :
 It means, a program can obtain its memory while it is running.
 Disadvantage of static memory allocation leads to dynamic concept
 In C, dynamic memory allocation function are
i. malloc()
ii. free()
iii. calloc()
iv. realloc()
syntax :
 pointer_variable = (type_cast*) malloc(size in bytes);
 pointer_variable = (type_cast*) calloc(n, element
size);
 pointer_variable = realloc(ptr, new size);
 free(ptr);
III)
i) a)Need Array Variable:
Many applications require the processing of multiple data items that
have common characteristics. In such a situation it is convenient to
place such data items in an array.
Declaration
1D Array : datatype array_variable[size];
2D Array: datatype array_variable[row_size][column_size];
Accessing array:
Eg ;
void main()
{
int a[5], sum=0;
clrscr();
printf(“Enter 5 integer numbers\n”):
for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
sum = sum + a[i];
}
printf(“The sum of given Number is %d”, sum);
}
Program to multiply two matrices using pointers:
#include<stdio.h>
#include<conio.h>
void main()
{
int (*a)[20], (*b)[20], (*c)[20];
int i, j, n, r1, c1, r2, c2;
void get();
void display();
void mul();
clrscr();
printf(”Enter the size of A matrix : \n”);
scanf(“%d%d”,&r1,&c1);
printf(”Enter the size of B matrix : \n”);
scanf(“%d%d”,&r2,&c2);
if( c1 != r2)
{
Printf(“Multiplication not possible : Columns of matrix A are
not equal\n”)
}
else
{
printf(“\n Multiplication possible”);
for(i=0;j=0;i<r1,j<r2;i++,j++)
{
a[i] = (int*) malloc(c1*sizeof(int));
b[i] = (int*) malloc(c2*sizeof(int));
c[i] = (int*) malloc(c3*sizeof(int));
}
printf(“Enter the matrix A elements\n”, r1, c1);
get(a,r1,c1);
display(a,r1,c1);
printf(“\n”);
printf(“Enter the matrix B elements\n”, r2, c2);
get(a,r2,c2);
display(a,r2,c2);
printf(“\n”);
mul(a,b,c,r1,c1,c2);
printf(“The product matrices C \n”, r1,c2);
display(c,r1,c2);
getch();
}
}
void get(x,r,c)
int *x[10],r,c;
{
int i,j;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf(“%d”,x[i]+j);
}
void display(x,r,c)
int *x[10],r,c;
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf(“%5d”,*(x[i]+j));
printf(“\n”);
}
}
void mul( a, b, c, row, m, col)
int *a[10], *b[10], *c[10], row, m, col;
{
int i,j,k;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
*(c[i]+j) = 0;
for(k=0;k<m;k++)
*(c[i]+j) = *(c[i]+j) + (*(a[i]+k)) * (*(b[k]+j));
}
}
}
IV)
i) UNIX ‘make’ Utility:
 it is useful for development of program system that comprise more
than one file.
 It automatically keeps track of files that have changed and causes
their recompilation when necessary.
 Automatically relinks the program if required.
 It takes the file known as ‘make file’ as its input.
 It describes the following
i. Name of the files that make up the program system
ii. Their interdependencies
iii. How to regenerate the program system.
Eg:
dact
Main.c
init.c
process.c
cleanup.c
Process.h
Here making a change to any source file will necessitate recompiling that
program and also relinking the dact file.
$ cat make file
dact :
main.o
cc –o dact
main.o
:
main.c
init.o
:
init.c
init.o
main.o
process.o
cleanup.o
init.o process.o
cleanup.o
process.o :
process.c
cleanup.o :
cleanup.c
process.h
IV) ii) Program for file:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
Char another = ‘y’;
struct emp
{
char name[20];
int age;
float salary;
};
struct emp e[100];
fp = fopen(“Employee”,”w”);
if(fp = = NULL)
{
puts(“Cannot open file”);
exit();
}
while( another = = ‘y’)
{
printf(“\n Enter the name, age and salary:”);
scanf(“%s%d%f”, e.name, &e.age, &e.salary);
fprintf(fp,“%s%d%f”, e.name, e.age, e.salary);
printf(“\n Add another record (Y/N)”);
another= getche();
}
fclose(fp);
}
fp=fopen(“Employee”,”r”);
if(fp = = NULL)
{
puts(“Cannot open file”);
exit();
}
while( fscanf(fp,”%s%d%f”, e.name, &e.age, &e.salary)!=EOF)
printf(“%s%d%f\n”, e.name, e.age, e.salary);
fclose(fp);
}