Sie sind auf Seite 1von 50

Unit 3& 4

M.K.Srivastava
Date:15/3/2016

Q:

What do you mean by Functions in programming? What are its types?

In programming, a function is a segment that groups code to perform a specific task.


A C program has at least one function main() . Without main() function, there is technically
no C program.
Types of C functions
There are two types of functions in C programming:
Library function
User defined function
Library function
Library functions are the in-built function in C programming system. For example:
main()
- The execution of every C program starts from this

main()

function.

printf()
-

prinf()

is used for displaying output in C.

scanf()
-

scanf()

is used for taking input in C.

User defined function


C allows programmer to define their own function according to their requirement. These
types of functions are known as user-defined functions. Suppose, a programmer wants to
find factorial of a number and check whether it is prime or not in same program. Then,
he/she can create two separate user-defined functions in that program: one for finding
factorial and other for checking whether it is prime or not.
Q:

How user-defined function works in C Programming?

#include <stdio.h>
void function_name()
{
................

//function decleration and definition

int main(){
...........
function_name();
...........
}

//function calling

As mentioned earlier, every C program begins from main() and program starts
executing the codes inside main() function. When the control of program reaches
to function_name() inside main() function. The control of program jumps to void
function_name() and executes the codes inside it. When all the codes inside that userdefined function are executed, control of the program jumps to the statement just
after function_name() from where it is called. Analyze the figure below for
understanding the concept of function in C programming

Remember, the function name is an identifier and should be unique.


Advantages of user defined functions

1. User defined functions helps to decompose the large program into small
segments which makes programmer easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include those
codes and execute when needed by calling that function.
3. Programmer working on large project can divide the workload by making
different functions.

Q:
Write an example of user-defined function and explain definition of
functions - return values and their types - function calls - function
declaration
/*Program to demonstrate the working of user defined function*/
#include<stdio.h>
intadd(int a,int b);//function prototype(declaration)
intmain(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2);//function call
printf("sum=%d",sum);
return0;
}
intadd(int a,int b)//function definition
{
/* Start of function definition. */
int add;
add=a+b;
returnadd;//return statement of function
/* End of function definition. */
}
Function prototype(declaration):

Every function in C programming should be declared before they


are used. These type of declaration are also called function
prototype. Function prototype gives compiler information about
function name, type of arguments to be passed and return type.
Syntax of function prototype

return_type function_name(type(1) argument(1),....,type(n)


argument(n));

In the above example, int add(int a, int b); is a function prototype


which provides following information to the compiler:
1. name of the function is add()
2. return type of the function is int .
3. two arguments of type int are passed to function.
Function prototype are not needed if user-definition function is
written before main() function.
Function call

Control of the program cannot be transferred to user-defined


function unless it is called invoked.

Syntax of function call


function_name(argument(1),....argument(n));
In
the
above
example,
function
call
is
made
using
statement add(num1,num2); from main() . This make the control of
program jump from that statement to function definition and
executes the codes inside that function.
Function definition

Function definition contains programming codes to perform


specific task.
Syntax of function definition

return_type function_name(type(1) argument(1),..,type(n)


argument(n))
{
//body of function
}
Function definition has two major components:

1. Function declarator
Function declarator is the first line of function definition. When a
function is called, control of the program is transferred to function
declarator.
Syntax of function declarator
return_type function_name(type(1) argument(1),....,type(n)
argument(n))
Syntax of function declaration and declarator are almost same
except, there is no semicolon at the end of declarator and function
declaration is followed by function body.
In above example, int add(int a,int b) in line 12 is a function
declarator.

2. Function body
Function declarator is followed by body of function inside braces.
Passing arguments to functions
In programming, argument(parameter) refers to data this is
passed to function(function definition) while calling function.
In above example two variable, num1 and num2 are passed to
function during function call and these arguments are accepted by
arguments a and b in function definition.

Arguments that are passed in function call and arguments that are
accepted in function definition should have same data type. For
example:
If argument num1 was of int type and num2 was of float type then,
argument variable a should be of type int and b should be of type
float,i.e., type of argument during function call and function
definition should be same.
A function can be called with or without an argument.
Return Statement
Return statement is used for returning a value from function
definition to calling function.

Syntax of return statement


return (expression);
For example:
return a;
return (a+b);

In above example, value of variable add in add() function is


returned
and
that
value
is
stored
in
variable sum in main() function. The data type of expression in
return statement should also match the return type of function.

Q
Differentiate between call by value and call by
reference
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a function
S.N
.

Call Type & Description

Call by value
This method copies the actual value of an argument into the formal parameter of the function. In
this case, changes made to the parameter inside the function have no effect on the argument.

Call by reference
This method copies the address of an argument into the formal parameter. Inside the function,
the address is used to access the actual argument used in the call. This means that changes made

to the parameter affect the argument.

