Solution/Model Answer to VTU question paper (JUlN-JUL 2019 exam) is linked at the last of this page
Solution/Model Answer to current sem IATs, VTU question paper (Jan 2019 exam) is linked at the last of this page
Solution of 25 important question questions is linked at last of this page
Last experiment of lab - Binary to Decimal using recursion
/* Binary to decimal using recursion-Dr. P. N. Singh */
#include <stdio.h>
int len=0;
int bintodec(char binary[], int pos)
{
int temp;
if (pos == len)
return (binary[pos] - '0');/* ASCII '0'-'0'=0 and '1'-'0'=1 */
/* Left shift & Add current, recur for remaining digits*/
temp=(binary[pos]-'0') << (len-pos);
return (temp + bintodec(binary,pos+1));
}
int main()
{
char bin[100];
printf("Enter binary digits(0 & 1):");
scanf("%s",bin);
while(bin[len]!=NULL) len++;
len=len-1; /* coming before NULL*/
printf("Decimal equivalent = %d\n",bintodec(bin,0));
return (0);
}
Module 1 : Computer fundamentals notes/Important points
2nd Sem: CPS : Dr. P. N. Singh,Professor(CSE)
Computer Generations
Classification/Types of computers:
According to purpose:
a. Analog computers: Analog computer is a form of computer that is used to read & measure the physical phenomena such as electrical, mechanical, or hydraulic quantities (Not discrete) . Eg. Thermometer, Speedometer, Morse code Telex Machine, amplifiers etc.
b. Digital Computer: A computer that performs calculations and logical operations with quantities represented as digits, usually in the binary number system. Example: Calculator, laptops, PCS
c. Hybrid Computer: A combination of analog and digital computers those are capable of inputting and outputting in both digital and analog signals. A hybrid computer system setup offers a cost effective method of performing complex simulations. Here calculations are done digitally and actions are taken mechanically or vice-versa. Super computers and robots are hybrid computers.
According to size:
a. Super Computer: They are very large and very fast & task specific computers used by large organizations. These computers are used for weather forecasting, meteorology, earth-quack studies, research and exploration purposes. Super computers may be installed in satellites. NASA uses supercomputers for launching space shuttles, controlling them and for space exploration purpose. Example: Titan, Cray( of India)
b. Mainframe Computer: These are smaller and less faster than super computers. Large firms & government organizations like banks, railways use Mainframes to run their business operations in their head/central office as a central role to update day to day transactions. Using virtual machines, mainframes run the various operating systems as if they were running on different computers. Example z9, z10
c. Mini Computers: Minicomputers are used by small businesses & firms. Minicomputers are also called as “Midrange Computers”. Individual departments of a large company or organizations use Mini-computers for specific purposes. Example K202, IBM Midrange
d. Micro Computers: Desktop computers, laptops, PCs, personal digital assistant (PDA), tablets & Smartphones, Scientific Clculators, Notebook, Gaming console, Sound and navigation System are all types of microcomputers. The micro-computers are widely used & the fastest growing computers. Well known manufacturers are Dell, Apple, Samsung, Sony etc.
Bits & Bytes, Words: Number System
Ports & Connectors:
PS/2 (Personnel System 2) port
Serial Port
Parallel Port
S/P DIF (Sony/Philips Digital Interface)
VGA(Visual/Video Graphics Array/Adaptor) (Digital Visual Interface)
USB ((Universal Serial Bus) (Display port)
eSATAp (e-Serial Advanced Technology Port, Serial May be replaced by Parallel)
Wi-fi- Wireless Fidelity
Different files abbreviations
PDF : Printer Definition File or Portable Document Format
PNG: Portable Network Graphics
TIFF: tagged ImageFile Format
JPEG: Joint Picture/Photograhic Experts Group
PSD: Photoshop Document
GIF: Graphic Interchange Format
EPS: Encapsulated Postscripts
AI: Adobe Illustrator
Computer Network: computer network is a set of computers connected together for the purpose of sharing resources. The most common resource shared today is connection to the Internet. Other shared resources can include a printer or a file server. The Internet itself can be considered a computer network.
Basic Network Hardware
Network Cables: Network cables are the transmission media to transfer data from one device to another. A commonly used network cable is category 5 cable with RJ – 45 connector, as shown in the image below:
Routers: A router is a connecting device that transfers data packets between different computer networks. Typically, they are used to connect a PC or an organization’s LAN to a broadband internet connection. They contain RJ-45 ports so that computers and other devices can connect with them using network cables.
Repeaters, Hubs, and Switches : Repeaters, hubs and switches connect network devices together so that they can function as a single segment.
A repeater receives a signal and regenerates it before re-transmitting so that it can travel longer distances.
A hub is a multiport repeater having several input/output ports, so that input at any port is available at every other port.
A switch receives data from a port, uses packet switching to resolve the destination device and then forwards the data to the particular destination, rather than broadcasting it as a hub.
Bridges: A bridge connects two separate Ethernet network segments. It forwards packets from the source network to the destined network.
Gateways: A gateway connects entirely different networks that work upon different protocols. It is the entry and the exit point of a network and controls access to other networks.
Network Interface Cards : NIC is a component of the computer to connect it to a network. Network cards are of two types: Internal network cards and external network cards.
Languages & Protocols:
DNS: Domain Name System
FPT: File transfer Protocol
HTML (Hypertext markup Language)
HTTP(Hyper text Transmission Protocol)
TCP(Transmission Control Protocol)
IP(Internet Protocol)
SAP(Service Access Point)
IPv4 (Internet Protocol version 4): 4 octats
Software Basics
Types of software:
System Software
Application Software:
Utility Software
Generation Programming Languages: “Every age has a language of its own”
1. The first generation languages, or 1GL, are low-level languages that are machine language (0s & 1s).
2. The second-generation languages, or 2GL, are also low-level assembly languages. They are sometimes used in kernels and hardware drives, but more commonly used for video editing and video games.
Assembly Language Mnemonic Codes: (ADD, MUL)
Up to 2nd generation the languages were machine dependent.
3. The third-generation languages, or 3GL, are high-level languages, such as C, C++, Java, JavaScript, and Visual Basic.
4. The fourth-generation languages, or 4GL, are languages that consist of statements similar to statements in a human language. Fourth generation languages are commonly used in database programming and scripts examples include Perl, PHP, Python, Ruby, and SQL.
5. The fifth-generation languages, or 5GL, are programming languages that contain visual tools to help develop a program. Examples of fifth generation languages include Mercury, OPS5, and Prolog.
Programming Terms:
Source Code
Editor
IDE (Integrated Development Environment)
Object File
Executable File
Working with OS / Few OS Commands
ls
date
cat
cp
cd
rmdir
rm
mv
wc
gedit
….
Understanding PATH of file/directory
To compile a C Program: cc/gcc filename.c
To run last compiled C program : ./a.out
Model Answer/Solution to VTU Question
CBCS-17PCD23-Programming In C & Data Structure – June 2018
Dr. P. N. Singh, Professor(CSE), CMRIT, Bangalore
Q 1 a) Write basic structure of C Program and explain its different sections. 8 M
Ans:
Structure of a C program
· Documentation Section: This section is used to write Problem, file name, developer, date etc in comment lines within /*….*/ or separate line comments may start with // . Compiler ignores this section. Documentation enhances the readability of a program.
· Link section : To include header and library files whose in-built functions are to be used. Linker also required these files to build a program executable. Files are included with directive # include
· Definition section: To define macros and symbolic constants by preprocessor directive #define
· Global section: to declare global variables – to be accessed by all functions
· main() is the user defined function which is recognized by the compiler first. So, all C program must have user defined function main() { …………. }. It should have declaration part first then executable part.
· Sub program section: There may be other user defined functions to perform specific task when called.
/* Example: a program to find area of a circle – area.c
Dr. P. N. Singh - Documentation Section*/
#include <stdio.h> /* - Link/Header Section */
#define PI 3.14 /* definition/global section*/
int main() /* main function section */
{
float r, area; /* declaration part */
printf(“Enter radius of the circle : “); /* Execution part*/
scanf(“%f”, &r);
area=PI*r*r; /* using symbolic constant PI */
printf(“Area of circle = %0.3f square unit\n”, area);
return (0);
}
Q 1 b) What are rules to be followed to declare an identifier with example. 4 M
Ans:
Identifiers - Names of variables, function, or arrays are identifiers.
Rules to construct identifier:
è They may contain A-Z, a-z, and _ (underscore) (no blanks)
è An identifier name but must be started with an alphabet or _ (specific purposes)
è Maximum length of name of identifier should be 31 characters (ANSI C standards) however in newer versions length of identifier name may be more.
è Keywords & compiler constants should not be identifier name
Valid identifiers: num1, a_2
Invalid identifiers: $num1, for, 1st_paper_marks
Q 1 c) Write a note on different types of type conversions, with an example program for each. 8 M
Ans:
Type conversion concept in C language is used to modify a variable from one date type to another data type. New data type should be mentioned before the variable name or value in brackets which to be typecast.
Example:
result = (float) 20/3;
· It is best practice to convert lower data type to higher data type to avoid data loss.
· Data will be truncated when higher data type is converted to lower. For example, if float is converted to int, data which is present after decimal point will be lost
Type conversion can be done 2ways:
a) Implicit Type conversion / Coercion / Automatic type conversion
It is done by compiler automatically:
example:
printf(“%f”, 20/3.00);
b) Explicit Type conversion / A cast
By preceding the expression with type in parenthesis
It may be checked, unchecked or bit pattern.
Syntax:
(type) expression;
Q 2 a) Define C – tokens. List & explain different C - Tokens. 8 M
Ans:
Valid Characters (alphabets, numbers or symbols) used in C program are known as C – tokens.
Each and every smallest individual units in a C program are known as C tokens.
C tokens are the basic buildings blocks in C language which are constructed together to write a C program.
C tokens are of six types. They are,
Keywords (eg: int, while),
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg: “total”, “hello”),
Special symbols (eg: (), {}),
Operators (eg: +, /,-,*)
Example program for C - Tokens
int main()
{
int x, y, sum;
x = 10, y = 20;
sum = x + y;
printf ("Total = %d \n", sum);
}
where,
main – identifier
{,}, (,) – delimiter
int – keyword
x, y, sum – identifier
main, {, }, (, ), int, x, y, sum – tokens
Q 2 b)Write a C program to convert number of days into months and days. (Hint: Assume a month has 30 days) (For e.g. 45 days = 1 month 15 days) 4 M
Ans:
/* number of days into months and days */
#include <stdio.h>
int main()
{
int days,ndays,months;
printf("Enter number of days : ");
scanf("%d",&days);
months = days/30;
ndays=days%30; /* remainder by dividing 30 */
printf("%d days = %d months and %d days\n",days,months,ndays);
return (0);
}
Expected Output:
Enter number of days : 987
987 days = 32 months and 27 days
Q 2 c) Write a note on Operators precedence and associativity: 8 M
Ans:
Operator Precedence:
· If more than one operators are involved in a single expression, C language has a predefined rule of priority for the operators. This rule of priority of operators is called Operators precedence.
Example1:
printf(“%d”, 3 % 10 + 5); /* gives the output 8 */
Explanation: Modulas operator % has greater precedence than addition +. So, 3 % 10 will be 3 and adding 5 will give the result 8
Example2:
printf(“%d”, 3 + 4>5); /* gives the output 1 and not 3 */
Explanation: Arithmetic operator has greater precedence than relational operator so, 3 will be added with 4 first then 7 will be compared with 5 which gives the boolean output 1.
Example 3:
printf(“%d”, 1 > 2 + 3 && 4);
This expression is equivalent to:
((1 > (2 + 3)) && 4)
i.e, (2 + 3) executes first resulting into 5
then, first part of the expression (1 > 5) executes resulting into 0 (false)
then, (0 && 4) executes resulting into 0 (false)
· In C, precedence of arithmetic operators( *, %, /, +, -) is higher than relational operators(==, !=, >, <, >=, <=) and precedence of relational operator is higher than logical operators(&&, || and !).
ii) Associativity:
If two operators of same precedence (priority) is present in an expression, Associativity of operators indicate the order in which they execute (left to right or right to left).
Most of the operators have the asociativity left to right.
Example 1:
printf(“%d”, 10/5/2); /* output 1 – There should not be confusion that 10 is divided by 5/2 */
Example 2:
printf(“%d”, 1==2 !=3); /* output 1, 1==2 will give 0 and 0 != 3 will give 1 */
increment and decrement operators have associativity from right to left:
Example:
int n=7;
printf(“%d %d %d”,n++,n++,n++); /* gives output 9 8 7 and not 7 8 9 */
Q 3 a) An electric power distribution company charges its domestic consumers as follows: 8 M
Ans:
/* Electric charges */
#include <stdio.h>
int main()
{
int units;
float charges;
printf("Enter number of units consumed : ");
scanf("%d",&units);
if (units <= 200)
charges=units*.5;
else
if (units <= 400)
charges=100+(units-200)*0.65;
else
if(units <=600)
charges=230+(units-400)*0.80;
else
charges=390+(units-600); /* same if multiplied by 1.00 */
print("Amount to be paid : Rs.%0.2f\n",charges);
return (0);
}
Expected Output:
Enter number of units consumed : 459
Amount to be paid : Rs.277.20
Enter number of units consumed : 130
Amount to be paid : Rs.65.00
Q 3 b. Write the syntax of different looping control constructs and explain their working.8 M
Ans:
Ans:
There are 3 looping control statements in C:
while
do…while
for
while statement syntax:
while (condition)
{
statement1;
statement2;
......
}
/*working example – to display squares of numbers from 1 to 20 */
#include <stdio.h>
int main()
{
int x;
x=1;
while(x<=20)
{
printf(“%d %d\n”, x, x*x);
x++;
}
return (0);
}
do…while statement syntax: (It is a post tested loop & must executes at least once)
do
{
statement1;
statement2;
......
} while (condition);
/*working example – to display squares of numbers from 1 to 20 */
#include <stdio.h>
int main()
{
int x;
x=1;
do
{
printf(“%d %d\n”, x, x*x);
x++;
}while(x<=20);
return (0);
}
for statement syntax:
for (initialization; test condition; increment or decrement)
{
statement1;
statement2;
.....
}
/*working example – to display squares of numbers from 1 to 20 */
#include <stdio.h>
int main()
{
int x;
for(x=1;x<=20;x++)
{
printf(“%d %d\n”, x, x*x);
}
return (0);
}
Q 3 c) Distinguish between the following: 4 M
i) goto and if ii) break and continue
Ans:
i) goto and if
o goto statement is used to transfer the control of program flow from one place to another (not good). In general this can be done when a condition is evaluated by if conditional construct.
o goto is followed by a label name
o label is followed by : colon
example program :
/* goto with if */
#include <stdio.h>
int main()
{
int marks;
again:
printf("Enter marks (0-100) :");
scanf("%d", &marks);
if(marks<0 || marks > 100)
{
printf("Invalid marks!!!\n");
goto again;
}
if(marks>=40)
printf("Pass\n");
else
printf("Fail\n");
return (0);
}
ii) break and continue
break statement would only exit from the loop containing it.
//Example program to check a number whether it is prime
#include<stdio.h>
int main()
{
int n,d,prime=1;
printf(“Enter a number : “);
scanf(“%d”, &n);
for (d=2;d<n/2;d++)
{
if (n%d==0)
prime=0;
break; /* there is no need to check further */
}
if (prime)
printf(“Yes %d is a prime number.\n”, n);
else
printf(“No, %d is not a prime number.\n”, n);
return (0);
}
The continue statement is used in loops to skip the following statements in the loop and to continue with the next iteration (current iteration in for loop).
//Example program to enter marks (0-100) in 6 subjects for sum
#include<stdio.h>
int main()
{
int marks,sum=0, x;
for (x=1;x<=6;x++)
{
printf(“Enter marks %d : “, x)
scanf(“%d”, &marks);
if(marks <0 || marks > 100)
{
printf(“Invalid marks!!!\n”);
continue; /* again read marks for same paper */
}
sum+=marks;
}
printf(“sum of marks = %d.\n”, sum);
return (0);
}
Q 4 a) Write the syntax of nested if …else statement and explain its working 8 M
Ans:
Nested if ...... else statement: It is if within if
If first condition is satisfied then without taking the decision 2nd condition can be framed. So decision can be taken for 4 sets like
1st & 2nd both satisfied
1st satisfied but 2nd not satisfied
1st not satisfied but 2nd satisfied
1st and 2nd both not satisfied
Syntax:
if (expression/condition)
{ if (expression/condition)
{statement1; statement2; ..... }
else
{statement1; statement2; ..... }
}
else { if (expression/condition)
{statement1; statement2; ..... }
else
{statement1; statement2; ..... }
}
/* Example program to find maximum in 3 integers using nested if*/
#include <stdio.h>
int main()
{
int n1,n2,n3,max;
printf(“Enter 3 numbers : “);
scanf(“%d%d%d”,&n1,&n2,&n3);
if(n1 > n2)
if(n1 > n3)
max=n1;
else
max=n3;
else
if(n2 > n3)
max=n2;
else
max=n3;
print(“Maximum = %d\n”,max);
return (0);
}
Q 4 b) Write a C program to convert a decimal number to binary form. 8M
Ans:
/* Decimal to binary – converting in a Binary string with 0s and 1s*/
#include <stdio.h>
#include <string.h>
int main()
{
int dec,temp,rem,p;
char c,binary[50];
printf("Enter number of decimal number system: ");
scanf("%d",&dec);
temp=dec;
p=0;
while(temp!=0)
{
rem=temp%2;
if (rem==0)
binary[p]='0'; /* storing remainders */
else
binary[p]='1';
temp/=2;
p++;
}
binary[p]='\0'; /* last character NULL */
strrev(binary); /* reversing to make Binary String */
printf("decimal number = %d equivalent binary is %s\n",dec,binary);
return (0);
}
Expected Output:
Enter number of decimal number system: 20
decimal number = 20 equivalent binary is 10100
Q 4 c) Differentiate between do…while loop and while loop with the help of syntax. 4 M
Ans:
while and do… while loop both are iterative statements to execute the set of statements till condition is satisfied.
Difference:
· while is a pre-tested/entry-controlled loop and do…while is a post tested/exit controlled loop
· do … while loop must execute once irrespective of the condition because condition is
while statement syntax:
while (condition)
{
statement1;
statement2;
......
}
/*working example – to display squares of numbers from 1 to 20 */
#include <stdio.h>
int main()
{
int x;
x=1;
while(x<=20)
{
printf(“%d %d\n”, x, x*x);
x++;
}
return (0);
}
do…while statement syntax: (It is a post tested loop & must executes at least once)
do
{
statement1;
statement2;
......
} while (condition);
/*working example – to display squares of numbers from 1 to 20 */
#include <stdio.h>
int main()
{
int x;
x=100; /* x is initialized 100 */
do
{
printf(“%d %d\n”, x, x*x); /* it will display 100, 10000 */
x++;
}while(x<=20); /* here condition is checked and now it will not execute */
return (0);
}
Q 5 a) Write a C program to search a key integer element in the given array of N elements using binary search technique. Print the output with suitable headings. 8 M
Ans:
/* Binary search in given array of N elements */
#include <stdio.h>
int main()
{
int a[1000],x, y,temp,N, first, last, mid, skey, found;
printf("Enter number of elements : ");
scanf("%d", &N);
for(x=0;x<N;x++)
{
printf("Enter element %d : ", x+1);
scanf("%d",&a[x]);
}
/* now sorting - because Binary search requires sorted elements */
for(x=0;x<N;x++)
for(y=0;y<N-x-1;y++)
if(a[y] > a[y+1])
{
temp=a[y];
a[y]=a[y+1];
a[y+1]=temp;
}
printf("The sorted array:\n");
for(x=0;x<N;x++)
printf(" %d",a[x]);
printf("\nEnter search key integer : ");
scanf("%d",&skey);
first=0;
last=N-1;
found=0;
while(first <= last && ! found)
{
mid=(first+last)/2; /* integer value of mid */
if(a[mid] > skey)
last=mid-1;
else if (a[mid] < skey)
first=mid+1;
else
found=1;
}
if(found)
printf("Found at %dth position\n",mid+1);
else
printf("Not found\n");
return (0);
}
Expected Ouput:
Enter number of elements : 11
Enter element 1 : 22
Enter element 2 : 3
Enter element 3 : 44
Enter element 4 : 5
Enter element 5 : 66
Enter element 6 : 7
Enter element 7 : 88
Enter element 8 : 9
Enter element 9 : 111
Enter element 10 : 23
Enter element 11 : 54
The sorted array:
3 5 7 9 22 23 44 54 66 88 111
Enter search key integer : 88
Found at 10th position
Q 5 b) Distinguish between the following types of variables:
ii) Automatic ii) Global iii) Static iv) Register 8 M
Ans:
The storage class specifies the portion of the program within which the variables are recognized. variables can be categorized by storage class as well as data type. Storage class refers to the permanence of a variable and its scope within the program, that is, the portion of the program over which the variable is recognized.
auto (Automatic variables): They are local variables, available to the function in which it is declared. Their scope is confined to that function only. Variables declared within a function are by default of auto storage class.
auto int x,y,z;
int num; /* num is also interpreted as auto storage class
extern (Global variables): They are global variables, known to all the functions of the program from point of definition. Hence, they usually span more than one functions, and often an entire program. Variables defined outside of the program are by default of extern storage class.
int global = 200;
int fullmarks = 100; /*external storage class variable */
main( )
{
......
}
static (Static variable): Static variables have the same scope as automatic variables, i.e. they are local to the functions in which they are defined. Unlike automatic variables, however, static variables retain their values throughout the life of the program. As a result, if a function is called again, the static variables defined in the called function will retain their former values (They will not be reinitialized again. They are confined at the first initialization).
#include <stdio.h>
int func()
{
static int k = 0; /* by default also zero */
k++;
return (k);
}
int main()
{
int x, sum=0;
for(x=1;x<=5;x++)
sum+=func();
print(“sum = %d\n”, sum);
return (0);
}
register (Register variables) : Registers are special storage area within a computer’s central processing unit (In-built memory with CPU). The actual arithmetic and logical operations that comprise a program are carried out within this registers. The execution time can be reduced considerably if certain values can be stored within these registers rather than in computer’s memory.
The register variables are local to the function in which they are declared. The address of operator cannot ‘&’ cannot be applied to register variables.
register int x, y, z;
Q 5 c) Explain the importance strcmp( ) and strcat( ) string manipulation functions. 4 M
Ans:
Header file for all string handling functions is string.h
strcat(str1, str2) – Concatenates(appends) str2 to str1 at the end.
Syntax:
char* strcat (char* strg1, const char* strg2);
Example:
If two strings are:
char name[]=”Roma”;
char surname[]=”Ritambhara”;
Then to append “Ritambhara” with name “Roma”
strcat(name,surname);
printf(“%s”, name);
Output: Roma Ritambhara
strcmp( str1, str2) – Compares two string and returns:
· 0 if both strings are identical
· else returns difference based on ASCII value of first mismatch.
Syntax:
int strcmp (const char* str1, const char* str2);
Example:
printf(“%d”, strcmp(“SINGH”, “SINHA”);
output: - 1
Q 6 a) Write the syntax and give example for each: 8 M
i) Declaration of One-Dimensional array ii) Initialization of One dimensional array
iii) Declaration of Two-dimensional array iv) Initialization of Two-dimensional array
Ans:
An array is an identifier that refers to the collection of data items which all have the same name. The individual data items are represented by their corresponding array elements. Address of an element (subscript) ranges from 0 to n-1, where n is total number of elements.
i) Declaration of one-dimensional array:
One dimensional array:
syntax:
type variable[size];
Examples:
float height[50];
int batch[10];
char name[20];
ii) Initialization of one-dimensional array:
Examples:
int marks[5] = {76,45,67,87,92};
static int count[ ] = {1,2,3,4,5};
static char name[5] = {‘S’, ‘I’, ‘N’, ‘G’, ‘H’, ‘\0’};
iii) Declaration of Two-dimensional array:
syntax:
type arrayname[rowsize][columnsize];
Examples:
int stud[16][5];
iv) Initialization of Two-dimensional array:
Examples:
int marks[3][3] = {
{26,57,66},
{56,77,48},
{76,54,82}
};
int marks[3][3] = { {12},{0},{0}};
Here first element of each row is explicitly initialised to 12 while other elements are automatically initialized to zero.
Q 6 b) Write a C program to find nth term Fibonacci series using recursion. 8 M
Ans:
/* Fibonacci series using recursion */
#include <stdio.h>
int fibo(int n)
{
if (n==1)
return (0);
if (n==2)
return (1); /* first 2 terms 0 and 1 */
else
return (fibo(n-1)+fibo(n-2));
}
int main()
{
int n,x;
printf("Enter number of terms for Fibonacci series : ");
scanf("%d",&n);
printf(“%dth term of Fibonacci series is %d\n”, fibo(n));
printf(“Now series also\n”);
for(x=1;x<=n;x++)
printf(" %d",fibo(x));
return (0);
}
Expected Output:
Enter number of terms for Fibonacci series : 10
10th term of Fibonacci series is 34
Now series also
0 1 1 2 3 5 8 13 21 34
Q 6 c) Write a C program to find length of a string without usng strlen( ) function. 4 M
Ans:
/* length of string without using strlen() function*/
#include <stdio.h>
int main()
{
char str[50];
int len=0;
printf("Enter string : ");
while((str[len]=getchar())!='\n') /* reading string with spaces */
len++;
str[len]='\0'; /* last character NULL */
printf("Length of string is %d characters\n",len);
return (0);
}
Expected Output:
Enter string : Dr. Paras Nath Singh
Length of string is 20 characters
Q 7 a) Write a note on the following with an example for each: 8 M
i) Array of structure ii) Arrays within structures iii) Structures within structures
Ans:
Ans:
Structure is a data structure whose individual elements can differ in type. It may contain integer elements, character elements, pointers, arrays and even other structures can also be included as elements within a structure. struct is keyword to define a structure.
struct tag { type member1;
type member2;
type member3; ...... type member n;};
New structure type variables can be declared as follows:
struct tag var1, var2, var3, ....... varn, var[10];
i) Array of structure:
Whole structure can be an element of the array. A student structure with members roll, name and marks:
struct student
{
int roll;
char name[30];
int marks;
};
Now we can use this template to create array of 60 students for their individual roll, name and marks.
struct student s[60]; /* array of structure *
to access roll of student x : s[x].roll
ii ) Array within structure:
A member of structure may be array. In above example name is also array of characters. We
can create a structure of student with members roll, name & marks (array of integers) for 6
papers:
struct student
{
int roll;
char name[30];
int marks[6]; /* array within structure */
}s[60];
To access the marks of student x in paper y: s[x].marks[y]
ii ) Structure within Structure:
A structure may be defined within another structure or a structure variable may be declared as a member within another structure . Here date structure is defined within employee structure:
struct employee
{
int eno;
char name[30];
long int salary;
struct date /*structure within structure */
{
int dd, mm, yy;
}dob,doj;
}e[1000];
Or structure variable of date structure can be defined within employee if date structure is separately defined:
struct date
{
int dd, mm, yy;
};
struct employee
{
int eno;
char name[30];
long int salary;
struct date dob, doj; /* variable of date structure within employee*/
}e[1000];
To access day(dd) of date structure we will use member operator (.) dot operator in following way:
e[x].dob.dd
Q 7 b) Write a C program to count the number of characters, number oflines and number of white spaces from a file. 8 M
Ans:
/* To count number of characters, number of lines and number of white
spaces from a file */
#include <stdio.h>
int main()
{
FILE *fp;
char fname[64],c;
int nchars, nlines,nspaces;
printf("Enter file name : ");
scanf("%s",fname);
fp=fopen(fname,"r");
if(!fp)
{
printf("File %s does not exists\n",fname);
return (99);
}
nchars=nlines=nspaces=0;
while(!feof(fp))
{
c=fgetc(fp);
if(c=='\n')
nlines++;
else
if(c==' ')
nspaces++;
nchars++;
}
fclose(fp);
printf("Number of characters = %d\n",nchars);
printf("Number of lines = %d\n",nlines);
printf("Number of white spaces = %d\n",nspaces);
return (0);
}
Expected output for input file recfibo.c (6 b)
Number of characters = 343
Number of lines = 22
Number of white spaces = 58
Q 7 c) Create a structure st_record having members student name (sname) and student marks(smarks). Write a C program which reads name and marks of two students and compare whether both students are same. 4 M
Ans:
/* structure st_record */
#include <stdio.h>
#include <string.h>
struct st_record
{
char sname[20];
int smarks;
}s1,s2;
int main()
{
printf("Enter name and marks of student1 : ");
scanf("%s%d",s1.sname, &s1.smarks);
printf("Enter name and marks of student2 : ");
scanf("%s%d",s2.sname, &s2.smarks);
if(strcmp(s1.sname,s2.sname)==0) /* if names are same */
if(s1.smarks==s2.smarks) /* and if marks also same */
printf("Both students'name and marks are same-aa?\n");
else /* only names are same */
printf("Both students' names are same.\n");
else
printf("Both students are different\n");
return (0);
}
Expected Output:
Enter name and marks of student1 : panchali 76
Enter name and marks of student2 : panchali 76
Both students' name and marks are same-aa?
Enter name and marks of student1 : Ramesh 65
Enter name and marks of student2 : Ramesh 54
Both students' names are same.
Enter name and marks of student1 : Suresh 77
Enter name and marks of student2 : Ganesh 76
Both students are different
Q 8 a) Mention importance of the following input/output file operations along with syntax and example for each. 8 M
i) fscanf() ii) fprintf() iii) fopen() iv) fclose()
Ans:
fscanf( ) – formatted input from file
Syntax: fscanf(fp, “control string”, &var1, &var2,….&varn);
Example: fscanf(f2, “ %s %d”, item, &qtty);
fprintf( ) – formatted output to a file
Syntax: fprintf ( fp, “control string”, var1,var2,..varn);
file pointer variable,constants, strings
Example: fprintf( f1, “%s %d %f\n ”, name, age, 7.8);
fopen( ) – opens file different modes
Syntax:
FILE *fp;
fopen(filename,”mode”)
Example:
fp=fopen(“student.txt”,”r”);
File opening modes:
r-read only
w-write
a-append
fclose() – Closes the open file in memory. When file handling work is done, we should close the file.
Syntax:
fclose(file_pointer_name);
Example:
fclose(fp); /* fp is the file pointer name by which file was opened */
Q 8 b) Create a structure st_record having members to store name of student, marks scored in three different subjects. Create a user defined function cal_average( ) to compute average marks scored by the student. Write a C program which reads details of a student and prints whether a student is pass or fail. 8 M
Ans:
/* structure st_record */
#include <stdio.h>
struct st_record
{
char sname[20];
int marks[3];
};
float cal_average(int marks[3]) /* only array of marks from structure */
{
float avg=(marks[0]+marks[1]+marks[2])/3.0;
return (avg);
}
int main()
{
struct st_record s1;
printf("Enter name of students : ");
scanf("%s",s1.sname);
printf("Enter marks in 3 papers : ");
scanf("%d%d%d",&s1.marks[0],&s1.marks[1],&s1.marks[2]);
if(cal_average(s1.marks) >= 40) /* passing only array of marks */
printf("The student is pass\n");
else
printf("The student is fail\n");
return (0);
}
Expected Output:
Enter name of students : Rubiya
Enter marks in 3 papers : 34 78 54
The student is pass
Enter name of students : Ricky
Enter marks in 3 papers : 34 15 40
The student is fail
Q 8 c) Mention syntax and give an example for the following: 4 M
i) Structure definition ii) structure variable declaration
Ans:
Structure is a data structure whose individual elements can differ in type. It may contain integer elements, character elements, pointers, arrays and even other structures can also be included as elements within a structure.
i) Structure definition:
struct is keyword to define a structure.
Syntax:
struct tag
{
type member1;
type member2;
type member3;
......
type member n;
};
Example:
struct student
{
int roll;
char name[30];
int marks;
};
ii) Structure variable declaration
Structure type variables can be declared as follows:
Syntax:
struct tag var1, var2, var3, ....... varn, var[10];
Example:
struct student s1, s2,s3; /* s1, s2 & s3 are structure variables */
struct student s[60]; /* array of structure */
structure variables can be declared with structure definition also:
struct student
{
int roll;
char name[30];
int marks;
}s1,s2; /* s1 and s2 are structure variables */
Q 9 a) Write Syntax and give an example of function declaration of the following:
i) malloc( ) ii) calloc( ) iii) realloc( ) iv) free( ) 8 M
Ans:
Memory is allocated/de-allocated dynamically at run time as and when required. Dynamic memory management refers to manual memory management. This allows a programmer to obtain more memory when required and release it when not necessary.
In C there are 4 library functions defined under stdlib.h or alloc.h for the same
malloc( ) - Allocates a block of memory of specified size in bytes and return a pointer of type void which can be casted into pointer of any form
Syntax:
ptr = (cast-type*) malloc(byte-size)
Example for p is 2-d array:
p= malloc(sizeof(int)*rows*cols)
If p is cast type then one example
p = (int *)malloc(sizeof(int)*100);
calloc() – Contiguous allocation – Allocates multiple blocks of same size – requires two arguments
calloc(number_of_blocks, size_in_bytes_for_each_block)
ptr = (cast-type*)calloc(n, element-size);
ptr = (float*) calloc(25, sizeof(float));
realloc( ) : changes/reallocates the size of previously allocated space by malloc() or calloc()
Syntax:
ptr = realloc(ptr, newsize);
if size1 is allocated by malloc: ptr = (int*) malloc(size1 * sizeof(int));
then to rallocate for size2
ptr = realloc(ptr, size2);
free() – To deallocate the previously allocated space
Syntax/example:
free(ptr)
This statement frees the space allocated in the memory pointed by ptr.
Q 9 b) Write a note on categories of Pre-Processor directives. 8 M
Ans:
A pre-processor represents pre-compilation process. These directives are preceded with # ( and there is no semicolon at the end).
C has the special feature of pre-processor directives. The pre-processor processes the C source code before it passes to the compiler. Pre-processor directives are executed before the C source code passes through the compiler.
Pre-processor directives can be categorized in 2 groups:
· General Directives : These are written in header section of the program and there will not be control of compiler over it. They are processed before compilation of program starts.
Examples: #include, #define, #undef, #pragma
· Compiler control directives: These are conditional directives and may be written within program also. For example whether a macro is defined or not we can check it within program and redefine (general directives also) if required. Mostly #if family directives are of this category.
Examples: #if, #endif, #else, #ifdef, #ifndef
Examples of pre-processor directives:
i) #include
This pre-processor is used to include another file. File name is written in angle brackets or
within double quotes.
#include <stdio.h>
#include “SORT.H”
File name enclosed within angle brackets are searched in standard directories. File name
enclosed within double quotes are searched first in the current directory and if not found
then it is searched in the standard directories.
ii) #define
#define directive is used to define the symbolic constant or macro name with macro
expression.
#define symconstant value
#define macroname macroexpression
Example
#define PI 3.141
Here the C pre-processor searches for the symbolic constant PI the source code and
substitutes 3.141 each time it is encountered.
As the function, a macro can have argument. The argument of the macro name is replaced
with actual argument of the macro name, which is encountered in the program.
Examples:
#define MAX(x,y) ( (x) > (y) ? (x) : (y) )
#define CUBE(x) (x)*(x)*(x)
iii) #ifdef
#ifdef preprocessor directives checks whether a macro is defined by #define. If yes, it executes
the code:
Example:
#ifdef PI
Printf(“PI symbolic constant is already defined\n”);
#endif
iV) #ifndef
#ifndef preprocessor directives checks whether a macro is not defined by #define. If yes, it
executes the code:
Example:
#ifndef PI
#define PI 3.14
#endif
V) #pragma
#pragma preprocessor directives schedules the execution of function before and after main()
function by clauses startup and exit:
Example:
#pragma startup func2
#pragma exit func1
Here func2() function will execute before main() function and func1() function will
execute after main() function. There is no need to call these function from main()
Example program for macros:
#include <stdio.h>
#define cube(x) x*x*x
int main()
{
printf(“%d”, cube(5+2))
return (0);
}
It gives the output 27 and not cube of 7 i.e. 343 because a macro is expanded in which way it is defined 5+2 * 5+2 * 5+2 and it gives 27. We can say it is blunder definition of macro. It should be defined as:
#define cube(x) (x)*(x)*(x)
Then it will give correct result
Q 9 c) List two disadvantage : i) arrays ii) Linked list 4 M
Ans:
i) Arrays : An Array is collection of similar data types.
2 Disadvantages of array:
1) Size of array cannot be modified (grown or shrunk) during run-time.
2) There may be wastage or shortage of memory
ii) Linked list: Linked list is a dynamic data structure. It is chain or self referential data structure where a member of the structure points to structure itself.
2 Disadvantages of Linked list:
1) A linked list requires extra space in each node to keep address of next node.
2) Proper memory allocation and chain management is required for inserting deleting nodes ( danger of loss of chain-address of linked node)
Q 10 a) Write note on the following data structures: i) Linked list ii) stack 8 M
Ans:
i) Linked List:
A linked list is a dynamic data structure where member of a structure is pointing to structure itself. It is also known as self referential structure.
New nodes can be added as and when required allocating the memory at run time. It requires extra space for address of the linked/next node:
| data | next---|---->| data | next---|---->| data | next---|----> NULL
#structure definition of a linked list
struct LIST
{
int data;
struct LIST *next;
};
typedef struct LIST node;
ii) stack
Stack is a LIFO (Last In First Out) data structure. Items can be inserted or deleted from one end (top) only
/*stack push() operation given in a function */
void push(int stack[], int item)
{
if(top==size-1)
print(“Stack is full-overflow.\n”);
else
{
top++;
stack[top]=item;
}
}
/*stack push() operation given in a function */
int pop(int stack[])
{
int d;
if(top==-1)
{
printf(“Stack is empty-underflow\n”);
return (NULL);
}
else
{
d=stack[top];
stack[top]=NULL;
top--;
return (d);
}
}
Q 10 b) Write a C program which copies contents of a string to another using pointer as function parameter. Print copied string. 8 M
Ans:
/* string copy using pointer as function parmeter */
#include <stdio.h>
#include <stdlib.h>
void strkopy(char *source, char *target) /*char pointer as parameter*/
{
int x;
for(x=0;*(source+x)!=NULL;x++)
*(target+x) = *(source+x); /* copying character by character */
*(target+x)=NULL; /* last character NULL */
}
int main()
{
char *str1, *str2;
str1=malloc(50); /* allocating memory 50 bytes for each */
str2=malloc(50);
printf("Enter source string : ");
gets(str1);
strkopy(str1,str2); /* calling function passing reference */
printf("Copied string is %s\n",str2);
return (0);
}
Expected Output:
Enter source string : Yuvraj Singh
Copied string is Yuvraj Singh
Q 10 c): Mention Significance of Compiler Control Pre-Processor Directives. 4 M
Ans:
· Compiler control directives: These are conditional directives and may be written within program also. For example whether a macro is defined or not we can check it within program and redefine (general directives also) if required. Mostly #if family directives are of this category.
Examples: #if, #endif, #else, #ifdef, #ifndef
#ifdef
#ifdef preprocessor directives checks whether a macro is defined by #define. If yes, it executes
the code:
Example:
#ifdef PI
Printf(“PI symbolic constant is already defined\n”);
#endif
#ifndef
#ifndef preprocessor directives checks whether a macro is not defined by #define. If yes, it
executes the code:
Example:
#ifndef PI
#define PI 3.14
#endif
#else : it is used for alternative where #if, #ifdef or #ifndef condition is not satisfied:
#ifdef PI
printf(“PI symbolic constant is already defined\n”);
#else
#define PI 3.14
#endif
Solution/Model Answer to IAT-3
Programming in C & data Structure
2nd Sem I & J Section
-Dr. P. N. Singh, Professor(CSE)
1 a) Develop(write) a C program to display contents of a text file. (File name is given by user. Display appropriate error message if the file does not exist.) 05m
Ans:
/* dikhao.c - To display the contents of a text file */
#include <stdio.h>
int main()
{
FILE *fp;
char fname[64],c;
printf("Enter file name : ");
scanf("%s",fname);
fp=fopen(fname,"r");
if(!fp)
{
printf("File %s does not exist.\n",fname);
return (99);
}
printf("Contents of %s file:\n");
while(!feof(fp))
{
c=fgetc(fp);
putchar(c);
}
fclose(fp);
return (0);
}
1 b) Write a C program to copy contents of a file to another file. 05
/* kopy.c */
#include <stdio.h>
int main()
{
FILE *fp1, *fp2;
char sfname[64],tfname[64],c;
printf("Enter source file name : ");
scanf("%s",sfname);
fp1=fopen(sfname,"r"); /*opening source file with read permission.*/
if(!fp1){
printf("File %s does not exist\n",sfname);
return (99);
}
printf("Enter target file name : ");
scanf("%s",tfname);
fp2=fopen(tfname,"w"); /* opening target file with write permission*/
while(!feof(fp1))
{
c=fgetc(fp1); /* copying character by character in target file*/
fputc(c,fp2);
}
fclose(fp1);
fclose(fp2);
return (0);
}
2. Define file handling functions fgetc(), fputc(), fprintf(), fscanf(), fopen() with syntax and examples. 10
Ans:
fgetc( ) – reads a character from a file and moved the file pointer one character forward:
example:
c=fgetc(fp);
Reads a character from file pointed by file pointer fp and stores in character variable c
fputc( ) – Writes a character to a file and moved the file pointer one character forward:
example:
fputc(c, fp);
Writes character of c variable in file pointed by fp and moves the file pointer for next
Reads a character from file pointed by file pointer fp and stores in character variable c
fprintf( ) – formatted output to a file
Syntax: fprintf ( fp, “control string”, var1,var2,..varn);
file pointer variable,constants, strings
Example: fprintf( f1, “%s %d %f\n ”, name, age, 7.8);
fscanf( ) – formatted input from file
Syntax: fscanf(fp, “control string”, &var1, &var2,….&varn);
Example: fscanf(f2, “ %s %d”, item, &qtty);
fopen( ) – opens file different modes
Syntax:
FILE *fp;
fopen(filename,”mode”)
Example:
fp=fopen(“student.txt”,”r”);
File opening modes:
r-read only
w-write
a-append
3 a)
What are following declarations:
i. int *a[5];
ii. int (*p)[5];
iii. int *func( );
iv. int (*func)( ); 5m
Ans:
i. int *a[5];
/* Array of pointers - an array having all 5 element addresses only */
ii. int (*p)[5];
/*Pointer to arrays – Here p is pointer to 2-d array where 5 is number of columns */
iii. int *func( );
/*Pointer to return type of function – The function func() will return address */
iv. int (*func)( );
/* Pointer to function – here func pointer will keep address of other function */
3 b) Implement call by reference in a C program using pointers. 5 m
/* Call by reference using pointers */
#include <stdio.h>
void swap(int *p, int *q) /* here p and q are receiving addresses */
{
int temp = *p;
*p = *q;
*q = temp;
}
int main()
{
int num1, num2;
printf(“Enter number 1 : “);
scanf(“%d”, &num1);
printf(“Enter number 2 : “);
scanf(“%d”, &num2);
swap(&num1, &num2); /& call by reference */
printf(“Numbers swapped: num1 = %d num2 = %d\n”, num1, num2);
return (0);
}
4) Explain dynamic memory allocation & de-allocation by built-in functions 10m
Ans:
Memory is allocated/de-allocated dynamically at run time as and when required. Dynamic memory management refers to manual memory management. This allows a programmer to obtain more memory when required and release it when not necessary.
In C there are 4 library functions defined under stdlib.h or alloc.h for the same
malloc( ) - Allocates a block of memory of specified size in bytes and return a pointer of type void which can be casted into pointer of any form
Syntax:
ptr = (cast-type*) malloc(byte-size)
Example for p is 2-d array:
p= malloc(sizeof(int)*rows*cols)
If p is cast type then one example
p = (int *)malloc(sizeof(int)*100);
calloc() – Contiguous allocation – Allocates multiple blocks of same size – requires two arguments
calloc(number_of_blocks, size_in_bytes_for_each_block)
ptr = (cast-type*)calloc(n, element-size);
ptr = (float*) calloc(25, sizeof(float));
realloc( ) : changes/reallocates the size of previously allocated space by malloc() or calloc()
Syntax:
ptr = realloc(ptr, newsize);
if size1 is allocated by malloc: ptr = (int*) malloc(size1 * sizeof(int));
then to rallocate for size2
ptr = realloc(ptr, size2);
free() – To deallocate the previously allocated space
Syntax/example:
free(ptr)
This statement frees the space allocated in the memory pointed by ptr.
5. Explain any 5 pre-processor directives with example. Write 1 example program for macros. 10m
Ans:
A pre-processor represents pre-compilation process. These directives are preceded with # ( and there is no semicolon at the end).
C has the special feature of pre-processor directives. The pre-processor processes the C source code before it passes to the compiler. Pre-processor directives are executed before the C source code passes through the compiler.
Example of two pre-processor directives:
i) #include
This pre-processor is used to include another file. File name is written in angle brackets or
within double quotes.
#include <stdio.h>
#include “SORT.H”
File name enclosed within angle brackets are searched in standard directories. File name
enclosed within double quotes are searched first in the current directory and if not found
then it is searched in the standard directories.
ii) #define
#define directive is used to define the symbolic constant or macro name with macro
expression.
#define symconstant value
#define macroname macroexpression
Example
#define PI 3.141
Here the C pre-processor searches for the symbolic constant PI the source code and
substitutes 3.141 each time it is encountered.
As the function, a macro can have argument. The argument of the macro name is replaced
with actual argument of the macro name, which is encountered in the program.
Examples:
#define MAX(x,y) ( (x) > (y) ? (x) : (y) )
#define CUBE(x) (x)*(x)*(x)
iii) #ifdef
#ifdef preprocessor directives checks whether a macro is defined by #define. If yes, it executes
the code:
Example:
#ifdef PI
Printf(“PI symbolic constant is already defined\n”);
#endif
iV) #ifndef
#ifndef preprocessor directives checks whether a macro is not defined by #define. If yes, it
executes the code:
Example:
#ifndef PI
#define PI 3.14
#endif
V) #pragma
#pragma preprocessor directives schedules the execution of function before and after main()
function by clauses startup and exit:
Example:
#pragma startup func2
#pragma exit func1
Here func2() function will execute before main() function and func1() function will
execute after main() function. There is no need to call these function from main()
Example program for macros:
#include <stdio.h>
#define cube(x) x*x*x
int main()
{
printf(“%d”, cube(5+2))
return (0);
}
It gives the output 27 and not cube of 7 i.e. 343 because a macro is expanded in which way it is defined 5+2 * 5+2 * 5+2 and it gives 27. We can say it is blunder definition of macro. It should be defined as:
#define cube(x) (x)*(x)*(x)
Then it will give correct result
6. Explain push() and pop() operations of stack data structure. 10m
Stack is a LIFO (Last In First Out) data structure. Items can be inserted or deleted from one end(top) only
/*stack push() operation given in a function */
void push(int stack[], int item)
{
if(top==size-1)
print(“Stack is full-overflow.\n”);
else
{
top++;
stack[top]=item;
}
}
/*stack push() operation given in a function */
int pop(int stack[])
{
int d;
if(top==-1)
{
printf(“Stack is empty-underflow\n”);
return (NULL);
}
else
{
d=stack[top];
stack[top]=NULL;
top--;
return (d);
}
}
7 a) What do you mean by a linked list? Define structure of a linked list. 5M
Ans:
A linked list is a dynamic data structure where member of a structure is pointing to structure itself. It is also known as self referential structure.
New nodes can be added as and when required allocating the memory at run time. It requires extra space for address of the linked/next node:
| data | next---|---->| data | next---|---->| data | next---|----> NULL
#structure definition of a linked list
struct LIST
{
int data;
struct LIST *next;
};
typedef struct LIST node;
7 b) Explain primitive data types & derived data types. 5m
Ans:
A data type is a classification of data, which can store a specific type of information.
Primitive data types are primary, fundamental or predefined types of data, which are supported by the programming language. In C primitive data types are:
char
int
float
double
Programmers can use these data types when creating variables in their programs. For example, a programmer may create a variable called marks and define it as a int data type type.
Examples:
int marks;
double num = 0.00;
char c;
float sum;
Derived data types are non-primitive data types or composed data types from primary data types. Non-primitive data types are not defined by the programming language, but are instead created by the programmer. Arrays, pointers, structures are examples of derived data type.
Examples of derived/non-primitive data types:
int a[10]; /* array of 10 integers */
struct student
{
int roll;
char name[20];
int marks;
};
struct student s1,s2; /* s1 and s2 are structure variables or objects */
int *p; /* p is pointer variable to keep address of integer data */
8. Write a C program to count frequency of vowels & total number of consonants in a sentence (given by user) 10m
Ans:
/* to count frequency of vowels and total count of consonants */
#include <stdio.h>
#include <ctype.h>
int main()
{
char sent[50],c;
int x,a,e,i,o,u,conso;
printf("Enter sentence : ");
scanf(" %[^\n]",sent); /* to read string with blanks */
a=e=i=o=u=conso=0;
for(x=0;sent[x]!='\0';x++)
{
if(isalpha(sent[x])) /* checks alphabets only */
{
c=tolower(sent[x]);
if(c=='a') a++;
else if(c=='e') e++;
else if(c=='i') i++;
else if(c=='o') o++;
else if(c=='u') u++;
else conso++;
}
}
printf("a=%d,e=%d,i=%d,o=%d,u=%d,consonants=%d\n",a,e,i,o,u,conso);
return (0);
}
Expected output:
Enter sentence : you are a good boy
a=2,e=1,i=0,o=4,u=1,consonants=6
Solution of IAT-2(April 18)
Solution/Model Answer
PCDS-17PCD23 - IAT-2 (2nd sem I & J Section)
Dr. P. N. Singh, Professor(CSE)
1.
a. Write a C Program to check whether a string (with space) is palindrome or not without using built-in functions. 5 M
Ans:
/* To check a string(with space) whether it is palindrome
without using built-in function*/
#include <stdio.h>
int main()
{
char str[50];
int x,y,len=0,palin=1;
printf("Enter string : ");
while((str[len]=getchar())!='\n')
len++;
str[len]='\0'; /* last character NULL */
y=len-1; /* coming before last character */
for(x=0;str[x]!='\0';x++,y--)
if(str[x]!=str[y])
{
palin=0;
break;
}
if(palin)
printf("Yes, \"%s\" is a palindrom\n",str);
else
printf("No, \"%s\" is not a palindrome\n",str);
return (0);
}
b. Write a C Program to find GCD of 2 numbers given by user using recursion. 5 M
Ans:
/* GCD of 2 numbers using recursive function*/
#include <stdio.h>
int GCD(int dividend,int divider)
{
int rem=dividend%divider;
if(rem==0)
return (divider);
else
return GCD(divider, rem);
}
main()
{
int n1,n2;
printf("Enter two numbers : ");
scanf("%d%d",&n1,&n2);
printf("GCD = %d\n",GCD(n1,n2));
return (0);
}
2. Write a C program to find sum and average of marks for 50 students in 6 papers each using 2-d array.
Ans:
/*sum and average of marks */
#include <stdio.h>
int main()
{
int marks[50][6],sum[50],x,y;
float avg[50];
for(x=0;x<50;x++)
{
sum[x]=0;
for(y=0;y<6;y++)
{
printf("Enter marks for student %d paper %d : ", x+1,y+1);
scanf("%d",&marks[x][y]);
sum[x]+=marks[x][y]; /* sum of marks */
}
avg[x]=sum[x]/6.00; /* average of marks for each student*/
}
printf("student p1 p2 p3 p4 p5 p6 sum average\n");
for(x=0;x<5;x++)
{
printf("%d.",x+1);
for(y=0;y<3;y++)
printf("%5d",marks[x][y]);
printf("%6d%7.2f\n",sum[x],avg[x]);
}
return (0);
}
3.
a. Describe string handling functions strlen(), strcpy(), strcat() and strcmp() 5M
Ans:
Header file for all string handling functions is string.h
strlen(str) – returns length of string in number of characters
example:
printf(“%d”,strlen(“PARAS”))
output : 5
strcpy(str1,str2) – Copies str2 to variable str1
example:
char name1[], name2[]=”ramaiyah”;
strcpy(name1,name2); /* copies name2 to name 1 */
strcat(str1, str2) – Concatenates(appends) str2 ton str1 at the end
example:
char name[]=”Roma”
char surname[]=”Ritambhara”
strcat(name,surname);
printf(“%s”, name);
Output: Roma Ritambhara
strcmp( str1, str2) – Compares two string and returns:
0 if both strings are identical
else returns difference based on ASCII value of first mismatch
printf(“%d”, strcmp(“SINGH”, “SINHA”);
output: - 1
b. Write a C program to check whether a number is prime or not. 5M
Ans:
/* to check a number whether it is prime or not */
#include <stdio.h>
#include <math.h>
int main()
{
int n,d,prime=1;
printf("Enter number : ");
scanf("%d",&n);
for(d=2;d<=sqrt(n);d++)
if(n%d==0)
{
prime=0;
break;
}
if(prime)
printf("Yes, %d is a prime number\n",n);
else
printf("No, %d is not prime number\n",n);
return (0);
}
4. Explain storage class extern, auto, static and register with examples. 10M
Ans:
The storage class specifies the portion of the program within which the variables are recognized. variables can be categorized by storage class as well as data type. Storage class refers to the permanence of a variable and its scope within the program, that is, the portion of the program over which the variable is recognized.
extern (external variables): They are global variables, known to all the functions of the program from point of definition. Hence, they usually span more than one functions, and often an entire program. Variables defined outside of the program are by default of extern storage class.
int global = 200;
int fullmarks = 100; /*external storage class variable */
main( )
{
......
}
auto (Automatic variables): They are local variables, available to the function in which it is declared. Their scope is confined to that function only. Variables declared within a function are by default of auto storage class.
auto int x,y,z;
int num; /* num is also interpreted as auto storage class
static (Static variable): Static variables have the same scope as automatic variables, i.e. they are local to the functions in which they are defined. Unlike automatic variables, however, static variables retain their values throughout the life of the program. As a result, if a function is called again, the static variables defined in the called function will retain their former values (They will not be reinitialized again. They are confined at the first initialization).
#include <stdio.h>
int func()
{
static int k = 0; /* by default also zero */
k++;
return (k);
}
int main()
{
int x, sum=0;
for(x=1;x<=5;x++)
sum+=func();
print(“sum = %d\n”, sum);
return (0);
}
register (Register variables) : Registers are special storage area within a computer’s central processing unit (In-built memory with CPU). The actual arithmetic and logical operations that comprise a program are carried out within this registers. The execution time can be reduced considerably if certain values can be stored within these registers rather than in computer’s memory.
The register variables are local to the function in which they are declared. The address of operator cannot ‘&’ cannot be applied to register variables.
register int x, y, z;
5. What is Bubble Sort? Implement Bubble sort for array of integers. 10M
Ans:
Bubble sort: Bubble sort is a sorting techniques to sort the items either in ascending or descending order. In Bubble sort adjacent elements are compared for swapping purpose. 1st element is compared with second, 2nd with 3rd, 3rd with 4th and so on. In each pass the “heaviest” element sinks down and “lighter” elements “bubble” up.
/* program for Bubble sort */
#include <stdio.h>
int main()
{
int num[10],x,y,temp;
/* Accept values */
for(x=0;x<10;x++)
{
printf("Enter value %d:",x+1);
scanf("%d",&num[x]);
}
/* now sorting */
for(x=1;x<9;x++)
for(y=0;y<=10-x;y++)
if(num[y] > num[y+1])
{
temp=num[y];
num[y]=num[y+1];
num[y+1]=temp;
}
printf("\nSorted value:\n");
for(x=0;x<10;x++)
printf("%7d",num[x]);
return (0);
}
6. Implement Binary Search by a C program for initialized sorted array. 10M
Ans:
/* Binary search for sorted array */
#include <stdio.h>
int main()
{
int a[11]={20,24,26,37,48,59,67,77,88,99,111};
int x, skey,first,last,mid,found=0;
printf("The Sorted Array\n");
for(x=0;x<10;x++)
printf("%5d", a[x]);
printf("Enter item to search : ");
scanf("%d", &skey);
first=0; last=10;
while(first <= last && !found)
{
mid=(first+last)/2;
if(a[mid] > skey) last = mid-1;
else if(a[mid] < skey) first = mid+1;
else found=1;
}
if(found) printf("Found at %dth position\n", mid+1);
else printf("Not found\n");
return (0);
}
7.
a. Define structure. How structure members are accessed using dot (.) operator? 5M
Ans:
Structure is a data structure whose individual elements can differ in type. It may contain integer elements, character elements, pointers, arrays and even other structures can also be included as elements within a structure. struct is keyword to define a structure.
struct tag { type member1;
type member2;
type member3; ...... type member n;};
New structure type variables can be declared as follows:
struct tag var1, var2, var3, ....... varn;
Example :
struct library {
char b_name[30];
char author[30];
int price;
};
Now structure variables:
struct library book1, book2, book3;
It is allowed to combine both the template declaration and variable declaration in statement:
struct library {
char b_name[30];
char author[30];
int price;
} book1, book2, book3;
The link between a member and a variable is established using the member operator . (dot operator) or ->
Giving values to members:
book1.price = 76;
by scanf function:
scanf (“%d”,&book1.price);
b. How structure variables are passed as a parameter to a function? Write with example.
5M
Ans:
Passing structure to a function - There are three methods:
1) To pass each member of the structure as an actual arguments of the function call. It is unmanageable and inefficient when structure size is big.
2) To pass a copy of the entire structure to the called function. All compilers do not support this method. Changes to structure members in called function have no effect to calling function. Again we have it has to return entire copy of the changed structure to the calling function.
3) Address of the structure is passed and structure elements can be accessed indirectly. It is more effective method.
To send a copy of the structure:
function name ( structure variable name )
The called function takes the following form
data type function name ( structure type structure name )
{
..... ;
.....;
return (expression);
}
When a function returns a structure. It must be assigned to a structure of identical type in the calling function
8. Implement array of structure of students by a C program with fields roll, name and marks and to get data and sort array of structure based on marks in descending order. 5M
Ans:
/*sorting array of structure - based on marks in descending order*/
#include <stdio.h>
struct student
{
int roll;
char name[20];
int marks;
}s[1000]; /* array of structure */
int main()
{
int n,x,y;
struct student temp;
printf("How many students : ");
scanf("%d",&n);
for(x=0;x<n;x++)
{
printf("Enter roll, name and marks for student %d : ", x+1);
scanf("%d%s%d",&s[x].roll,s[x].name,&s[x].marks);
}
/*now sorting */
for(x=0;x<n-1;x++)
for(y=0;y<n-x-1;y++)
if(s[y].marks < s[y+1].marks)
{
temp=s[y];
s[y]=s[y+1];
s[y+1]=temp;
}
printf("roll name marks:\n");
for(x=0;x<n;x++)
printf("%5d%20s%5d\n",s[x].roll,s[x].name,s[x].marks);
return (0);
}
----------------- Think like a person of action; act like a person of thought.------------------
Solution of IAT-1 (March 2018)
Solution/Model Answer of IAT-1 (March 2018)
Programming in C & data Structure – 17PCD23
II sem – All
Dr. P. N. Singh, Professor(CSE)
1.
a. What is an identifier? What are rules to construct identifier? Classify following as valid/invalid
identifier.
num1, $num1, a_2, for, 1st_paper_marks. 06
Ans:
Identifiers - Names of variables, function, or arrays are identifiers.
Rules to construct identifier:
è They may contain A-Z, a-z, and _ (underscore) (no blanks)
è An identifier name but must be started with an alphabet or _ (specific purposes)
è Maximum length of name of identifier should be 31 characters (ANSI C standards) however in newer versions length of identifier name may be more.
è Keywords & compiler constants should not be identifier name
Valid identifiers: num1, a_2
Invalid identifiers: $num1, for, 1st_paper_marks
b. Explain any 4 types of operators in C. 04
Ans:
Arithmetic Operators + (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)
Relational Operators < (less than)
<= (less than or equal to)
> (greater than)
>= (greater than or equal to)
==(equal to)
!=(not equal to)
Logical Operators && (and)
|| (or)
! (Not)
Assignment Operator =, +=, -=, */, /=, %=
2. What is an Algorithm? Write algorithm for the following i) To find area of triangle by given 3 sides ii) To check given number is Palindrome or not.
Ans:
Algorithm: An algorithm is step-by-step ( in the sequence ) procedure/ formula to get the solution of a task. Number of steps must be finite. Criteria of an algorithm to reduce the complexity of the solution.
i. Algorithm to find area of a triangle by given 3 sides
Step 1. Start
Step 2. Input sides a,b & c
Step 3. s=(a+b+c)/2
Step 4. If s <= a OR s <= b OR s <= c then
4.1 Print ‘Wrong measurement of triangle’
Step 5. Else
5.1 area=sqrt(s*(s-a)*(s-b)*(s-c))
5.2 Print area
Step 6. Endif
Step 7. End.
ii. Algorithm to check given number is palindrome or not
Step 1. Start
Step 2. Input num
Step 3. Temp=num
Step4. REV=0
Step 5. While temp <> 0
5.1 Rem=temp MOD 10
5.2 Rev=Rev*10+Rem
5.3 Temp=(integer)Temp/10
Step 6. Endwhile
Step 7. If rev = num then
7.1 Print “Number is palindrome”
Step 8. Else
8.1 Print “Number is not palindrome”
Step 9. Endif
Step10. End.
3.
a. With Syntax and example explain printf() and scanf() functions. 06
Ans:
printf() – Library function for formatted output:
Output data can be written on to a standard output device using the library function printf(). The printf statement provides certain features that can be effectively exploited to control the alignment and spacing of printouts on the terminals. The general form of printf statement is:
printf (“control string”, arg1,arg2, ........., argn);
Control string of printf function consists of three types of item :
· Character that will be printed on the screen as they appear.
· Format specification that define the output format for display of each item.
· Escape sequence characters such as \n,\t, and \b.
scanf() – Library function for formatted input
Formatted input refers to an input data that has been arranged in a particular format. Input data can be entered into the computer from a standard input device by means of the C library function scanf. In general terms, scanf function is written as
scanf (“control string”, &arg1, &arg2, ........., &argn);
The control string specifies the field format in which the data is to be entered and the arguments arg1,arg2.....,argn specify the address of locations where the data is stored. Actually arguments are pointers which indicate where the data items are stored in computer’s memory.
Control string contains field specification which direct the interpretation of input data. It may include:
· Field (or format) specification, consisting of the conversion character %, a data type character (or type specifier, and an optional number, specifying the field width.
· Blanks, tabs, or new lines.
· The arguments are written as variables or arrays, whose type match the corresponding character groups in the control string. Each variable name must be preceded by an ampersand (&). Array names should not begin with an ampersand.
b. Evaluate the expression: i) 100%20<=20-5+100%10-20==5>=1!=20
ii) a+=b*=c-=10 (Initial values, a=5,b=10 and c=15) 04
Ans:
(i) 100%20 <= 20-5+100%10-20 ==5>=1!=20
(Arithmetic operator has greater precedence than relational operator)
0 <= -5 == 5 >= 1 != 20
(Now associativity of relational operator is left to right)
0 == 5 >= 1 != 20
0 >= 1 != 20
0 != 20
1 Ans is 1 (True)
(ii) a+=b*=c-=10
(Associativity of assignment operator is right to left)
So, c - = 10 will be 5
b*=c will be 50
and a+=b will be 55
Finally Answer is: a = 55, b= 50 and c = 5
4.
a. Write a C program to calculate and display area of a rectangle. 5
Ans:
/* area of a rectangle */
#include <stdio.h>
int main()
{
float length, width, area;
printf(“Enter length & width of rectangle : “);
scanf(“%f%f”,&length, &width); /* input from keyboard*/
area=length*width;
printf(“Area = % .3 square unit\n”, area);
return (0);
}
Expected output:
Enter length and width: 5 4
Area = 20.000 square unit
b. Write a C program to calculate and display sum and average of 5 integers.
Ans:
#include <stdio.h>
int main()
{
int x,num, sum=0;
float avg;
for(x=1;x<=5;x++)
{
printf(“Enter number : “);
scanf(“%d”, &num);
sum+=num;
}
avg=sum/5.00;
printf(“sum = %d average = %f\n“, sum,avg);
return (0);
}
/* computing sum and average of 5 integers – without loop */
#include <stdio.h>
int main()
{
int n1,n2,n3,n4,n5,sum;
float avg;
printf(“Enter 5 integers : “);
scanf(“%d%d%d%d%d”, &n1,&n2,&n3,&n4,&n5);
sum=n1+n2+n3+n4+n5;
avg=sum/5.00;
printf(“sum = %d average = %f\n“, sum,avg);
return (0);
}
Expected output:
Enter 5 integers: 10 20 30 40 50
sum = 150 average = 30.000000
5.
a. Explain cascaded if else (else if ladder) and nested if statements with syntax and suitable example. 5
Ans:
Ladder of if ....else statement: for Multiple sets of conditions
if (expression/condition)
{statement1; statement2; ..... }
else if (expression/condition)
{statement1; statement2; ..... }
else if (expression/condition)
{statement1; statement2; ..... }
........
else
{statement1; statement2; ..... }
/* Example program to display division using if ladder*/
#include <stdio.h>
int main()
{
int marks;
printf(“Enter marks : “);
scanf(“%d”,&marks);
if(marks>=60)
printf(“First division\n”);
else
if(marks>=45) /* no surplus condition is required */
printf(“Second division\n”);
else
if(marks>=30)
printf(“Third division\n”);
else
printf(“Fail\n”);
return (0);
}
Nested if ...... else statement: if within if
if (expression/condition)
{ if (expression/condition)
{statement1; statement2; ..... }
else
{statement1; statement2; ..... }
}
else { if (expression/condition)
{statement1; statement2; ..... }
else
{statement1; statement2; ..... }
}
/* Example program to find maximum in 3 integers using nested if*/
#include <stdio.h>
int main()
{
int n1,n2,n3,max;
printf(“Enter 3 numbers : “);
scanf(“%d%d%d”,&n1,&n2,&n3);
if(n1 > n2)
if(n1 > n3)
max=n1;
else
max=n3;
else
if(n2 > n3)
max=n2;
else
max=n3;
print(“Maximum = %d\n”,max);
return (0);
}
b. Explain Structure of a C Program with Example 05
Ans:
Structure of C Program
/* Separate line comments –
------------ */
pre-processor directives /* header section */
global declarations
int main( ) /* main ( ) function section */
{
local variables to function main ;
statements associated with function main ;
………………….
return (0);
}
udf1( ) /* user defined functions */
{
local variables to user defined function udf1 ;
statements associated with udf1 ;
}
.
.
/* Example program to calculate simple interest */
#include <stdio.h>
int main( )
{
float p,r,t,si;
printf(“Enter principle, rate and time : “);
scanf(“%f%f%f”, &p, &r, &t);
si=p*r*t/100.00;
printf(“Simple interest = %f\n”, si);
return (0);
}
6. Explain switch case statement with syntax and example of a calculator program to do simple operations like addition, subtraction, multiplication and division. 10
switch statement:
switch (expression)
{
case condition1
statement1;
statement2;
......
break;
case condition2
statement1;
statement2;
.......
break;
.....
default:
statement1;
statement2;
.......
}
/* Arithmetic operation by switch */
int main( )
{
float n1,n2,result;
int choice;
printf(“Enter 2 numbers : “);
scanf(“%f%f”, &n1, &n2);
printf(“1. Addition 2. Subtraction 3. Multiplication 4. Division:\n”);
printf(“Enter your choice number : “);
scanf(“%d”, &choice);
switch(choice)
{
case 1 : result = n1+n2;
break;
case 2 : result = n1-n2;
break;
case 3 : result = n1*n2;
break;
case 4 : if(n2 == 0)
{ printf(“divide error!!!\n”); return (99); }
else
result = n1/n2;
break;
default: printf(“Wrong choice!\n”);
}
printf(“Result = %f\n”, result);
return (0);
}
Expected Output:
Enter 2 numbers : 50 25
1. Addition 2. Subtraction 3. Multiplication 4. Division:
Enter your choice number : 4
Result = 2.000000
7. Write a C program to find roots of a quadratic equation of the form ax2+bx+c=0, where a, b and c are coefficients. Explain the output for all possible cases. 10
Ans:
/* to find roots of quadratic equation */
#include <stdio.h>
#include <math.h>
main()
{
float a,b,c,d,r1,r2, rpart,ipart;
printf("Enter values of a, b and c : ");
scanf("%f%f%f",&a,&b,&c);
if(a==0) { printf(“The equation is not quadratic\n”); return (99); }
d=b*b-4*a*c;
if(d==0)
{
r1=r2=-b/(2.0*a);
printf(“Roots are real and equal: %f\n”,r1);
}
else
if(d > 0)
{
r1=(b+sqrt(d))/(2*a);
r2=(b-sqrt(d))/(2*a);
printf("Roots are distinct : %.3f and %.3f\n",r1,r2);
}
else /* computing imaginary roots*/
{
rpart=-b/(2.0*a);
ipart=sqrt(-d)/(2.0*a);
printf(“Roots are imaginary:\n”);
printf(“ r1=%f+i*%f\n r2=%f-i*%f\n”,rpart,ipart,rpart,ipart);
}
return (0);
}
8.
a. Explain while loop with an example. 5
Ans:
while loop: while is a looping statement where statements are executed till the condition is satisfied/true.
Syntax:
while (condition)
{
statement1;
statement2;
......
}
Example:
/* while loop example to display number and message 5 times */
#include <stdio.h>
int main()
{
int x=1;
while(x<=5)
{
printf(“%d. %s\n”, x, “Kudi Punjaban Dil chura ke le gayee – Sona Sona”);
x++;
}
return (0);
}
Expected Output:
1. Kudi Punjaban Dil chura ke le gayee – Sona Sona
2. Kudi Punjaban Dil chura ke le gayee – Sona Sona
3. Kudi Punjaban Dil chura ke le gayee – Sona Sona
4. Kudi Punjaban Dil chura ke le gayee – Sona Sona
5. Kudi Punjaban Dil chura ke le gayee – Sona Sona
b. Write a program to find whether the given year is leap or not. (consider century year) 5
Ans:
/* to find whether the given year is leap year or not */
#include <stdio.h>
int main( )
{
int year;
printf(“Enter year : “);
scanf(“%d”, &year);
if((year%4==0 && year%100 != 0)|| year%400==0)
printf(“Yes, %d is leap year.\n”, year);
else
printf(“No, %d is not leap year.\n”, year);
return (0);
}
Expected Output:
Enter year: 2016
Yes, 2016 is leap year.
Again
Enter year: 1900
No, 1900 is not leap year.
Again
Enter year: 2000
Yes, 2000 is leap year
Solution to IAT-I
CMR
INSTITUTE OF
TECHNOLOGY
Solution/Model Answer of IAT-1 (March 2017)
Programming in C & data Structure – 15PCD23
II sem – All
Dr. P. N. Singh, Professor(CSE)
1. Explain Structure of a C Program. Write a program to calculate simple interest 10
Ans:
Structure of C Program
/* Separate line comments –
------------ */
pre-processor directives /* header section */
global declarations
int main( ) /* main ( ) function section */
{
local variables to function main ;
statements associated with function main ;
………………….
return (0);
}
udf1( ) /* user defined functions */
{
local variables to user defined function udf1 ;
statements associated with udf1 ;
}
.
.
/* program to calculate simple interest */
int main( )
{
float p,r,t,si;
printf(“Enter principle, rate and time : “);
scanf(“%f%f%f”, &p, &r, &t);
si=p*r*t/100.00;
printf(“Simple interest = %f\n”, si);
return (0);
}
2.
a. Define an operator? Explain with Example 6
C includes a large number of operators. Individual constants, variables, array elements and function references can be joined by various operation to form expressions. The data items that operators act upon are called operands.
Examples of some operators:
Arithmetic Operators + (addition) - (subtraction) * (multiplication)
/ (division) % (modulus)
unary operator - (minus) acts upon a single operand
( oh! C does not have an operator for exponentiation)
Relational Operators < (less than) <= (less than or equal to) > (greater than) >= (greater than or equal to)
equality operators = = (equal to) != (not equal to)
Logical Operators && (and) || (or)
unary operator ! negates the value of a logical operator
!(n<=10) - n is not less than or equal to 10
b. Describe data types in C? Explain the syntax for variable declaration and initialization.
4
Data type Description
int integer quantity
char single character
float (real) floating point number(i.e., a number containing a decimal point and/or an exponent
double double-precision floating-point number
(i.e., more significant figures, and an exponent which may be larger in magnitude.)
Syntax for variable declaration & initialization:
datatype variable;
int num;
float radius;
datatype variable = value;
int num=20;
float radius = 5.067;
3.
a. Define an Identifier? List the rules to construct an identifier? Give examples of valid and invalid identifier. 4
Ans:
Identifiers - Names of variables, function, or arrays are identifiers.
Rules:
è They may contain A-Z, a-z, and _ (underscore) (no blanks)
è An identifier name but must be started with an alphabet or _ (specific purposes)
è Maximum length of name of identifier should be 31 characters (ANSI C standards) however in newer versions length of identifier name may be more.
è Keywords & compiler constants should not be identifier name
Examples of valid identifiers: amount, order_no, marks1, stud[10], sort( )
Examples of invalid identifiers: 1stpaper, for, if, name of student
b. Explain different conditional decision making statements with syntax. 6
Ans:
if statement: .........
if (expression/condition)
{
statement1;
statement2;
...
}
if .... else statement:
if (expression/condition)
{ statement1;
statement2;
........
}
else
{ statement1;
statement2;
......
}
Ladder of if ....else statement:
if (expression/condition)
{statement1; statement2; ..... }
else if (expression/condition)
{statement1; statement2; ..... }
else if (expression/condition)
{statement1; statement2; ..... }
........
else
{statement1; statement2; ..... }
Nested if ...... else statement:
if (expression/condition)
{ if (expression/condition)
{statement1; statement2; ..... }
else
{statement1; statement2; ..... }
}
else { if (expression/condition)
{statement1; statement2; ..... }
else
{statement1; statement2; ..... }
}
switch statement:
switch (expression)
{
case condition1
statement1;
statement2;
......
break;
case condition2
statement1;
statement2;
.......
break;
.....
default:
statement1;
statement2;
.......
}
4.
a. Write a program to find greatest of the 3 numbers using nested if-else. 5
Ans:
/* program to find greatest in the 3 numbers using nested if-else */
#include <stdio.h>
int main( )
{
int n1, n2, n3,max;
printf(“Enter 3 numbers : “);
scanf(“%d%d%d”, &n1, &n2, &n3);
if(n1 > n2)
if(n1 > n3)
max=n1;
else
max=n3;
else
if (n2 > n3)
max=n2;
else
max=n3;
printf(“Greatest = %d\n”, max);
return (0);
}
b. Write a program to find whether the given year is leap or not. (consider century year) 5
Ans:
/* to find whether the given year is leap year or not */
#include <stdio.h>
int main( )
{
int year;
printf(“Enter year : “);
scanf(“%d”, &year);
if((year%4==0 && year%100 != 0)|| year%400==0)
printf(“Yes, %d is leap year.\n”, year);
else
printf(“No, %d is not leap year.\n”, year);
return (0);
}
5.
a. Differentiate between while and do-while loop. 6
Ans:
The while statement:
while (condition)
{
statement1;
statement2;
......
}
The do ..... while statement:
do
{
statement1;
statement2;
......
} while (condition);
è While is a pre-tested loop/entry controlled loop and do… while is post-tested loop
è Post-tested loop must execute at least once because condition is checked at the end of loop
b. Write a program to check whether the given number is even or odd. (Use conditional Operator) 4
Ans:
/* to check whether a given number is even or odd - using conditional operator*/
#include <stdio.h>
int main()
{
int n;
printf(“Enter number : “)
scanf(“%d”, &n);
printf(“Number is %s\n”, n%2 == 0 ? “ Even” : “Odd”);
return (0);
}
6.
a. Evaluate the following expression. 4
a=5, b=6, c=7
d= ++a * b –c;
e = a & b
f=100%20<=20-5+100%10-20= =5>=1!=20;
g=c-- *b+d;
Ans:
d = 6 * 6 – 7 = 29
e = 6 & 6 = 6 (by bit wise operator 110 & 110)
f = 1 (true, finally not equal to 20)
g = 7 * 6 + 29 = 71 ( post decrement of c after statement)
b. What will be value of x in following segments? 4
int a,b; float x; a=4; b=5; x=b/a;
int a,b; float x; a=4; b=5; x= (float) b/a;
Ans:
int a,b; float x; a=4; b=5; x=b/a;
x = 1.0 (integer values b/a is not casted)
int a,b; float x; a=4; b=5; x= (float) b/a;
x = 1.25 (b/a is casted)
c. What is difference between 7, 7.0, ‘7’, “7” ? 2
Ans:
7 Integer constant
7.0 floating point constant
‘7’ character constant
“7” string constant
7. Explain the syntax of switch case. Write a program to perform basic arithmetic operations like addition, subtraction, multiplication & division, using switch statement. (Error message should be displayed if number is divided by 0) 10
Ans:
/* Arithmetic operation by switch */
int main( )
{
float n1,n2,result;
int choice;
printf(“Enter 2 number : “);
scanf(“%f%f”, &n1, &n2);
printf(“1. Addition 2. Subtraction 3. Multiplication 4. Division:\n”);
printf(“Enter your choice number : “);
scanf(“%d”, &choice);
switch(choice)
{
case 1 : result = n1+n2;
break;
case 2 : result = n1-n2;
break;
case 3 : result = n1*n2;
break;
case 4 : if(n2 == 0)
{ printf(“divide error!!!\n”); return (99); }
else
result = n1/n2;
break;
default: printf(“Wrong choice!\n”);
}
printf(“Result = %f\n”, result);
return (0);
}
8.
a. Write a program and pseudo-code to check whether the given number is palindrome or not. 5
Ans:
Pseudo-code to check given number is palindrome or not
START
INPUT NUM
TEMP=NUM
REV=0
WHILE TEMP <> 0
REM=TEMP MOD 10
REV=REV*10+REM
TEMP=(INTEGER)TEMP/10
ENDWHILE
IF REV = NUM THEN
PRINT “NUMBER IS PALINDROME”
ELSE
PRINT “NUMBER IS NOT PALINDROME”
ENDIF
END.
/*Program to check given number is palindrome */
#include <stdio.h>
int main()
{
long int num,temp,rev,rem;
printf(“Enter Number : “);
scanf(“%ld”, &num);
temp=num;
rev=0;
while (temp !=0)
{
rem=temp%10;
rev=rev*10+rem;
temp/=10;
}
if(rev==num)
printf(“Yes, %ld is palindrome\n”, num);
else
printf(“No, %ld is not palindrome\n”, num);
return (0);
}
b. Write a program to print Fibonacci series up to n terms. 5
Ans:
/* to print Fibonacci series up to n terms */
#include <stdio.h>
int main( )
{
long int a=0,b=1,c;
int n,x;
printf(“How many numbers of Fibonacci series ( > 2) ? “);
scanf(“%d”, &n);
printf(“%7ld%7ld”, a,b);
for(x=3;x<=n;x++)
{
c=a+b;
printf(“%7ld”, c);
a=b;
b=c;
}
return (0);
}
Solution of IAT - 2
CMR
INSTITUTE OF
TECHNOLOGY
Solution/Model Answer of IAT-2 (May 2017)
Programming in C & data Structure – 15PCD23
II sem – G & F
Dr. P. N. Singh, Professor(CSE)
1. a) What is array? Explain the declaration and initialization of one and two dimensional arrays
with example. 10
Ans:
Array is collection of similar data types.
An array is an identifier that refers to the collection of data items which all have the same name. The individual data items are represented by their corresponding array elements. Element ranges from 0 to n-1 where n is total number of elements.
One-dimensional array
Declaration:
syntax: datatype arrayname[size];
examples: float height[50];
int batch[10];
char name[20];
Initialization:
int marks[5] = {76,45,67,87,92};
static int count[ ] = {1,2,3,4,5};
static char name[ ] = {‘S’, ‘I’, ‘N’, ‘G’, ‘H’};
Two-dimensional array
Declaration:
syntax: type arrayname[rowsize][columnsize];
examples: static int stud[16][5];
Initialization:
int marks[3][3] = {
{26,57,66},
{56,77,48},
{76,54,82}
};
static int marks[3][3] = { {0},{0},{0}};
Here first element of each row is explicitly initialized to zero while other elements
are automatically initialized to zero.
2 a) Write a program to implement the strcpy function. 4
Ans:
strcpy(strvar, strval) function is used to copy string value to string variable. Related header file is string.h
/*Program to implement strcpy() function */
#include <stdio.h>
#include <string.h>
int main()
{
char str1[30], str2[30];
printf(“Enter string : “);
scanf(“%s”, str1);
strcpy(str2,str1); /* to copy str1 to str2 */
printf(“copied string is %s\n”,str2);
return (0);
}
2b) Explain any 4 string manipulation functions with examples 6
Ans:
i. strlen( ) : Returns length of string in bytes.
Syntax:
int strlen(str);
Example:
printf(“Length of string = %d\n”, strlen(“SINGH”));
output will be 5
ii. strcpy( ): copies string
Syntax:
void strcpy(stringvar, stringval);
Example:
strcpy(name,”SINGH”);
SINGH string is copied to string variable name.
iii. strcat( ): concatenates 2nd string to 1st string
Syntax:
void strcat(name, surname);
Example:
strcpy(name,”VIKRAM”);
strcpy(surname,”SINGH”);
SINGH will be appended to string variable name and now name is VIKRAMSINGH
iv. strrev( ): reverses string
Syntax:
void strrev(string);
Example:
strcpy(name,”VIKRAM”);
strrev(name);
Now name is MARKIV
3a) Describe the different methods of passing parameters to functions, with examples. 5
Ans:
Parameters can be passed by two ways:
i. Pass by value/variable
ii. Pass by address
i. Pass by value/variable
When value is passed as parameters to a function its value remains unchanged in calling function.
/*pass by value */
#include <stdio.h>
void func(int x)
{
x=200;
printf(“value of x in func ( ) =%d\n”,x); /* prints x = 200 */
}
int main()
{
int x = 100;
printf(“value of x in main( ) = %d\n”,x); /* prints x = 100 */
func(x);
printf(“value of x in main( ) = %d\n”,x); /* prints x = 100 */
return (0);
}
ii. Pass by address
When address of a variable passed as parameters to a function its value may be changed by the called function & changed value will be available in calling function.
/*pass by address */
#include <stdio.h>
void func(int *p) /* p receives address of parameter passed */
{
*p=200;
printf(“value in func ( ) changed =%d\n”, *p);
/* prints value 200 */
}
int main()
{
int x = 100;
printf(“value of x in main( ) = %d\n”,x); /* prints x = 100 */
func(&x); /* pass by address */
printf(“changed value of x in main( ) = %d\n”,x); /* prints x = 200 */
return (0);
}
3b) Write a C function to count the frequency of vowels and consonants in a string. 5
Ans:
/* counts frequency of vowels and total count of consonants */
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void count_vow_conso(char str[ ])
{
int x, len=strlen(string),a,e,i,o,u,conso;
char c;
a=e=i=o=u=conso=0;
for(x=0;str[x]!=’\0’;x++) /* till NULL character occurs */
{
if( isalpha(str[x]) ) /* if alphabets from a to z */
{
c=tolower(str[x]); /* converts in lower case */
if(c==’a’) a++;
else if (c==’e’) e++;
else if(c==’i’) i++;
else if(c==’o’) o++;
else if(c==’u’) u++;
else conso++;
}
}
printf(“vowels a=%d e=%d i=%d o=%d u=%d and consonants = %d\n”,
a,e,i,o,u,conso);
}
4a) What is a structure? Explain the C syntax of structure declaration with an example. How is a structure different from arrays? 5
Ans:
Structure is a data structure whose individual elements can differ in type. It may contain integer elements, character elements, pointers, arrays and even other structures can also be included as elements within a structure.
The individual structure elements are referred to as members.
Structure declaration:
The key word struct declares a structure to hold the details of fields. Name of the structure is called structure tag. The tag name may be used subsequently to declare variables that have the tag’s element.
struct tag
{
type member1;
type member2;
type member3;
...... ;
type member n;
};
New structure type variables can be declared as follows:
struct tag var1, var2, var3, ....... varn;
Example :
struct library {
char b_name[30];
char author[30];
int price;
};
Now structure variables:
struct library book1, book2, book3;
Structure and array :
A structure is collection of dissimilar data types and it represents a records with different types of a field.
An array is collection of similar data type.
If structure is also a derived type then an array is evergreen hero to occupy it. We can make array of structure:
struct library books[10000];
4b) Write a program to create of structure to store details of a person and print the details of a person given his name. Assume the fields are Name, Age, Gender and College Name. 5
Ans:
/* array of structure */
#include <stdio.h>
struct person
{
int age;
char name[20], gender, cname[30];
};
struct person p1; /* p1 is structure variable */
int main()
{
printf(“Enter name, gender, collegename & age of the person:”);
scanf(“%s %c%s%d”,p1.name,&p1.gender,p1.cname,&p1.age);
/* space before %c */
printf(“Name = %s gender = %c collegename = %s age = %d\n”,
p1.name,p1.gender,p1.cname,p1.age);
return (0);
}
5a) Explain the concept of array of structures with example. 6
Ans:
An array is collection of similar data type.
If structure is also a derived type then an array is evergreen hero to occupy it. We can make array of structure:
struct tagname structarray[size];
struct student
{
int roll;
char name[20];
int marks;
};
struct student s[60]; /* array of structure */
/* to accept rollname and marks of 60 students & to display */
int main()
{
int x;
for(x=0;x<60;x++)
{
printf(“Enter roll, name & marks for student %d : “ , x+1);
scanf(“%d%s%d”,&s[x].roll,s[x].name,&s[x].marks);
}
/* to display */
for(x=0;x<60;x++)
printf(“%5d%20s%5d\n”,s[x].roll,s[x].name,s[x].marks);
/* taking 5 & 20 characters minimum space to display*/
return (0);
}
5b) Write a program to add two matrices. Also check for compatibility.
Ans:
/* adding two matrices */
#include <stdio.h>
int main()
{
int m, n, p,q,c, d, first[100][100], second[100][100], sum[100][100];
printf("Enter the number of rows and columns of matrix1 \n");
scanf("%d%d", &m, &n);
printf("Enter the number of rows and columns of matrix2 \n");
scanf("%d%d", &p, &q);
if(m!=p || n!=q) /* checking rows and columns of both matrices
for compatibility */
{
printf(“Needs square matrix – not compatible\n”);
return (99); /* return from here with non-zero value*/
}
printf("Enter the elements of first matrix:\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix:\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return (0);
}
6a) What is dynamic memory allocation? Explain malloc ( ), calloc ( ) realloc () and free () functions with examples.
Ans:
Dynamically memory allocation:
Memory can be allocated dynamically at run time as & when required. It is good for the fear of wasted or shortage of memory if limited size is declared
For Memory allocation header file is stdlib.h or alloc.h
For allocation we can use malloc( ), calloc( ) and realloc( )
malloc( ) : allocates single block of memory in bytes
example:
int *p;
p=malloc(sizeof(int)*20));
calloc() : allocates multiple blocks of memory of equal size
calloc(nblocks, size_of_each_block_in_bytes);
example:
calloc(10,sizeof(int));
realloc() : resets the memory already allocated by malloc() or calloc() by growing or shrinking the size
realloc(nblocks, size_of_each_block_in_bytes);
realloc(20,sizeof(int)*2);
free() is used to de-allocate the allocated memory generally at the end of execution
example:
free(p);
memory allocated dynamically should be de-allocated properly at the end of execution
6b) Write a recursive function to find factorial. 3
Ans:
/* recursive function to find factorial */
long int fact(int n)
{
if(n==0 || n==1)
return (1);
else
return (n*fact(n-1));
}
7a) Write a function to find sum, mean, variance and standard deviation using pointers 5
/* sum, mean, variance & standard deviation */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double *a,sum=0.00,mean,variance,stdev,diff,sum2;
int x,n;
printf("How many numbers : ");
scanf("%d",&n);
a=malloc(sizeof(double)*n); /* allocating memory */
for(x=0;x<n;x++)
{
printf("Enter number %d : ", x+1);
scanf("%lf",(a+x));
sum+= *(a+x); /* using pointers */
}
mean=(double)sum/n;
sum2=0.00;
for(x=0;x<n;x++)
{
diff=*(a+x) - mean;
sum2+=diff*diff; /* sum of squares of diff. in number & mean */
}
variance=(double)sum2/(n-1);
stdev=sqrt(variance); /* std deviation is square root of variance*/
printf("Sum=%.3lf Mean=%.3lf Standard deviation=%.3lf\n" ,
sum,mean,stdev);
return (0);
}
7b) What is a pointer? How do you declare and initialize a pointer? What is a pointer to pointer? Give example 5
“Pointer is a variable that stores address(location) of data as value.”
In C when we define a pointer variable we do so by preceding its name with an asterisk.
To declare:
datatype *pointervar;
int *p;
/*Example code */
#include <stdio.h>
int main()
{
int n=20,*p;
p=&n; /* address of n is initialized to pointer variable p */
/*Now value of n can be accessed by variable or by address;
*p value is value and p is address */
printf(“Value of n = %d\n”, n);
printf(“Address of n = %u\n”, p);
printf(“Value stored at address = %d\n”, *p);
*p=40;
printf(“Value changed by pointer = %d\n”, n);
/* value of n is changed to 40 */
return (0);
}
Pointer to Pointer : A pointer can store address of another pointer :
Address ---à Address --à value
int n, *p, **q;
p=&n;
q=&p;
/* Here p stores address of n and q stores address of p */
p : address of n
*p : value of n
q : address of p
*q : value of p i.e. address of n
**q :value of n
/* Think like a person of action, act like a person of thought */
__________________________________________________________________________________________________________
Model answers of University questions (2017-2nd sem)
Solution to VTU Question-2017
(Model Answers – Comments/Outputs can be added more in programs)
Programming in C & Data Structure – 15PCD13/23
Dr. P. N. Singh, Professor(CSE), CMRIT
Q 1 a. Define Pseudo code. Explain with an example. [05 marks]
Ans:
Pseudo code is a tool for designing solution of a problem written with simple terms and verbs(here in English). It is an informal high-level description of the operating principle of a computer program or other algorithm. It uses the programming constructs similar to normal programming language, but is intended for human reading rather than machine reading (That’s the reason it is known as pseudo (false) code & not actual programming code. A pseudo code may be inclined to a programming language as per programmer expertise.
The other designing tool algorithm differs in terms of writing steps.
START/BEGIN, END/STOP, INPUT, READ, WRITE, PRINT, IF, WHILE & calculation/comparisons operators are mostly used in a pseudo code.
Example of a Pseudo code to find maximum in 3 numbers (USING NESTED IF):
START
INPUT N1,N2,N3
IF N1 > N2 THEN
IF N1 > N3 THEN
MAX=N1
ELSE
MAX=N3
ENDIF
ELSE
IF N2 > N3 THEN
MAX=N2
ELSE
MAX=N3
ENDIF
ENDIF
PRINT MAX
END.
Q 1 b. Write a C program to find biggest among three numbers using ternary operator
[05 marks]
Ans:
#include <stdio.h>
int main()
{
int n1,n2,n3,max;
printf("Enter 3 numbers : ");
scanf("%d%d%d",&n1,&n2,&n3);
max=n1>n2?(n1>n3?n1:n3):(n2>n3?n2:n3);
/* use of ternary operator in nesting form*/
printf("biggest = %d\n",max);
return (0);
}
Expected o/p:
Enter 3 numbers : 33 44 22
biggest = 44
Q 1 c. Explain the following constants with example [06 marks]
i) Integer constant
ii) Floating constant
iii) Character constant
Ans:
Here constants are referred to different types for the assigning the values and it will remain constant to the variable “till they are not changed”.
i) Integer constant:
Integer numbers are written as they are & by default they are integer of decimal number system. In C type of integer is int.
Integer of Decimal Number System:
int n;
n=20;
Integer of Octal number system precedes with 0 (zero)
n=036;
Integer of Hexadecimal number system precedes with 0x(zero & x)
n=b01a;
ii) Floating constants:
Type of floating/real type in c is float(single precision) & double(double precision). A floating value is assigned as they are:
float f1=3.456;
iii) Character constant:
A character value is assigned enclosing them in single quote (‘ ‘). Their type in c is char.
char c=’A’;
C language has no difference between a character and its ASCII equivalent.
Q 2 a. List the formatted input/output functions of C language. Explain the basic structure of C program with proper syntax and example. [06 marks]
Ans:
Formatted output function: printf()
printf() is a formatted output function of C to send the output to default output stream(monitor). It is written with format of the data and the data.
Syntax:
printf(“format control string”, var1, var2, data1, data2,…);
Example:
printf(“Sum of numbers = %d\n”, sum);
Here Sum of numbers = written in format control string and %d is the format specifier for integer of decimal number system. In place of %d the value of the variable sum would be displayed.
Formatted input function: scanf()
scanf() is a formatted input function of C to read(scan) the input from default/standard input stream (keyboard). It is written with format of the data and the data preceding with address of operator &.
Syntax:
printf(“format control string”, &var1, &var2,…);
Example:
printf(“%d%d%d”, &n1,&n2,&n3);
Here %d is the format specifier for integer of decimal number system. In place of %d the value of the variable sum would be scanned and stored in memory on a particular address. & is address of operator (which is not used with string because name of the string represents address of the first character of the string).
Structure of a C program
/* Example: a program to find area of a circle – area.c
Dr. P. N. Singh - Documentation Section*/
#include <stdio.h> /* - Link/Header Section */
#define PI 3.14 /* definition/global section*/
int main() /* main function section */
{
float r, area; /* declaration part */
printf(“Enter radius of the circle : “); /* Execution part*/
scanf(“%f”, &r);
area=PI*r*r; /* using symbolic constant PI */
printf(“Area of circle = %0.3f square unit\n”, area);
return (0);
}
Q 2b. Define an algorithm. Write an algorithm to find area of circle and triangle. [06 marks]
Ans:
An algorithm is step-by-step process to solve the task. It is self contained sequence of actions to be performed. In programming life cycle it is applied as designing tool. Number of steps must be finite. Criteria of an algorithm are to reduce complexity also.
Algorithm to find area of circle and triangle:
Step 1. Start
Step 2. input radius
Step 3. area_of_circle <- 3.14*radius*radius
Step 4. print “Area of circle “, area, “ square unit.”
Step 5. input base,height
Step 6. area_of_triangle <- 0.5*base*height
Step 7. print “Area of triangle = “, area_of_triangle, “ square unit.”
Step 8. End.
Q 2 c. Evaluate the following expression/code segment
i) 22+3 < 6 && ! 5 || 22 == 7 && 22 -2 >= 5
ii) a + 2 > b || ! c && a == d || a – 2 <= e
where a = 11, b=6, c=0, d=7 and e=5
Ans:
i) 22+3 < 6 && ! 5 || 22 == 7 && 22 -2 >= 5
Evaluating (according to precedence):
22+3 < 6, false so, 0
22-2>=5 true so, 1
22==7 false so, 0
!5 || 0 false so,0
Finally 0 && 0 && 1 so evaluated output is 0
ii) a + 2 > b || ! c && a == d || a – 2 <= e
where a = 11, b=6, c=0, d=7 and e=5
Evaluating by keeping values of variables:
11+2 > 6 || !0 && 11 == 7 || 11-2 <= 5
1 || 1 && 0 || 0
1 || 0 || 0 , So finally evaluated output is 1
Q 3a. List all branching statements. Explain any two with proper syntax and example. [06 marks]
Ans:
In C programming language branching statements are:
if, if else & switch
if/if else can be extended to:
ladder if & nested if
if statement: syntax
if (expression/condition)
{
statement1;
statement2;
...
}
Example:
#include <stdio.h>
int main()
{
int age;
printf(“Enter your age : “);
scanf(“%d”, &age);
if(age >= 25)
printf(“Celebrate valentine day\n”);
else
printf(“Just keep looking cute only.\n”);
return (0);
}
Nested if syntax:
if (expression/condition)
{
if (expression/condition)
{
statement1;
statement2;
.....
}
else
{
statement1;
statement2;
.....
}
}
else
{
if (expression/condition)
{
statement1;
statement2;
.....
}
else
{
statement1;
statement2;
.....
}
}
// Example: to find maximum in 3 numbers
#include <stdio.h>
int main()
{
int n1,n2,n3,max;
printf(“Enter 3 numbers : “);
scanf(“%d%d%d”, &n1, &n2, &n3);
if(n1>n2)
if(n1>n3)
max=n1;
else
max=n3;
else
if(n2>n3)
max=n2;
else
max=n3;
print(“Maximum = %d\n”, max);
return (0);
}
Q 3b. Explain switch case statement with syntax and example [05 marks]
Ans:
If the number of alternatives increases, the program becomes difficult to read and follow. C has a built-in multiway decision statement known as a switch. It tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated with the case is executed. The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to the next statement following the switch ( where branch ends with } ). The default is an optional case. When present, it will be executed if thevalue of the expression does not match with any of the case values. If not present, no action takes place if all matches fail and the control goes to the next statement following switch.
switch statement syntax:
switch (expression)
{ case condition1
statement1;
statement2;
......
break;
case condition2
statement1;
statement2;
.......
break;
.....
default:
statement1;
statement2;
.......
}
Example:
#include <stdio.h>
int main()
{
int salary,bonus;
char grade:
printf(“Enter grade : “);
scanf(“%c”, &grade);
printf(“Enter salary : “);
scanf(“%d”, &salary);
switch (grade)
{
case ‘a’:
case ‘A’: bonus=salary;
break;
case ‘b’:
case ‘B’: bonus=salary+5000;
break;
default : bonus=salary+10000; /*lower grade-more bonus*/
}
print(“Bonus = %d\n”, bonus);
return (0);
}
Q 3c. Write a C program to find whether a given year is leap year or not. [05 marks]
Ans:
/* to check whether a year is leap year */
#include <stdio.h>
main()
{
int y;
printf("Enter year : ");
scanf("%d",&y);
/* if year is a century year, it must be divided by 400 also*/
if((y%4==0) && (y%100 !=0) || (y%400==0))
printf("Yes %u is a leap year\n",y);
else
printf("No, %u is not leap year\n",y);
return (0);
}
Q 4a. Write the syntax of all looping control statements. Explain how break & continue statements are used in C program with example. [06 marks]
Ans:
There are 3 looping control statements in C:
while
do…while
for
while statement syntax:
while (condition)
{
statement1;
statement2;
......
}
do…while statement syntax: (It is a post tested loop & must executes at least once)
do
{
statement1;
statement2;
......
} while (condition);
for statement syntax:
for (initialization; test condition; increment or decrement)
{
statement1;
statement2;
.....
}
break & continue statements:
break statement would only exit from the loop containing it.
//Example program to check a number whether it is prime
#include<stdio.h>
int main()
{
int n,d,prime=1;
printf(“Enter a number : “);
scanf(“%d”, &n);
for (d=2;d<n/2;d++)
{
if (n%d==0)
prime=0;
break; /* there is no need to check further */
}
if (prime)
printf(“Yes %d is a prime number.\n”, n);
else
printf(“No, %d is not a prime number.\n”, n);
return (0);
}
continue statement:
The continue statement is used in loops to skip the following statements in the loop and to continue with the next iteration (current iteration in for loop).
//Example program to enter marks (0-100) in 6 subjects for sum
#include<stdio.h>
int main()
{
int marks,sum=0, x;
for (x=1;x<=6;x++)
{
printf(“Enter marks %d : “, x)
scanf(“%d”, &marks);
if(marks <0 || marks > 100)
{
printf(“Invalid marks!!!\n”);
continue; /* again read marks for same paper */
}
sum+=marks;
}
printf(“sum of marks = %d.\n”, sum);
return (0);
}
Q 4b. Write a C program to find square root of a given number without using library function.
[05 marks]
Ans:
/* to find square root (without using in-built function)*/
#include <stdio.h>
int main()
{
float n,r1,r2,diff;
printf("Enter number : ");
scanf("%f",&n);
r1=n/2.00; r2=n/r1;
do
{
r1=(r1+r2)/2.00;
r2=n/r1;
diff= r1-r2;
printf("simulating r1 = %.5f & r2 = %.5f\n",r1,r2);
}while(diff>0.000001);
printf("Square root = %.5f\n",r1); /*display r1 or r2 */
return (0);
}
Q 4c. List the difference between while & do-while loop. [05 marks]
Ans:
while is a pre-tested (entry-controlled) loop. Condition is checked before entering in the loop.
do-while is a post-tested (exit-controlled) loop. Condition is checked after execution of the statements within the loop.
The main difference is that do-while loop must execute once (because condition is checked at the end.)
Q 5a. Define the array. How one and two dimensional arrays are declared and initialized? Explain.
[07 marks]
Ans:
An array is an identifier that refers to the collection of data items which all have the same name. The individual data items are represented by their corresponding array elements. Address of an element (subscript) ranges from 0 to n-1, where n is total number of elements.
Declaration and initialisation of arrays:
One dimensional array:
syntax: type variable[size];
declaration: float height[50];
int batch[10];
char name[20];
initialisation: int marks[5] = {76,45,67,87,92};
static int count[ ] = {1,2,3,4,5};
static char name[5] = {‘S’, ‘I’, ‘N’, ‘G’, ‘H’, ‘\0’};
Two dimensional arrays:
declaration syntax: type arrayname[rowsize][columnsize];
examples: static int stud[16][5];
int marks[3][3] = {
{26,57,66},
{56,77,48},
{76,54,82}
};
int marks[3][3] = { {12},{0},{0}};
Here first element of each row is explicitly initialised to 12 while other elements are automatically initialised to zero.
Q 5b. Write C program to evaluate the polynomial equation f(x) = a0 + a1x + a2x2 + ............ an-1xn-1 + anxn for given constant x and its co-efficient. [05 marks]
Ans:
/* Evaluating polynomial by Horner's rule */
#include <stdio.h>
int main()
{
int order, i;
float x,a[15],sum;
printf("Enter value of x : ");
scanf("%f",&x);
printf("Enter order of polynomial : ");
scanf("%d",&order);
for(i=0;i<=order;i++)
{
printf("Enter coefficient at %d : ", i+1);
scanf("%f",&a[i]);
}
if(order ==0) { printf("Sum = %f\n",a[0]); return (99); }
sum=a[order]*x;
for(i=order-1;i>0; i--)
sum = (sum+a[i])*x;
sum+=a[0];
printf("Sum = %f\n",sum);
return (0);
}
Q 5c. Explain string input / output functions with example. [05 marks]
Ans:
All these string input & output functions are associated with header file stdio.h
String input function: gets( )
Usage : reads string with blanks and terminated with a new line character.
Syntax: gets(char str[]);
fgets() : reads string from file
Syntax: fgets(char str[], int length, FILE *fp);
Length is size of string & *fp is file pointer
String output function: puts( )
Usage : displays/prints string and terminated with a new line character.
fputs() : writes string to file
Syntax: fputs(char str[], FILE *fp);
Writes str to file pointed by file pointer *fp
Example
#include <stdio.h>
int main()
{
char name[30];
printf(“Enter your name : “);
gets(name);
printf(“You have entered : “);
puts(name);
return (0);
}
Q 6a. Explain how strings are declared and initialized with syntax and example: [06 marks]
Ans:
A string is array of characters terminated by single character. In C type of string is char.
Syntax to initialize:
Declaration: char str[5];
Initialization: char str[] = “SINGH”;
/* size should be kept blank for direct initialization.
Compiler will add NULL character by default*/
char str[5]={‘S’, ‘I’, ‘N’, ‘G’,’H’,’\0’};
String can be initialized by pointer to character also.
char *name=”SINGH”;
Q 6b. Write a C program to find the addition of two matrices. [04 marks]
Ans:
/*/Adding two matrices */
#include <stdio.h>
void addmat(int a[3][3], int b[3][3])
{
int c[3][3],row,col;
for(row=0;row<3;row++)
for(col=0;col<3;col++)
c[row][col] = a[row][col] + b[row][col];
puts("After addition:\n"); /* displaying resultant matrix */
for(row=0;row<3;row++)
{
for(col=0;col<3;col++)
printf("%5d",c[row][col]);
printf("\n");
}
}
int main()
{
int a[3][3], b[3][3], x,y;
printf("Enter data for matrix a:\n");
for(x=0;x<3;x++)
for(y=0;y<3;y++)
{
printf("Row %d Col %d : ", x+1, y+1);
scanf("%d",&a[x][y]);
}
printf("Enter data for matrix b:\n");
for(x=0;x<3;x++)
for(y=0;y<3;y++)
{
printf("Row %d Col %d : ",x+1,y+1);
scanf("%d",&b[x][y]);
}
addmat(a,b); /* calling function addmat with arguments a & b */
return (0);
}
Q 6c. Explain function definition, function call and function declaration with example. [06 marks]
Ans:
Here we discuss about user defined function.
A function is a self-contained block of statements that performs a coherent task of some kind. Arguments are written within ( ) parentheses separating by comma,
Function declaration:
Formal declaration of a function with its return type and types of arguments are known as prototype.
Syntax for declaring a function:
returntype functionname(type1, type2, type3,….);
example:
int rectarea(int, int);
Function Definition:
Operations are performed in function definition for which task is related. Arguments (parameters) are received from calling function with their types.
int rectarea(int len, int wid)
{
int a = len*wid;
return (a);
}
Function Call:
Functions are called passing the arguments only. Arguments should be as type of arguments are declared in function.
rectarea(x,y);
/* Now bringing everything together */
#include <stdio.h>
int rectarea(int, int); / * function declaration */
int main()
{
int x,y,area;
printf(“Enter length & width : “);
scanf(“%d%d”, &x, &y);
area=rectarea(x,y); /* function call */
printf(“Area of rectangle = %d square unit\n”, area);
return (0);
}
int rectarea(int len, int wid)
{
int a = len*wid;
return (a);
}
Q 7a. Define structure. Explain how structure members are accessed using dot (.) operator with example. [05 marks]
Ans:
Structure is a data structure whose individual elements can differ in type. It may contain integer elements, character elements, pointers, arrays and even other structures can also be included as elements within a structure.
Syntax to declare a structure:
struct tag
{
type member1;
type member2;
......
type member n;
};
Example:
struct student
{
int roll;
char name[30];
int marks;
};
struct student s1, s2; /* s1 & s2 are structure variables */
struct student s[60]; /* Array of structure */
Accessing structure members:
Structvariable.memberofstructure
Example:
s1.roll
s2.marks
in case of array s[x].marks
Q 7b. Show how structure variables are passed as a parameter to a function with example.
[05 marks]
Ans:
Passing structure to a function - There are three methods:
i) To pass each member of the structure as an actual arguments of the function call. It is unmanageable and inefficient when structure size is big.
ii) To pass a copy of the entire structure to the called function. All compilers do not support this method. Changes to structure members in called function have no effect to calling function. Again we have it has to return entire copy of the changed structure to the calling function.
iii) Use of pointers to pass the structure as an argument. In this way address of the structure is passed and structure elements can be accessed indirectly. It is more effective method.
/* Example program to pass structure as a parameter to a function */
#include <stdio.h>
struct emp {
char name[20];
char rank[10];
int salary;
}pay = { "B.N. Thakral","Assistant",27000};
int main()
{
struct emp sal( struct emp pay);
printf("\n salary of the employee = %s %s %d",
pay.name,pay.rank,pay.salary);
pay = sal(pay);
printf("\nUpdated salary of the employee = %s %s %d",
pay.name,pay.rank,pay.salary);
return (0);
}
struct emp sal( struct emp pay)
{
int inc;
printf("\n Enter increment \t");
scanf("%d",&inc);
pay.salary = pay.salary + inc;
return(pay);
}
Q 7c. Write a C Program to maintain record of ‘n’ student detail using array of structures with four fields(rno,name,marks,grade). Each field is an appropriate data type. Print the marks of student if student name is given. [06 marks]
Ans:
/* array of structure */
#include <stdio.h>
struct student
{
int rno,marks;
char name[30], grade[2];
};
int main()
{
int n,x,found=0;
char name2[30];
printf(“How many students ? “);
scanf(“%d”, &n);
struct student s[n];
for(x=0;x<n;x++)
{
printf(“Enter roll, name, marks & grade of student %d : “, x+1);
scanf(“%d%s%d%s”, &s[x].roll, s[x].name,&s[x].marks,s[x].grade);
}
printf(“Enter name of student to search : “);
scanf(“%s”, name2);
for(x=0;x<n;x++)
if(strcmp(s[x].name, name2) == 0)
{
found=1;
break;
}
If(found)
printf(“Marks of the student = %d\n”, s[x]. marks);
else
printf(“Not found\n”);
return (0);
}
Q 8a. Define file. Explain the different modes of file with suitable examples. [08 marks]
Ans:
A file is stream of data.
A file is a place on the disk where a group of related data is stored.
stream oriented ( standard ) data files are more commonly used
Opening files:
FILE *fp; /* fp is the file pointer */
fopen(“filename”, “mode”);
Q 8b. Explain the file function with example: [08 marks]
i) fopen()
ii) fprintf()
iii) fscanf()
iv) fgets()
Ans:
i) fopen( ) – opens file different modes
Syntax:
FILE *fp;
Example:
fp=fopen(“student.txt”,”r”);
ii) fprintf( ) – formatted output to a file
Syntax: fprintf ( fp, “control string”, var1,var2,..varn);
file pointer variable,constants, strings
Example: fprintf( f1, “%s %d %f\n ”, name, age, 7.8);
iii) fscanf( ) – formatted input from file
Syntax: fscanf(fp, “control string”, &var1, &var2,….&varn);
Example: fscanf(f2, “ %s %d”, item, &qtty);
iv) fgets( ) – reads string from file terminated with new line character
Syntax: fgets(char str[], int length, FILE *fp);
Example: fgets(name,30,fp);
Q 9a. What is pointer? Explain how pointer variable is declared and initialized. [05 marks]
Ans:
A pointer keeps address of data. A pointer is variable that represents the location ( rather than the value) of a data item, such as a variable or an array element.
Pointers is an important feature of C and frequently used in C. They have a number of useful applications.
Pointer operator is asterisk ( * ).
To declare a pointer: datatype *pointervariable;
To initialize: pointervariable = &data;
& is address of operator.
Example1:
int n;
int *p; /* here p is pointer variable & can be used to keep address */
p=&n; /* here p keeps address of n */
Example2:
int a[5] = { 10,20.30,40,50};
int *p;
p = a; /* It is equivalent to p = &a[0]; Here it keeps address of first element */
Q 9b. Explain any two pre-processor directives in C with example. [05 marks]
Ans:
A pre-processor represents pre-compilation process. These directives are preceded with # ( and there is no semicolon at the end).
C has the special feature of pre-processor directives. The pre-processor processes the C source code before it passes to the compiler. Pre-processor directives are executed before the C source code passes through the compiler.
Example of two pre-processor directives:
i) #define
#define directive is used to define the symbolic constant or macro name with macro
expression.
#define symconstant value
#define macroname macroexpression
Example
#define PI 3.141
Here the C pre-processor searches for the symbolic constant PI the source code and
substitutes 3.141 each time it is encountered.
As the function, a macro can have argument. The argument of the macro name is replaced
with actual argument of the macro name, which is encountered in the program.
Examples:
#define MAX(x,y) ( (x) > (y) ? (x) : (y) )
#define CUBE(x) (x)*(x)*(x)
ii) #include
This pre-processor is used to include another file. File name is written in angle brackets or
within double quotes.
#include <stdio.h>
#include “SORT.H”
File name enclosed within angle brackets are searched in standard directories. File name
enclosed within double quotes are searched first in the current directory and if not found
then it is searched in the standard directories.
Q 9c. Write a C program to swap two numbers using pointer concept. [05 marks]
Ans:
/* Program to swap two numbers using pointers */
#include <stdio.h>
void swap(int *p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;
}
int main()
{
int num1, num2;
printf(“Enter number 1 : “);
scanf(“%d”, &num1);
printf(“Enter number 2 : “);
scanf(“%d”, &num2);
swap(&num1, &num2);
printf(“Numbers swapped: num1 = %d num2 = %d\n”, num1, num2);
return (0);
}
Q 10a. What are primitive and non-primitive data types? Explain. [05 marks]
Ans:
A data type is a classification of data, which can store a specific type of information.
Primitive data types are primary, fundamental or predefined types of data, which are supported by the programming language. In C primitive data types are:
char
int
float
double
Programmers can use these data types when creating variables in their programs. For example, a programmer may create a variable called marks and define it as a int data type type.
Examples:
int marks;
double num = 0.00;
char c;
float sum;
Non-primitive data types are derived data types or composed data types from primary data types. Non-primitive data types are not defined by the programming language, but are instead created by the programmer. Arrays, pointers, structures are examples of derived data type.
Examples:
int a[10];
struct student
{
int roll;
char name[20];
int marks;
};
int *p;
Q 10b. List the applications of stack and queue data structure. [05 marks]
Ans:
Stack:
A stack is a LIFO (Last In First Out) data structure where item inserted at last will be deleted first.
Applications of stack:
Backtracking
Undoing
Reversing
Recursion (Recursive functions, Recurrence relation)
Converting Infix to Postfix
Queue:
A Queue is FIFO (First in First Out) data structure where item inserted at first will be processed/deleted first.
Applications of Queue:
Process Scheduling (CPU Scheduling in computers)
Inserting from one end and taking from other end
FCFS (First Come First Serve) applications
Resource Sharing among same priority customers
Asynchronous transmission of data
Q 10c. Write a C program to find sum and mean of all elements in an array using pointers.
[05 marks]
Ans:
/* sum & mean of elements using pointers */
#include <stdio.h>
#include <stdlib.h>
int main()
{
double *a,sum=0.00,mean;
int x,n;
printf("How many numbers : ");
scanf("%d",&n);
a=malloc(sizeof(double)*n); /* allocating memory */
for(x=0;x<n;x++)
{
printf("Enter number %d : ", x+1);
scanf("%lf",(a+x));
sum+= *(a+x); /* using pointers */
}
mean=(double)sum/n;
printf("Sum = %0.3lf Mean = %0.3lf",sum,mean);
return (0);
}