Solution sample for exam
Solution sample for exam
A function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among
different function is up to you – but logically the division should be such that each function
performs a specific task. The advantages of function are:
• Manageability
o Easier to write and keep track of.
o Easier to understand and maintain.
• Code Reusability
o Can be used multiple times.
• Non-redundant programming
o Same function can be called when needed.
• Logical Clarity
o Reduced number of code in main function.
• Easy to divide work
o Large work can be divided by writing different functions.
When values of actual arguments are passed to the function as arguments, it is known as passing
by value. Here, the value of each actual argument is copied into corresponding formal argument
of the function definition. The contents of the actual arguments in the calling function are not
changed, even if they are changed in the called function.
#include<stdio.h>
#include<conio.h>
void swap(int a,int b)
{
int t; t=a; a=b; b=t;
printf("\nValues within swap: a=%d & b=%d",a,b);
When addresses of actual arguments are passed to the function as arguments (instead of values of
actual arguments), it is known as passing by address. Here, the address of each actual argument
is copied into corresponding formal argument of the function definition. In this case, the formal
arguments must be of type pointers. The values contained in addresses of the actual arguments in
the calling function are changed, if they are changed in the called function.
#include<stdio.h>
#include<conio.h>
void swap(int *x,int *y)
{
int temp; temp=*x; *x=*y; *y=temp;
printf("Values within swap: x=%d & y=%d\n",*x,*y);
}
void main()
{
int a=23, b=34;
printf("Before swap function call: a=%d & b=%d\n",a,b);
swap(&a,&b);
printf("After swap function call: a=%d & b=%d\n",a,b);
getch();
}
[email protected] SULAV NEPAL
2. Discuss different types of if statements with suitable example of each. Differentiate if
statement with switch statement. (8+2)
If statement
If statement consists of a Boolean expression followed by one or more statements. Syntax for if
statement is here below:
if(boolean_expression)
{ /* statement(s) will execute if the Boolean expression is true */ }
If the Boolean expression evaluates to true, then the block of code inside the “if” statement will
be executed. If the Boolean expression evaluates to false, then the first set of code after the end
of “if” statement will be executed. C programming language assumes any non-zero and non-null
values as true and if it is either zero or null, then it is assumed as false value.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
if(a<20)
{ printf("a is less than 20\n"); }
printf("Value of a is: %d\n", a);
getch();
}
if…else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false. Syntax is given below:
if(boolean_expression)
{ /* statement(s) will execute if the Boolean expression is true */ }
else
{ /* statement(s) will execute if the Boolean expression is false */ }
#include<stdio.h>
#include<conio.h>
void main()
{
int a=100;
if(a<20)
{ printf("a is less than 20\n"); }
else
{ printf("a is not less than 20\n"); }
printf("Value of a is %d", a);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
Nested if Statement
It is always legal in C programming to nest if-else statements, i.e. you can use one if or else if
statement inside another if or else if statement(s). Syntax is given below:
if(boolean_expression1)
{ /* statement(s) will execute if the Boolean expression 1 is true */
if(boolean_expression2)
{ /* statement(s) will execute if the Boolean expression 2 is true */ }
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a=100, b=200;
if(a==100)
{
if(b==200)
{
Switch Statement
Switch statement allows a program to select one statement for execution of a set of alternatives.
Only one of the possible statements will be executed, the remaining statements will be skipped.
The multiple usage of if…else statement increases the complexity of the program, hard to read,
and difficult to follow the program. Switch statement removes these disadvantages by using a
simple and straight forward approach. Syntax for switch statement is given below:
switch(expression)
{
case caseConstant1:
statement(s);
break;
case caseConstant2:
statement(s);
break;
.
.
.
default:
statement;
}
A structure is a collection of variables under a single name. Arrays allow defining type of
variables that can hold several data items of the same kind. Similarly structure is another user
defined data type available in C that allows combining data items of different kinds. A structure
is a convenient way of grouping several pieces of related information together. A structure is a
convenient tool for handling a group of logically related data items. For example: name, roll, fee,
marks, address, gender, and phone are related information of a student. To store information
about a student, we would require to store the name of the student which is array of characters,
roll of student which is integer type of data and so on. These attributes of students can be
grouped into a single entity, student. Here, student is known as structure which organizes
different data types in a more meaningful way.
#include <stdio.h>
struct Student
{
char name[30];
int roll_no;
float percentage;
};
int main()
{
struct Student stud[5];
for(int i=0; i<5; i++)
{
printf("Student %d\n",i+1);
printf("Enter name :\n");
scanf("%s",stud[i].name);
printf("Enter roll no. :\n");
scanf("%d", &stud[i].roll_no);
Operators are the symbol that operates on certain data type or data item. It is used in program to
perform certain mathematical or logical manipulations. For example: In a simple expression 5+6,
the symbol “+” is called an operator which operates on two data items 5 and 6. The data items
that operator act upon are called operands.
Logical Operator
Assume variable A holds 1 and variable B holds 0, then
Operator Description Example
Called “Logical AND Operator”. If both the operands are non-
&& (A&&B) is false
zero, then the condition becomes true.
Called “Logical OR Operator”. If any of the two operands is
|| (A||B) is true
non-zero, then the condition becomes true.
Called “Logical NOT Operator”. It is used to reverse the logical
!(A&&B) is true
! state of its operand. If a condition is true, then Logical NOT
!(A||B) is false
Operator will make it false.
5. What is break statement? Discuss with example. How the break statement is different
from continue statement? (2+3)
break continue
The break statement is used to terminate the
The continue statement is used to bypass the
control from the switch…case structure as well
execution of the further statements.
in the loop.
When the break statement is encountered, it
When the continue statement is encountered, it
terminates the execution of the entire loop or
bypasses single pass of the loop.
switch case.
It doesn’t bypass the current loop though it
It is used to bypass current pass through a loop.
transfers the control out of the loop.
The loop terminates when a break is The loop doesn’t terminate when continue is
encountered. encountered.
Syntax: break; Syntax: continue;
Operators are the symbol that operates on certain data type or data item. It is used in program to
perform certain mathematical or logical manipulations. Different types of binary and unary
operators used in C are listed below:
• Arithmetic Operator
• Relational Operator
• Logical or Boolean Operator
• Assignment Operator
• Ternary Operator
• Bitwise Operator
• Increment or Decrement Operator
• Conditional Operator
• Special Operators (sizeof and comma)
#include<stdio.h>
int main()
{
int n, sum=0, i=0;
printf("Enter n value: ");
scanf("%d", &n);
while(i<=n)
{
sum += (i*i); i++;
}
printf("Sum of squares of first %d natural numbers = %d",
n, sum);
return 0;
}
C S T R I N G S \0
Strings are actually one-dimensional array of characters terminated by a null character. Thereby,
size of character array is always declared one more than the input size.
#include<stdio.h>
#include <string.h>
int main()
{
char s[1000],c;
int i,count=0;
printf("Enter the string : ");
gets(s);
printf("Enter character to be searched: ");
c=getchar();
for(i=0;s[i];i++)
{
if(s[i]==c)
{
count++;
}
}
printf("character '%c' occurs %d times \n ",c,count);
return 0;
}
[email protected] SULAV NEPAL
8. What is function? Discuss the benefits of using function. (1+4)
A function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among
different function is up to you – but logically the division should be such that each function
performs a specific task. Suppose a program where a set of operations has to be repeated often,
though not continuously. Loops seems like a better option. Instead of inserting the program
statements for these operations at so many places, a separate program segment is written and
compiled it separately. As many times as it is needed, the segment program is called. The
separate program segment is called a function. The C functions can be classified into two
categories:
• User Defined Function
• Library Function
Few benefits of using functions in C are listed below:
• Manageability
o Easier to write and keep track of.
o Easier to understand and maintain.
• Code Reusability
o Can be used multiple times.
• Non-redundant programming
o Same function can be called when needed.
• Logical Clarity
o Reduced number of code in main function.
• Easy to divide work
o Large work can be divided by writing different functions.
#include <stdio.h>
int main()
{
int i;
int num[10];
float sum = 0, avg;
printf("Enter 10 numbers:\n");
for(i=1;i<=10;i++)
{
scanf("%d", &num[i]);
sum += num[i];
}
avg = sum / 10;
printf("Sum=%.2f\nAverage = %.2f", sum,avg);
return 0;
}
10. What is dynamic memory allocation? Discuss the use of malloc( ) in DMA with
example. (1+4)
The process of allocating and freeing memory at run time is known as dynamic memory
allocation. This reserves the memory required by the program and returns valuable resources to
the system once the use of reserved space is utilized. Consider an array size of 100 to store marks
of 100 student. If the number of students is less than 100 say 10, only 10 memory locations will
be used and rest 90 locations are reserved but will not be used. i.e. wastage of memory will
occur. In such situation DMA will be useful.
malloc()
It allocates requested size of bytes and returns a pointer to the first byte of the allocated space.
ptr=(data_type*) malloc(size_of_block);
#include <stdio.h>
#include <conio.h>
void main()
{
float amount,discount;
printf("Enter the amount:\n");
scanf("%f",&amount);
if(amount>=5000)
{ discount=10*amount/100; }
else if(amount>=4000 && amount<5000)
{ discount=7*amount/100; }
else if(amount>=3000 && amount<4000)
{ discount=5*amount/100; }
else if(amount>=2000 && amount<3000)
{ discount=3*amount/100; }
else
{ discount=2*amount/100; }
printf("The discount amount is %.2f and the total amount after getting discount is
%.2f",discount, amount-discount);
getch();
}
[email protected] SULAV NEPAL
12. Write short notes on the following: (2.5*2)
a. Local & Global variables
b. free( )
Global Variables are also known as External variables. These variables are both alive and active
throughout the entire program. Unlike local variables, global variables can be accessed by any
function in the program.
• Initial value: zero
• Scope: global (i.e. throughout the program)
• Lifetime: throughout program execution
free( )
free( ) frees previously allocated space by calloc, malloc or realloc functions. The memory
dynamically allocated is not returned to the system until the programmer returns the memory
explicitly. This can be done using free() function. This function is used to release the space when
not required. Syntax for DMA - free() is given below:
free(ptr);