Q
What are different types of User-defined Functions in C
Programming
For better understanding of arguments and return type in
functions, user-defined functions can be categorised as:
1. Function with no arguments and no return value
2. Function with no arguments and return value
3. Function with arguments but no return value
4. Function with arguments and return value .
Let's take an example to find whether a number is prime or not
using above 4 categories of user defined functions.

Function with no arguments and no return value.


/*C program to check whether a number entered by user is prime or not
using function with no arguments and no return value*/
#include<stdio.h>
voidprime();
intmain(){
prime();
//No argument is passed to prime().
return0;
}
voidprime(){
/* There is no return value to calling function main(). Hence, return type
of prime() is void */
intnum,i,flag=0;
printf("Enter positive integer enter to check:\n");
scanf("%d",&num);
for(i=2;i<=num/2;++i){

if(num%i==0){
flag=1;
}
}
if (flag==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
}

Function prime() is used for asking user a input, check for whether it
is prime of not and display it accordingly. No argument is passed
and returned form prime() function.

Function with no arguments but return value


/*C program to check whether a number entered by user is prime or not
using function with no arguments but having return value */
#include<stdio.h>
intinput();
intmain(){
intnum,i,flag = 0;
num=input();
/* No argument is passed to input() */
for(i=2; i<=num/2; ++i){
if(num%i==0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not prime",num);
else
printf("%d is prime", num);
return0;
}

intinput(){ /* Integer value is returned from input() to calling function


*/
int n;
printf("Enter positive integer to check:\n");
scanf("%d",&n);
return n;
}

There is no argument passed to input() function But, the value


of n is returned from input() to main() function.

Function with arguments and no return value


/*Program to check whether a number entered by user is prime or not
using function with arguments and no return value */
#include<stdio.h>
void check_display(int n);
intmain(){
int num;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
check_display(num); /* Argument num is passed to function. */
return0;
}
void check_display(int n){
/* There is no return value to calling function. Hence, return type of
function is void. */
int i, flag = 0;
for(i=2; i<=n/2; ++i){
if(n%i==0){
flag = 1;
break;
}
}
if(flag == 1)

printf("%d is not prime",n);


else
printf("%d is prime", n);
}

Here, check_display() function is used for check whether it is prime or


not and display it accordingly. Here, argument is passed to userdefined function but, value is not returned from it to calling
function.

Function with argument and a return value


/* Program to check whether a number entered by user is prime or not
using function with argument and return value */
#include<stdio.h>
intcheck(int n);
intmain(){
intnum,num_check=0;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
num_check=check(num); /* Argument num is passed to check()
function. */
if(num_check==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
return0;
}
intcheck(int n){
/* Integer value is returned from function check() */
int i;
for(i=2;i<=n/2;++i){
if(n%i==0)
return1;
}
return0;

Here, check() function is used for checking whether a number is


prime or not. In this program, input from user is passed to
function check() and integer value is returned from it. If input the
number is prime, 0 is returned and if number is not prime, 1 is
returned.
Q:
What do you mean by scope of a variable? Explain local and global variable in
detail.
A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed. There are three places where variables
can be declared in C programming language

Inside a function or a block which is called local variables.

Outside of all functions which is called global variables.

In the definition of function parameters which are called formalparameters.

Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They can be
used only by statements that are inside that function or block of code. Local variables are not
known to functions outside their own. The following example shows how local variables are
used. Here all the variables a, b, and c are local to main() function.
#include<stdio.h>
int main (){
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a =10;
b =20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return0;

Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables
hold their values throughout the lifetime of your program and they can be accessed inside any of
the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. The following program show how global
variables are used in a program.
#include<stdio.h>
/* global variable declaration */
int g;
int main (){
/* local variable declaration */
int a, b;
/* actual initialization */
a =10;
b =20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return0;
}

A program can have same name for local and global variables but the value of local variable
inside a function will take preference. Here is an example
#include<stdio.h>
/* global variable declaration */
int g =20;
int main (){
/* local variable declaration */
int g =10;
printf ("value of g = %d\n", g);

return0;
}

When the above code is compiled and executed, it produces the following result
value of g = 10

Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take precedence
over global variables. Following is an example
#include<stdio.h>
/* global variable declaration */
int a =20;
int main (){
/* local variable declaration in main function */
int a =10;
int b =20;
int c =0;
printf ("value of a in main() = %d\n", a);
c =sum( a, b);
printf ("value of c in main() = %d\n", c);
return0;
}
/* function to add two integers */
intsum(int a,int b){
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}

When the above code is compiled and executed, it produces the following result
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20

value of c in main() = 30

Initializing Local and Global Variables


When a local variable is defined, it is not initialized by the system, you must initialize it
yourself. Global variables are initialized automatically by the system when you define them as
follows
Data Type

Initial Default Value

int

char

'\0'

float

double

pointer

NULL

It is a good programming practice to initialize variables properly, otherwise your program may
produce unexpected results, because uninitialized variables will take some garbage value
already available at their memory location.
Q:
What do you mean by Recursion in C Programming. Explain with
an example
A function that calls itself is known as recursive function and this technique is known as
recursion in C programming.
Example of recursion in C programming
Write a C program to find sum of first n natural numbers using recursion. Note: Positive
integers are known as natural number i.e. 1, 2, 3....n
#include<stdio.h>
intsum(int n);

intmain(){
intnum,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
intsum(int n){
if(n==0)
return n;
else
return n+sum(n-1);/*self call to function sum() */
}

Output
Enter a positive integer:
5
15
In, this simple C program, sum() function is invoked from the same function. If n is not
equal to 0 then, the function calls itself passing argument 1 less than the previous
argument it was called with. Suppose, n is 5 initially. Then, during next function calls, 4
is passed to function and the value of argument decreases by 1 in each recursive call.
When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5
to 1.
For better visualization of recursion in this example:

sum(5)

=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Every recursive function must be provided with a way to end the recursion. In this
example when, n is equal to 0, there is no recursive call and recursion ends.
Advantages and Disadvantages of Recursion

Recursion is more elegant and requires few variables which make program clean.
Recursion can be used to replace complex nesting code by dividing the problem
into same problem of its sub-type.
In other hand, it is hard to think the logic of a recursive function. It is also
difficult to debug the code containing recursion.
Q:
Write a C Program to Display Prime Numbers Between Intervals Using User-defined
Function
A positive integer which is only divisible by 1 and iself is known as prime number. For example: 13 is a
prime number because it is only divisible by 1 and 13 but, 15 is not prime number because it is divisible
by 1, 3, 5 and 15.
#include<stdio.h>
int check_prime(int num);
int main(){
int n1,n2,i,isPrime;
printf("Enter two numbers(intervals): ");
scanf("%d %d",&n1, &n2);
printf("Prime numbers between %d and %d are: ", n1, n2);
for(i=n1+1;i<n2;++i)
{
isPrime=check_prime(i);
if(isPrime==0)

printf("%d ",i);
}
return 0;
}
int check_prime(int num) /* User-defined function to check prime number*/
{
int j,isPrime=0;
for(j=2;j<=num/2;++j){
if(num%j==0){
isPrime=1;
break;
}
}
return isPrime;
}
Q:
Write a C program to Find Sum of Natural Numbers using Recursion
#include<stdio.h>
int add(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Sum = %d",add(n));
return 0;
}
int add(int n)
{
if(n!=0)
return n+add(n-1); /* recursive call */
}
Output
Enter an positive integer: 20
Sum = 210
Q:
Write a C program to Calculate Factorial of a Number Using Recursion
/* Source code to find factorial of a number. */
#include<stdio.h>
int factorial(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;

}
int factorial(int n)
{
if(n!=1)
return n*factorial(n-1);
}
Output
Enter an positive integer: 6
Factorial of 6 = 720
Q:
Write a C Program to Find G.C.D / H.C.F. Using Recursion
/* Example to calculate GCD or HCF using recursive function. */
#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d%d", &n1, &n2);
printf("H.C.F of %d and %d = %d", n1, n2, hcf(n1,n2));
return 0;
}
int hcf(int n1, int n2)
{
if (n2!=0)
return hcf(n2, n1%n2);
else
return n1;
}
Output
Enter two positive integers: 366
60
H.C.F of 366 and 60 = 6
Q:
Write a C program to Reverse a Sentence Using Recursion
/* Example to reverse a sentence entered by user without using strings. */
#include <stdio.h>
void Reverse();
int main()
{
printf("Enter a sentence: ");
Reverse();
return 0;
}
void Reverse()

{
char c;
scanf("%c",&c);
if( c != '\n')
{
Reverse();
printf("%c",c);
}
}
Output
Enter a sentence: margorp emosewa
awesome program
Q:
Write a C Program to Convert Binary Number to Decimal and vice-versa
/* C programming source code to convert either binary to decimal or decimal to binary according to data
entered by user. */
#include <stdio.h>
#include <math.h>
int binary_decimal(int n);
int decimal_binary(int n);
int main()
{
int n;
char c;
printf("Instructions:\n");
printf("1. Enter alphabet 'd' to convert binary to decimal.\n");
printf("2. Enter alphabet 'b' to convert decimal to binary.\n");
scanf("%c",&c);
if (c =='d' || c == 'D')
{
printf("Enter a binary number: ");
scanf("%d", &n);
printf("%d in binary = %d in decimal", n, binary_decimal(n));
}
if (c =='b' || c == 'B')
{
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("%d in decimal = %d in binary", n, decimal_binary(n));
}
return 0;
}
int decimal_binary(int n) /* Function to convert decimal to binary.*/
{
int rem, i=1, binary=0;

while (n!=0)
{
rem=n%2;
n/=2;
binary+=rem*i;
i*=10;
}
return binary;
}
int binary_decimal(int n) /* Function to convert binary to decimal.*/
{
int decimal=0, i=0, rem;
while (n!=0)
{
rem = n%10;
n/=10;
decimal += rem*pow(2,i);
++i;
}
return decimal;
}
Output
Instructions:
1. Enter alphabet 'd' to convert binary to decimal.
2. Enter alphabet 'b' to convert decimal to binary.
d
Enter a binary number: 110111
110111 in binary = 55 in decimal
Q:
Write a C Program to Check Armstrong Number. (Unit 2)
A positive integer is called anArmstrong number if the sum of cubes of individual digit is equal to
thatnumber itself. For example: 153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is anArmstrong number.
/* C program to check whether a number entered by user is Armstrong or not. */
#include <stdio.h>
int main()
{
int n, n1, rem, num=0;
printf("Enter a positive integer: ");
scanf("%d", &n);
n1=n;
while(n1!=0)
{
rem=n1%10;
num+=rem*rem*rem;

n1/=10;
}
if(num==n)
printf("%d is an Armstrong number.",n);
else
printf("%d is not an Armstrong number.",n);
}
Output
Enter a positive integer: 371
371 is an Armstrong number.
Q:
Explain Uses of C functions.
1. C functions are used to avoid rewriting same logic/code again and again in a program.
2. There is no limit in calling C functions to make use of same functionality wherever required.
3. We can call functions any number of times in a program and from any place in a program.
4. A large C program can easily be tracked when it is divided into functions.
5. The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve
the functionality and to improve understandability of very large C programs.

Unit 4
Q:
What do you mean by an array?
C Array is a collection of variables belongings to the same data type. You can store group of data of same
data type in an array.

Array might be belonging to any of the data types


Array size must be a constant value.
Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
It is a best practice to initialize an array to zero or null while declaring, if we dont assign any
values to array.
Example for C Arrays:
int a[10];
// integer array
char b[10]; // character array i.e. string
Q:
How many Types of arrays are there in C? Give Example.
There are 2 types of C arrays. They are,
1. One dimensional array
2. Multi dimensional array
1. Two dimensional array
2. Three dimensional array, four dimensional array etc
1. One dimensional array in C:
Syntax : data-type arr_name[array_size];
Array
Array initialization
Accessing array
declaration
Syntax: data_t data_type arr_name
arr_name[index];
ype arr_name [arr_size]=(value1, value2,

[arr_size];
int age [5];
char str[10];

value3,.);
int age[5]={0, 1, 2, 3, 4};

age[0];_/*0_is_accessed*/age[1];_/*1_is_accessed*/age[2];_/*2_
is_accessed*/
char str[10]={H,a,i}; (o str[0];_/*H is accessed*/str[1]; /*a is accessed*/str[2]; /* i is
r)char str[0] = H;char
accessed*/
str[1] = a;
char str[2] = i;

Example program for one dimensional array in C:


#include<stdio.h>int main(){
int i;
int arr[5] = {10,20,30,40,50};
// declaring and Initializing array in C
//To initialize all array elements to 0, use int arr[5]={0};
/* Above array can be initialized as below also
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */
for (i=0;i<5;i++)
{
// Accessing each variable
printf(value of arr[%d] is %d \n, i, arr[i]);
}
}
Output:
value of arr[0] is 10
value of arr[1] is 20

value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
2. Two dimensional array in C:
Two dimensional array is nothing but array of array.
syntax : data_type array_name[num_of_rows][num_of_column]
S.no
Array declaration
Array initialization
1 Syntax: data_type arr_name
data_type arr_name[2][2] =
[num_of_rows][num_of_column];
{{0,0},{0,1},{1,0},{1,1}};
2 Example:int arr[2][2];
int arr[2][2] = {1,2, 3, 4};

Accessing array
arr_name[index];
arr [0] [0] = 1; arr [0] ]1]
= 2;arr [1][0] = 3;
arr [1] [1] = 4;

Example program for two dimensional array in C:


#include<stdio.h>int main(){
int i,j;
// declaring and Initializing array
int arr[2][2] = {10,20,30,40};
/* Above array can be initialized as below also
arr[0][0] = 10; // Initializing array
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40; */
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
// Accessing variables
printf(value of arr[%d] [%d] : %d\n,i,j,arr[i][j]);
}

}
}
Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40
Q:
Give example of multidimensional array initialization.

In C, multidimensional arrays can be initialized in different number of ways.

int c[2][3]={{1,3,0}, {-1,5,9}};


OR
int c[][3]={{1,3,0}, {-1,5,9}};
OR
int c[2][3]={1,3,0,-1,5,9};
Initialization Of three-dimensional Array

double cprogram[3][2][4]={
{{-0.1, 0.22, 0.3, 4.3}, {2.3, 4.7, -0.9, 2}},
{{0.9, 3.6, 4.5, 4}, {1.2, 2.4, 0.22, -1}},
{{8.2, 3.12, 34.2, 0.1}, {2.1, 3.2, 4.3, -2.0}}
};
Q:
Write a C Program to Add Two Matrix Using Multi-Dimensional Arrays
#include<stdio.h>
int main() {
int i, j, mat1[10][10], mat2[10][10], mat3[10][10];
int row1, col1, row2, col2;
printf("\nEnter the number of Rows of Mat1 : ");
scanf("%d", &row1);
printf("\nEnter the number of Cols of Mat1 : ");
scanf("%d", &col1);
printf("\nEnter the number of Rows of Mat2 : ");
scanf("%d", &row2);
printf("\nEnter the number of Columns of Mat2 : ");
scanf("%d", &col2);

/* Before accepting the Elements Check if no of


rows and columns of both matrices is equal */
if (row1 != row2 || col1 != col2) {
printf("\nOrder of two matrices is not same ");
exit(0);
}
//Accept the Elements in Matrix 1
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
printf("Enter the Element a[%d][%d] : ", i, j);
scanf("%d", &mat1[i][j]);
}
}
//Accept the Elements in Matrix 2
for (i = 0; i < row2; i++)
for (j = 0; j < col2; j++) {
printf("Enter the Element b[%d][%d] : ", i, j);
scanf("%d", &mat2[i][j]);
}
//Addition of two matrices
for (i = 0; i < row1; i++)
for (j = 0; j < col1; j++) {
mat3[i][j] = mat1[i][j] + mat2[i][j];
}
//Print out the Resultant Matrix
printf("\nThe Addition of two Matrices is : \n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
printf("%d\t", mat3[i][j]);
}
printf("\n");
}
return (0);
}
Output
Enter the number of Rows of Mat1 : 3
Enter the number of Columns of Mat1 : 3
Enter the number of Rows of Mat2 : 3
Enter the number of Columns of Mat2 : 3

