0% found this document useful (0 votes)
9 views

Solution sample for exam

The document discusses the concept of functions in C programming, including their definition, advantages, and the differences between passing arguments by value and by reference. It also covers various types of if statements, the switch statement, structures, logical operators, break and continue statements, binary and unary operators, and string handling in C. Additionally, it provides example code snippets to illustrate these concepts.

Uploaded by

iamanuroadh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Solution sample for exam

The document discusses the concept of functions in C programming, including their definition, advantages, and the differences between passing arguments by value and by reference. It also covers various types of if statements, the switch statement, structures, logical operators, break and continue statements, binary and unary operators, and string handling in C. Additionally, it provides example code snippets to illustrate these concepts.

Uploaded by

iamanuroadh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

1. Define function and list its advantages.

Describe the difference between passing


arguments by value and passing arguments by reference with suitable example. (4+6)

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.

Passing Arguments by value:

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);

[email protected] SULAV NEPAL


}
void main()
{
int x=2,y=3;
printf("Before swap function call: x=%d & y=%d",x,y);
swap(x,y);
printf("\nAfter swap function call: x=%d & y=%d",x,y);
getch();
}

Passing Arguments by reference:

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 */ }

[email protected] SULAV NEPAL


If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else
block 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=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();
}

if…else if…else Statement


An if statement can be followed by an optional else if . . . else statement, which is very useful to
test various conditions. Syntax is given below:
if(boolean_expression1)
{ /* statement(s) will execute if the Boolean expression 1 is true */ }
else if(boolean_expression2)
{ /* statement(s) will execute if the Boolean expression 2 is true */ }
else
{ /* statement(s) will execute if both Boolean expressions are false */ }

#include<stdio.h>
#include<conio.h>
void main()
{

[email protected] SULAV NEPAL


int a=100;
if(a==10)
{ printf("Value of a is 10\n"); }
else if(a==20)
{ printf("Value of a js 20\n"); }
else if(a==30)
{ printf("Value of a is 30\n"); }
else
{ printf("None of the values are matching\n"); }
printf("Exact value of a is %d\n",a);
getch();
}

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)
{

[email protected] SULAV NEPAL


printf("Value of a is 100 & b is 200\n");
}
}
printf("Exact value of a is: %d\n",a);
printf("Exact value of b is: %d\n",b);
getch();
}

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;
}

[email protected] SULAV NEPAL


3. What is structure? How is it different from array? Create a structure student having
data members name, roll-number and percentage. Complete the program to display the
name of student having percentage greater than or equal to 60. (1+2+7)

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);

[email protected] SULAV NEPAL


printf("Enter Percentage :\n");
scanf("%f", &stud[i].percentage);
}
for(int i=0; i<5; i++)
{
if(stud[i].percentage>60)
{
printf("Student %d\n",i+1);
printf("Name: %s \nRoll: %d \nPercentage:
%f\n",stud[i].name,stud[i].roll_no,stud[i].percentage);
}
}
return 0;
}

4. Discuss different logical operators in detail. (5)

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.

[email protected] SULAV NEPAL


#include<stdio.h>
#include<conio.h>
void main()
{ int a=5, b=20;
if(a && b)
{ printf("Line 1 - Condition is true\n"); }
else
{ printf("Line 1 - Condition is not true\n"); }
if(a || b)
{ printf("Line 2 - Condition is true\n"); }
else
{ printf("Line 2 - Condition is not true\n"); }
// Let us change the value of a and b
a=0; b=10;
if(a && b)
{ printf("Line 3 - Condition is true\n"); }
else
{ printf("Line 3 - Condition is not true\n"); }
if(!(a && b))
{ printf("Line 4 - Condition is true\n"); }
getch();
}

5. What is break statement? Discuss with example. How the break statement is different
from continue statement? (2+3)

The break statement in C programming has the following two usages:


• When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement.
Syntax for break statement is given below:
break;
[email protected] SULAV NEPAL
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
while(a<20)
{
printf("Value of a: %d\n",a);
a++;
if(a>15)
{
break;
}
}
getch();
}

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;

[email protected] SULAV NEPAL


6. List various binary and unary operators used in C. Write a program that uses a
“while” loop to compute and print the sum of a given numbers of squares. For example,
if 4 is input, then the program will print 30, which is equal to 𝟏𝟐 + 𝟐𝟐 + 𝟑𝟐 + 𝟒𝟐 . (1+4)

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;
}

[email protected] SULAV NEPAL


7. “Size of character array is always declared one more than the input size.” Justify the
statement. Write a program to read a character array input as “TEXAS
INTERNATIONAL COLLEGE” from the user and find out how many times a
character “A” occurs in that array? (1+4)

In C programming, an array of character are called strings. A string is terminated by null


character \0. For example: “C Strings”. Here, “C STRINGS” is a string. When compiler
encounters strings, it appends null character at the end of string.

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.

[email protected] SULAV NEPAL


9. Write a program to find sum and average of 10 integer numbers stored in an array. (5)

#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);

[email protected] SULAV NEPAL


Here, ptr is a pointer of type data_type. The malloc() returns a pointer to an area of memory with
size size_of_block.
x=(int*) malloc(100*sizeof(int));
A memory space equivalent to 100 times the size of an integer is reserved and the address of the
first byte of the memory allocated is assigned to the pointer x of type int. (i.e. x refers to the first
address of allocated memory).

// Program to calculate the sum of n numbers entered by the user


#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
if(ptr == NULL) // if memory cannot be allocated
{
printf("Error! memory not allocated."); exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i); sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
Here, we have dynamically allocated the memory for "n" number of "int".

[email protected] SULAV NEPAL


11. Write a program to calculate discount:
a. If purchased amount is greater than or equal to 5000, discount is 10%.
b. If purchased amount is greater than or equal to 4000 and less than 5000,
discount is 7%.
c. If purchased amount is greater than or equal to 3000 and less than 4000,
discount is 5%.
d. If purchased amount is greater than or equal to 2000 and less than 3000,
discount is 3%.
e. If purchased amount is less than 2000, discount is 2%.

#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( )

Local and Global Variables


Local variables are also known as Automatic variables or Internal variables. They are always
declared inside a function or block in which they are to be used. They are created when the
function is called and destroyed automatically when the function is exited, hence the name is
automatic. The keyword auto is used for storage class specification although it is optional.
• Initial value: garbage.
• Scope: local to the block where the variable is defined.
• Lifetime: till the control remains within the block where variable is defined.

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);

[email protected] SULAV NEPAL

You might also like