Enter the Element a[0][0] : 1


Enter the Element a[0][1] : 2
Enter the Element a[0][2] : 3
Enter the Element a[1][0] : 2
Enter the Element a[1][1] : 1
Enter the Element a[1][2] : 1
Enter the Element a[2][0] : 1
Enter the Element a[2][1] : 2
Enter the Element a[2][2] : 1
Enter the Element b[0][0] : 1
Enter the Element b[0][1] : 2
Enter the Element b[0][2] : 3
Enter the Element b[1][0] : 2
Enter the Element b[1][1] : 1
Enter the Element b[1][2] : 1
Enter the Element b[2][0] : 1
Enter the Element b[2][1] : 2
Enter the Element b[2][2] : 1
The Addition of two Matrices is :
246
422
242
Q:
Write a C program for matrix multiplication
#include<stdio.h>
int main() {
int a[10][10], b[10][10], c[10][10], i, j, k;
int sum = 0;
printf("\nEnter First Matrix : n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}
printf("\nEnter Second Matrix:n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &b[i][j]);
}
}
printf("The First Matrix is: \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", a[i][j]);
}

printf("\n");
}
printf("The Second Matrix is : \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", b[i][j]);
}
printf("\n");
}
//Multiplication Logic
for (i = 0; i <= 2; i++) {
for (j = 0; j <= 2; j++) {
sum = 0;
for (k = 0; k <= 2; k++) {
sum = sum + a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}
printf("\nMultiplication Of Two Matrices : \n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf(" %d ", c[i][j]);
}
printf("\n");
}
return (0);
}
Q:
Write a C Program to find Transpose of Given Square Matrix
#include<stdio.h>
#include<conio.h>
void main() {
int arr[10][10], size, i, j, temp;
printf("\nEnter the size of matrix :");
scanf("%d", &size);
printf("\nEnter the values a:");
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
scanf("%d", &arr[i][j]);
}
}
printf("\nGiven square matrix is");
for (i = 0; i < size; i++) {

printf("\n");
for (j = 0; j < size; j++) {
printf("%d\t", arr[i][j]);
}
}
/* Find transpose */
for (i = 1; i < size; i++) {
for (j = 0; j < i; j++) {
temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
printf("\nTranspose matrix is :");
for (i = 0; i < size; i++) {
printf("\n");
for (j = 0; j < size; j++) {
printf("%d\t", arr[i][j]);
}
}
getch();
}
Q:
Write a C program for Addition of Diagonal Elements in Matrix
#include<stdio.h>
int main() {
int i, j, mat[10][10], row, col;
int sum = 0;
printf("\nEnter the number of Rows : ");
scanf("%d", &row);
printf("\nEnter the number of Columns : ");
scanf("%d", &col);
//Accept the Elements in m x n Matrix
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("\nEnter the Element a[%d][%d] : ", i, j);
scanf("%d", &mat[i][j]);
}
}

//Addition of all Diagonal Elements


for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
if (i == j)
sum = sum + mat[i][j];
}
}
//Print out the Result
printf("\nSum of Diagonal Elements in Matrix : %d", sum);
return (0);
}
Output

Enter the number of Rows : 2


Enter the number of Columns : 2
Enter the Element a[0][0] : 1
Enter the Element a[0][1] : 1
Enter the Element a[1][0] : 1
Enter the Element a[1][1] : 1
The Addition of All Elements in the Matrix : 2
Elements in the Matrix : 2
Q:
What do you mean by C Strings? Give example.

C Strings are nothing but array of characters ended with null character (\0).

This null character indicates the end of the string.

Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.

Example for C string:

char string[20] = { f , r , e , s , h , 2 , r , e , f , r , e , s , h , \0}; (or)

char string[20] = fresh2refresh; (or)

char string []

Difference between above declarations are, when we declare char as string[20], 20 bytes of memory
space is allocated for holding the string value.

= fresh2refresh;

When we declare char as string[], memory space will be allocated as per the requirement during
execution of the program.

Example program for C string:


#include <stdio.h>
intmain()
{
charstring[20]="fresh2refresh.com";

printf("The string is : %s \n",string);


return0;
}

Output:
The string is : fresh2refresh.com

Q:

How Strings are initialized in C?

In C, string can be initialized in different number of ways.

char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};

Q:
Write a short note on gets and puts functions.
gets() and puts()
Functions gets() and puts() are two string functions to take string input from user and display string
respectively as mentioned in previous chapter.
#include<stdio.h>
int main(){
char name[30];
printf("Enter name: ");

gets(name); //Function to read string from user.


printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Though, gets() and puts() function handle string, both these functions are defined in "stdio.h" header file.
String Manipulations In C Programming Using Library Functions
Q:
What do you mean by string manipulation in C? Give example.
Strings are often needed to be manipulated by programmer according to the need of a problem. All string
manipulation can be done manually by the programmer but, this makes programming complex and large.
To solve this, the C supports a large number of string handling functions.
There are numerous functions defined in "string.h" header file. Few commonly used string handling
functions are discussed below:
Function
strlen()
strcpy()
strcat()
strcmp()
strlwr()
strupr()

Work of Function
Calculates the length of string
Copies a string to another string
Concatenates(joins) two strings
Compares two string
Converts string to lowercase
Converts string to uppercase

strlen()
In C, strlen() function calculates the length of string. It takes only one argument, i.e, string
name.
Defined in Header File <string.h>
Syntax of strlen()

temp_variable = strlen(string_name);
Function strlen() returns the value of type integer.

Example of strlen()

#include<stdio.h>
#include<string.h>
intmain(){
chara[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
charc[20];
printf("Enter string: ");
gets(c);
printf("Length of string a=%d \n",strlen(a));
//calculates the length of string before null charcter.
printf("Length of string b=%d \n",strlen(b));
printf("Length of string c=%d \n",strlen(c));
return0;
}
Output

Enter string: String


Length of string a=7
Length of string b=7
Length of string c=6

strcpy()
Function strcpy() copies the content of one string to the content of another string. It takes two
arguments.
Defined in Header File <string.h>
Syntax of strcpy()

strcpy(destination,source);
Here, source and destination are both the name of the string. This statement, copies the content
of string source to the content of string destination.
Example of strcpy()

#include<stdio.h>
#include<string.h>
intmain(){
char a[10],b[10];
printf("Enter string: ");
gets(a);
strcpy(b,a);//Content of string a is copied to string b.
printf("Copied string: ");
puts(b);
return0;
}
Output

Enter string: Programming Tutorial


Copied string: Programming Tutorial

strcat()
In C programming, strcat() concatenates(joins) two strings. It takes two arguments, i.e, two
strings and resultant string is stored in the first string specified in the argument.
Defined in Header File <string.h>
Syntax of strcat()
strcat(first_string,second_string);
Example of strcat()
#include<stdio.h>
#include<string.h>
intmain(){
char str1[]="This is ", str2[]="programiz.com";
strcat(str1,str2);//concatenates str1 and str2 and resultant string is stored in str1.
puts(str1);
puts(str2);
return0;

}
Output

This is programiz.com
programiz.com

strcmp()
In C programming, strcmp() compares two string and returns value 0, if the two strings are
equal. Function strcmp() takes two arguments, i.e, name of two string to compare.
Defined in Header File: <string.h>
Syntax of strcmp()

temp_varaible=strcmp(string1,string2);
Example of strcmp()
#include<stdio.h>
#include<string.h>
intmain(){
char str1[30],str2[30];
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Both strings are equal");
else
printf("Strings are unequal");
return0;
}
Output

Enter first string: Apple


Enter second string: Apple
Both strings are equal.
If two strings are not equal, strcmp() returns positive value if ASCII value of first mismatching
element of first string is greater than that of second string and negative value if ASCII value of
first mismatching element of first string is less than that of second string. For example:

char str1[]="and",str2[]="cat";
temp=strcmp(str1,str2);

strlwr()
In C programming, strlwr() function converts all the uppercase characters in that string to
lowercase characters. The resultant from strlwr() is stored in the same string.
Defined in header file: <string.h>
Syntax of strlwr()

strlwr(string_name);
Example of strlwr()

#include<stdio.h>
#include<string.h>
intmain(){
char str1[]="LOWer Case";
puts(strlwr(str1));//converts to lowercase and displays it.
return0;
}
Output
lower case

Function strlwr() leaves the lowercase characters as it is and converts uppercase characters to
lowercase.

strupr()
In C programming, strupr() function converts all the lowercase characters in that string to
uppercase characters. The resultant from strupr() is stored in the same string.
Defined in Header File: <string.h>
Syntax of strupr()

strupr(string_name);
Example of strupr()
#include<stdio.h>
#include<string.h>
intmain(){
char str1[]="UppEr Case";
puts(strupr(str1));//Converts to uppercase and displays it.
return0;
}
Output

UPPER CASE
Function strupr() leaves the uppercase characters as it is and converts lowercase characters to
uppercase.

Q:
What is a Structure in C Programming? How will you define and declare
a function? What is the procedure to access the members of a structure?
Structure is the collection of variables of different types under a single name for better
handling. For example: You want to store the information about person about his/her name,
citizenship number and salary. You can create these information separately but, better approach
will be collection of these information under single name because all these information are
related to person.

Structure Definition in C
Keyword struct is used for creating a structure.
Syntax of structure

struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};
We can create the structure for a person as mentioned above as:

struct person
{
char name[50];
int cit_no;
float salary;
};
This declaration above creates the derived data type struct person.
Structure variable declaration
When a structure is defined, it creates a user-defined type but, no storage is allocated. For the
above structure of person, variable can be declared as:

struct person
{
char name[50];
int cit_no;
float salary;
};

Inside main function:


struct person p1, p2, p[20];
Another way of creating sturcture variable is:

struct person
{
char name[50];
int cit_no;
float salary;
}p1 ,p2 ,p[20];
In both cases, 2 variables p1, p2 and array p having 20 elements of type struct personare
created.
Accessing members of a structure
There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->) (will be discussed in structure and pointers chapter )
Any member of a structure can be accessed as: structure_variable_name.member_name
Suppose, we want to access salary for variable p2. Then, it can be accessed as:

p2.salary
Example of structure
Write a C program to add two distances entered by user. Measurement of distance should be in
inch and feet.(Note: 12 inches = 1 foot)

#include<stdio.h>
structDistance{
int feet;

float inch;
}d1,d2,sum;
intmain(){
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d",&d1.feet);/* input of feet for structure variable d1 */
printf("Enter inch: ");
scanf("%f",&d1.inch);/* input of inch for structure variable d1 */
printf("2nd distance\n");
printf("Enter feet: ");
scanf("%d",&d2.feet);/* input of feet for structure variable d2 */
printf("Enter inch: ");
scanf("%f",&d2.inch);/* input of inch for structure variable d2 */
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;
if(sum.inch>12){//If inch is greater than 12, changing it to feet.
++sum.feet;
sum.inch=sum.inch-12;
}
printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch);
/* printing sum of distance d1 and d2 */
return0;
}
Output

1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances= 15'-5.7"
Q:

How will you use keyword typedef while using structure

Programmer generally use typedef while using structure in C language. For example:

typedef struct complex{


int imag;
float real;
}comp;
Inside main:
comp c1,c2;
Here, typedef keyword is used in creating a type comp(which is of type as struct complex).
Then, two structure variables c1 and c2 are created by this comp type.
Structures within structures
Structures can be nested within other structures in C programming.

struct complex
{
int imag_value;
float real_value;
};
struct number{
struct complex c1;
int real;
}n1,n2;
Suppose you want to access imag_value for n2 structure variable then, structure
member n1.c1.imag_value is used.
Q:

How structure variable can be passed to the function? Give an Example.

Passing structure by value


A structure variable can be passed to the function as an argument as normal variable. If structure
is passed by value, change made in structure variable in function definition does not reflect in
original structure variable in calling function.

Write a C program to create a structure student, containing name and roll. Ask user the name
and roll of a student in main function. Pass this structure to a function and display the
information in that function.
#include<stdio.h>
structstudent{
charname[50];
int roll;
};
voidDisplay(struct student stu);
/* function prototype should be below to the structure declaration otherwise compiler shows
error */
intmain(){
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1);// passing structure variable s1 as argument
return0;
}
voidDisplay(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}
Output

Enter student's name: Kevin Amla


Enter roll number: 149
Output
Name: Kevin Amla
Roll: 149
Q:

C Program to Calculate sum of two Time Periods using structure

#include<stdio.h>

struct time
{
int h,m,s;
}t1,t2,t3;
void main()
{
printf("enter time1(h m s)");
scanf("%d%d%d",&t1.h,&t1.m,&t1.s);
printf("enter time2(h m s)");
scanf("%d%d%d",&t2.h,&t2.m,&t2.s);
t3.h=t1.h+t2.h;
t3.m=t1.m+t2.m;
t3.s=t1.s+t2.s;
if(t3.s>59)
{
t3.s=t3.s-60;
t3.m=t3.m+1;
}
if(t3.m>59)
{
t3.m=t3.m-60;
t3.h=t3.h+1;
}
if(t3.h>23)
{
t3.h=t3.h-24;
}
printf("The sum of time is: %dH:%dM:%dS",t3.h,t3.m,t3.s);
}
Q:
Explain with an example array of structure.
C Structure is collection of different datatypes ( variables ) which are grouped together. Whereas, array of
structures is nothing but collection of structures. This is also called as structure array in C.
Example program for array of structures in C:
This program is used to store and access id, name and percentage for 3 students. Structure array is used
in this program to store and display records for many students. You can store n number of students
record by declaring structure variable as struct student record[n], where n can be 1000 or 5000 etc.
#include <stdio.h>
#include <string.h>
structstudent
{
intid;
charname[30];
floatpercentage;

};
intmain()
{
inti;
structstudent record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name,"Raju");
record[0].percentage=86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name,"Surendren");
record[1].percentage=90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name,"Thiyagu");
record[2].percentage=81.5;
for(i=0;i<3;i++)
{
printf(" Records of STUDENT : %d n",i+1);
printf(" Id is: %d n",record[i].id);
printf(" Name is: %s n",record[i].name);
printf(" Percentage is: %fnn",record[i].percentage);
}
return0;
}
Output:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
Q:

Explain with example nested structure in c


Structure within Structure : Nested Structure

Structure written inside another structure is called as nesting of two structures.


Nested Structures are allowed in C Programming Language.

We can write one Structure inside another structure as member of another structure.
Way 1 : Declare two separate structures
struct date
{
int date;
int month;
int year;
};
struct Employee
{
charename[20];
int ssn;
float salary;
struct date doj;
}emp1;
Accessing Nested Elements :
1. Structure members are accessed using dot operator.
2. date structure is nested within Employee Structure.
3. Members of the date can be accessed using employee
4. emp1 & doj are two structure names (Variables)
Explanation Of Nested Structure :
Accessing Month Field : emp1.doj.month
Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year
Way 2 : Declare Embedded structures
struct Employee
{
charename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp1;
Accessing Nested Members :
Accessing Month Field : emp1.doj.month

Accessing day Field : emp1.doj.day


Accessing year Field : emp1.doj.year
Live Complete Example :
#include <stdio.h>
struct Employee
{
charename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp={"Pritesh",1000,1000.50,{22,6,1990}};
intmain(int argc,char*argv[])
{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee SSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", \
emp.doj.date,emp.doj.month,emp.doj.year);
return0;
}
Output :
Employee Name : Pritesh
Employee SSN :1000
Employee Salary :1000.500000
Employee DOJ :22/6/1990

Q:
Write a short note on Unions in C Programming. In what way they are
different from structure.
Unions are quite similar to the structures in C . Union is also a derived type as structure. Union
can be defined in same manner as structures just the keyword used in defining union
in union where keyword used in defining structure was struct.

union car{
char name[50];
int price;
};
Union variables can be created in similar manner as structure variable.

union car{
char name[50];
int price;
}c1, c2, *c3;

OR;

union car{
char name[50];
int price;
};
-------Inside Function----------union car c1, c2, *c3;
In both cases, union variables c1, c2 and union pointer variable c3 of type union car is created.
Accessing members of an union
The member of unions can be accessed in similar manner as that structure. Suppose, we you
want to access price for union variable c1 in above example, it can be accessed as c1.price. If
you want to access price for union pointer variable c3, it can be accessed as (*c3).price or as c3>price.
Difference between union and structure
Though unions are similar to structure in so many ways, the difference between them is crucial
to understand. This can be demonstrated by this example:

#include<stdio.h>
union job {//defining a union
charname[32];
float salary;
int worker_no;
}u;
struct job1 {
charname[32];
float salary;
int worker_no;
}s;
intmain(){
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d",sizeof(s));
return0;
}
Output

size of union = 32
size of structure = 40
There is difference in memory allocation between union and structure as suggested in above
example. The amount of memory required to store a structure variables is the sum of memory
size of all members.

But, the memory required to store a union variable is the memory required for largest element of
an union.

What difference does it make between structure and union?


As you know, all members of structure can be accessed at any time. But, only one member of
union can be accessed at a time in case of union and other members will contain garbage value.

#include <stdio.h>
union job {
char name[32];
float salary;
int worker_no;
}u;
int main(){
printf("Enter name:\n");
scanf("%s",&u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
return 0;
}
Output

Enter name
Hillary
Enter salary

1234.23
Displaying
Name: f%Bary
Salary: 1234.2

Note: You may get different garbage value of name.


Why this output?
Initially, Hillary will be stored in u.name and other members of union will contain garbage
value. But when user enters value of salary, 1234.23 will be stored in u.salaryand other
members will contain garbage value. Thus in output, salary is printed accurately but, name
displays some random string.
Passing Union To a Function
Union can be passed in similar manner as structures in C programming.

Das könnte Ihnen auch gefallen