C Language:
C Language:
C for the
beginner 's by Md Farrukh Asif
Operators
in C by Md. Farrukh Asif
C's
Control Flow by Md. Farrukh Asif
String handling in C by Md Farrukh Asif
The
Function of C Language by Md. Farrukh Asif
File Handling
with various statements/syntaxes in Programming and their output in C Language.
C
for beginner's programming with output. Course Code – 106 [‘C’]) TMBU,BGP
BCA
SOLVED EXAMINATION QUESTIONS WITH ANSWERS Course Code – 106 [‘C’]) TMBU,BGP
Function:
o Standard Library Function:
o User Defined Function:
o Recursive Function:
o Function prototype
ü Calling a function
ü Function definition
ü Syntax of function definition
ü Arrays in C:
ü C Array declaration :
ü Initialization of an Array:
ü C Multidimensional Arrays:
ü Initializing a multidimensional
array:
ü Passing an Array to a Function:
ü Pointers:
Function:
A function
is a block of code that performs a specific task. To address a problem of
creating a program to create a circle and color it, two functions can be
created: one to create a circle and another to create a color. By dividing a
complex problem into smaller chunks, our program becomes easier to understand
and reuse.
In C programming,
there are two types of functions: standard library functions and user-defined
functions.
Standard
library functions are built-in functions in C programming and are defined in the
<stdio.h> header files.
For
example, the printf() function is a standard library function used to send
formatted output to the screen.
To use
this function, the stdio.h header file needs to be included using #include
<stdio.h>.
Another
example is the sqrt() function, which calculates the square root of a number
and is defined in the math.h header file.
To learn
more about standard library functions in C programming, you can visit the
appropriate resource.
On the
other hand, user-defined functions can be created according to specific needs.
These functions, created by the user, are known as user-defined functions.
C
User-defined functions
A function
is a block of code that performs a specific task.
C allows
you to define functions according to your need. These functions are known as
user-defined functions. For example:
Suppose,
you need to create a circle and color it depending upon the radius and color.
You can create two functions to solve this problem:
Create
Circle() function
color()
function
Example:
User-defined function
Here is an
example to add two integers. To perform this task, we have created an
user-defined addNumbers().
// An
example of user defined function …..
#include
<stdio.h>
int
addNum(int a, int b); // function
prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNum (n1, n2); // function call
printf("The Sum = %d",sum);
return 0;
}
// User
defined Function begins here……
int addNum
(int a, int b) // function
definition
{
int result;
result = a+b;
return result; // return statement
}
Recursive
Function:
When
programming in C, recursion is when a function calls itself multiple times to
solve a small problem. These functions are called recursive functions, and when
they call themselves, it's known as a recursive call.
The
process of recursion in the C language consists of multiple recursive calls.
And, it is also a prerequisite that you choose a termination condition for the
recursive function- or else, the program will be stuck in a loop.
Examples
of Recursive Function #1:
Write a C
program that prints the 10th values of the Fibonacci series.
//Author:
Farrukh Asif
#include<stdio.h>
int
myfibo(int);
void main
()
{
int a,b,n;
printf(“Please
enter the value of the n number here : “);
scanf(“%d”,&a);
b=
myfibo(a);
printf(“%d”,b);
}
int
myfibo(int a)
{
if (a==0)
{
return 0;
}
else if (a
== 1)
{
return 1;
}
else
{
return
myfibo(a-1) + myfibo(a-2);
}
}
---------------------------------------------------------------
The output
generated here from the code mentioned above would be:
Please
enter the value of the n number here : 10
55
-----------------------------------------------------------
Examples
of Recursive Function #2:
// Author:
“Farrukh Asif”
#include<stdio.h>
#include<conio.h>
int
fact(int a); /* Definition of Function */
void
main()
{
int n,
result;
clrscr();
printf(“Please
enter a non-negative number here: “);
scanf(“%d”,&n);
result =
factorial(n);
/*
Function Calling in a Normal way */
printf(“%d!
= %d” , n , result);
getch();
}
int
factorial(int a) /* Definition of Function */
{
int x=1;
if(a <=
0)
{
return(1);
}
else
{
x = a *
factorial(a-1);
/*
Function Call Recursively as the fact() calls itself in the program */
return(x);
}
}
--------------------------------------------------------------
The output
generated here from the code mentioned above would be: Please enter a
non-negative number here: 5
---------------------------------------------------------------
5! = 120
--------------------------------------------------------------
Function
prototype:
A function
prototype is simply the declaration of a function that specifies function's
name, parameters and return type. It doesn't contain function body.
A function
prototype gives information to the compiler that the function may later be used
in the program.
Syntax of
function prototype
returnType
functionName(type1 argument1, type2 argument2, ...);
In the
above example, int addNum (int a, int b); is the function prototype which provides
the following information to the compiler:
·
name
of the function is addNum ()
·
return
type of the function is int
·
two
arguments of type int are passed to the function
·
The
function prototype is not needed if the user-defined function is defined before
the main() function.
Calling a
function
Control of
the program is transferred to the user-defined function by calling it.
Syntax of
function call
functionName(argument1,
argument2, ...);
In the
above example, the function call is made using addNumbers(n1, n2); statement
inside the main() function.
Function
definition
Function
definition contains the block of code to perform a specific task. In our
example, adding two numbers and returning it.
Syntax of
function definition
returnType
functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}
When a
function is called, the control of the program is transferred to the function
definition. And, the compiler starts executing the codes inside the body of a
function.
C Program
to Reverse a Sentence Using Recursion
#include
<stdio.h>
void
revSent();
int main()
{
printf("Enter a sentence: ");
revSent ();
return 0;
}
void
revSent () {
char c;
scanf("%c", &c);
if (c != '\n') {
revSent ();
printf("%c", c);
}
}
----------------
Output
----------------
Enter a
sentence: awesome program
margorp
emosewa
C program
to calculate the power using recursion
//Author:
‘Farrukh Asif’
#include
<stdio.h>
int
power(int n1, int n2);
int main()
{
int base, a, result;
printf("Enter base number: ");
scanf("%d", &base);
printf("Enter power number(positive
integer): ");
scanf("%d", &a);
result = power(base, a);
printf("%d^%d = %d", base, a,
result);
return 0;
}
int
power(int base, int a) {
if (a
!= 0)
return (base * power(base, a - 1));
else
return 1;
}
----------
Output
----------
Enter base
number: 3
Enter
power number(positive integer): 4
3^4 = 81
------------------------------------------------
Arrays in
C:
An array
is a variable that can store multiple values. For example, if you want to store
100 integers, you can create an array for it.
int
data[100];
How to
declare an array?
dataType arrayName[arraySize];
For
example,
float
mark[5];
Here, we
declared an array, mark, of floating-point type. And its size is 5. Meaning, it
can hold 5 floating-point values.
It's
important to note that the size and type of an array cannot be changed once it
is declared.
Access
Array Elements
You can
access elements of an array by indices.
Makr[0] |
Makr[1] |
Makr[2] |
Makr[3] |
Makr[4] |
|
|
|
|
|
Suppose
you declared an array mark as above. The first element is mark[0], the second
element is mark[1] and so on.
C Array
declaration
Declare an
Array
Some keynotes:
Exhibits
have 0 as the primary record, not 1. In this model, marks[0] is the main
component.
In the
event that the size of a cluster is n, to get to the keep going component, the
n-1 record is utilized. In this model, marks[4]
Assume the
beginning location of marks[0] is 2120d. Then, the location of the marks[1]
will be 2124d. Likewise, the location of marks[2] will be 2128d, etc.
This is on
the grounds that the size of a float is 4 bytes.
This is
because the size of a float is 4 bytes.
How to
initialize an array?
It is
possible to initialize an array during declaration. For example,
int marks[5]
= {19, 10, 8, 17, 9};
You can
also initialize an array like this.
int marks[]
= {19, 10, 8, 17, 9};
Here, we
haven't specified the size. However, the compiler knows its size is 5 as we are
initializing it with 5 elements.
Initialize
an array in C programming
It is
possible to initialize an array during declaration. For example,
int
marks[5] = {19, 10, 8, 17, 9};
You can
also initialize an array like this.
int
marks[] = {19, 10, 8, 17, 9};
Here, we
haven't specified the size. However, the compiler knows its size is 5 as we are
initializing it with 5 elements.
Example 1:
Array Input/Output
// Program
to take 5 values from the user and store them in an array
// Md. Farrukh
Asif
// Print
the elements stored in the array
#include
<stdio.h>
int main()
{
int num[5];
printf("Enter
5 integers: ");
// taking
input and storing it in an array
for(int i = 0; i < 5; ++i) {
scanf("%d", & num [i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; ++i) {
printf("%d\n", num [i]);
}
return 0;
}
---------------
Output
---------------
Enter 5
integers: 1
-3
34
0
3
Displaying
integers: 1
-3
34
0
3
---------------
Example 2:
Calculate Average
// Program
to find the average of n numbers using arrays
#include
<stdio.h>
int main()
{
int marks[10], i, n, sum = 0;
double
average;
printf("Enter
number of elements: ");
scanf("%d",
&n);
for(i=0; i
< n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the user to the
sum variable
sum += marks[i];
}
// explicitly convert sum to double
// then calculate average
average = (double) sum / n;
printf("Average = %.2lf", average);
return 0;
}
-------------
Output
-------------
Enter
number of elements: 5
Enter
number1: 45
Enter
number2: 35
Enter
number3: 38
Enter
number4: 31
Enter
number5: 49
Average =
39.60
-------------------------
C’ss
Multidimensional Arrays
In C programming,
we can create an array of arrays. Generally these arrays are known as
multidimensional arrays. For example,
float
multi[3][4];
Here,
multi is a two-dimensional (2d) array. The array can hold 12 elements. You can
think the array as a table with 3 rows and each row has 4 columns.
Two
dimensional array in C programming
Two
dimensional Array
Similarly,
you can declare a three-dimensional (3d) array. For example,
float
y[2][4][3];
Here, the
array y can hold 24 (2*4*3) elements.
Initializing
a Multidimensional Array:
Here is
how you can initialize two-dimensional and three-dimensional arrays:
Initialization
of a 2d array
//
Different ways to initialize two-dimensional array
int
c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[][3]
= {{1, 3, 0}, {-1, 5, 9}};
int
c[2][3] = {1, 3, 0, -1, 5, 9};
Example 1:
Two-dimensional array to store and print values
// C
program to store temperature of two cities of a week //and display it.
//Farrukh
Asif
#include
<stdio.h>
const int
CITY = 2;
const int
WEEK = 7;
int main()
{
int temperature[CITY][WEEK];
// Here
the matrices ar 2 * 7 = 14 cells or locations
// Using nested loop to store values in a 2d
array
for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d: ", i +
1, j + 1);
scanf("%d",
&temperature[i][j]);
}
}
printf("\nDisplaying values:
\n\n");
// Using nested loop to display vlues of a 2d
array
for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d =
%d\n", i + 1, j + 1, temperature[i][j]);
}
}
return 0;
}
-------------
Output
-------------
City 1,
Day 1: 33
City 1,
Day 2: 34
City 1,
Day 3: 35
City 1,
Day 4: 33
City 1,
Day 5: 32
City 1,
Day 6: 31
City 1,
Day 7: 30
City 2,
Day 1: 23
City 2,
Day 2: 22
City 2,
Day 3: 21
City 2,
Day 4: 24
City 2,
Day 5: 22
City 2,
Day 6: 25
City 2,
Day 7: 26
-----------------------
Displaying
values:
-----------------------
City 1,
Day 1 = 33
City 1,
Day 2 = 34
City 1,
Day 3 = 35
City 1,
Day 4 = 33
City 1,
Day 5 = 32
City 1,
Day 6 = 31
City 1,
Day 7 = 30
City 2,
Day 1 = 23
City 2,
Day 2 = 22
City 2,
Day 3 = 21
City 2,
Day 4 = 24
City 2,
Day 5 = 22
City 2,
Day 6 = 25
City 2,
Day 7 = 26
----------------------------
Example 2:
Sum of two matrices
// C prog.
to find the sum of two matrices of order 2*2
// Farrukh
Asif
#include
<stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
// Taking input using nested for loop
printf("Enter elements of 1st
matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1,
j + 1);
scanf("%f", &a[i][j]);
}
// Taking input using nested for loop
printf("Enter elements of 2nd
matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1,
j + 1);
scanf("%f", &b[i][j]);
}
// adding corresponding elements of two
arrays
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}
// Displaying the sum
printf("\nSum Of Matrix:");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);
if (j == 1)
printf("\n");
}
return 0;
}
----------------
Output
---------------
Enter
elements of 1st matrix
Enter a11:
2;
Enter a12:
0.5;
Enter a21:
-1.1;
Enter a22:
2;
Enter
elements of 2nd matrix
Enter b11:
0.2;
Enter b12:
0;
Enter b21:
0.23;
Enter b22:
23;
Sum Of
Matrix:
2.2 0.5
-0.9 25.0
----------------------
Example 3:
Three-dimensional array
// C Prog.
to store and print 12 values entered by the user
// Farrukh
Asif
#include
<stdio.h>
int main()
{
int test[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d",
&test[i][j][k]);
}
}
}
// Printing values with the proper index.
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for
(int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] =
%d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
-------------
Output
-------------
Enter 12
values:
1
2
3
4
5
6
7
8
9
10
11
12
-----------------------
Displaying
Values:
test[0][0][0]
= 1
test[0][0][1]
= 2
test[0][1][0]
= 3
test[0][1][1]
= 4
test[0][2][0]
= 5
test[0][2][1]
= 6
test[1][0][0]
= 7
test[1][0][1]
= 8
test[1][1][0]
= 9
test[1][1][1]
= 10
test[1][2][0]
= 11
test[1][2][1]
= 12
---------------------
Passing an
Array to a Function:
Example 1:
Pass Arrays to Functions
// Program
to calculate the sum of array elements by //passing to a function
//Farrukh
Asif
#include
<stdio.h>
float
calculateSum(float num[]);
int main()
{
float result, num[] = {23.4, 55, 22.6, 3,
40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
//
Function begins here….
float
calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
sum
+= num[i];
}
return sum;
}
-------------
Output
-------------
Result =
162.50
-------------------
C
Pointers:
Pointers
are useful aspects of C and C++ programming. Before we go into pointers, let's
talk about addresses in C programming.
Address in
C
If you
have a variable n in your program, &n will give you its address in the
memory.
We have
used address while using the scanf() function.
scanf("%d",
&n);
Here, the
value entered by the user is stored in the address of n variable. Let's take a working
example.
// Md. Farrukh
Asif
#include
<stdio.h>
int main()
{
int n = 5;
printf("var: %d\n", n);
// Notice the use of & before n
printf("address of var: %p",
&n);
return 0; }
-------------
Output
------------
n: 5
address of
n: 2686778
------------------------------
C Pointers
Pointers
(pointer variables) are special variables that are used to store addresses
rather than values.
Pointer
Syntax:
Here is
how we can declare pointers.
int* x;
Here, we
have declared a pointer x of int type.
You can
also declare pointers in these ways.
int *x1;
int * x2;
Let's take
another example of declaring pointers.
int* x1, x2;
Here, we
have declared a pointer x1 and a normal variable x2.
Assigning
addresses to Pointers:
Let's take
an example.
int* pc, c;
c = 5;
pc =
&c;
Here, 5 is
assigned to the c variable. And, the address of c is assigned to the pc
pointer.
Get Value
of Thing Pointed by Pointers
To get the
value of the thing pointed by the pointers, we use the * operator. For example:
int* pc,
c;
c = 5;
pc =
&c;
printf("%d",
*pc); // Output: 5
--------------
Example:
Working of Pointers
Let's take
a working example.
// Use of
Pointers
#include
<stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n",
&c);
printf("Value of c: %d\n\n",
c); // 22
pc = &c;
printf("Address of pointer pc:
%p\n", pc);
printf("Content of pointer pc:
%d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc:
%p\n", pc);
printf("Content of pointer pc:
%d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n",
&c);
printf("Value of c: %d\n\n", c);
// 2
return 0; }
-------------------
Output
-------------------
Address of
c: 2686784
Value of
c: 22
Address of
pointer pc: 2686784
Content of
pointer pc: 22
Address of
pointer pc: 2686784
Content of
pointer pc: 11
Address of
c: 2686784
Value of
c: 2
-------------------
Relationship
Between Arrays and Pointers:
Before you
learn about the relationship between arrays and pointers, be sure to check
these two topics:
An array
is a block of sequential data.
Let's
write a program to print addresses of array elements.
// Address
of an Array
#include
<stdio.h>
int main()
{
int x[4];
int i;
for(i = 0;
i < 4; ++i) {
printf("&x[%d] = %p\n", i,
&x[i]);
}
printf("Address of array x: %p",
x);
return 0;
}
---------------
Output
---------------
&x[0]
= 1450734448
&x[1]
= 1450734452
&x[2]
= 1450734456
&x[3]
= 1450734460
Address of
array x: 1450734448
---------------
There is a
difference of 4 bytes between two consecutive elements of array x. It is
because the size of int is 4 bytes (on our compiler).
Notice
that, the address of &x[0] and x is the same. It's because the variable
name x points to the first element of the array.
From the
above example, it is clear that &x[0] is equivalent to x. And, x[0] is
equivalent to *x.
Similarly,
&x[1]
is equivalent to x+1 and x[1] is equivalent to *(x+1).
&x[2]
is equivalent to x+2 and x[2] is equivalent to *(x+2).
Basically, &x[i] is equivalent to x+i and
x[i] is equivalent to *(x+i).
Example 1:
Pointers and Arrays
#include
<stdio.h>
int main()
{
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i) {
// Equivalent to scanf("%d",
&x[i]);
scanf("%d", x+i);
// Equivalent to sum += x[i]
sum += *(x+i);
}
printf("Sum = %d", sum);
return 0;
}
--------------------------------------------------------------
When you
run the program, the output will be:
--------------------------------------------------------------
Enter 6
numbers: 2
3
4
4
12
4
Sum = 29
--------------------------------------------------------------
Example 2:
Arrays and Pointers
#include
<stdio.h>
int main()
{
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
// ptr is assigned the address of the third
element
ptr = &x[2];
printf("*ptr = %d \n", *ptr); // 3
printf("*(ptr+1) = %d \n",
*(ptr+1)); // 4
printf("*(ptr-1) = %d",
*(ptr-1)); // 2
return 0;
}
--------------------------------------------------------------
When you
run the program, the output will be:
--------------------------------------------------------------
*ptr = 3
*(ptr+1) =
4
*(ptr-1) =
2
--------------------------------------------------------------
C Pass
Addresses and Pointers:
In C
programming, it is also possible to pass addresses as arguments to functions.
To accept
these addresses in the function definition, we can use pointers. It's because
pointers are used to store addresses. Let's take an example:
Example:
Pass Addresses to Functions
#include
<stdio.h>
void
swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed
swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2 = %d", num2);
return 0;
}
void
swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
--------------------------------------------------------------
When you
run the program, the output will be:
--------------------------------------------------------------
num1 = 10
num2 = 5
--------------------------------------------------------------
Example:
Passing Pointers to Functions
#include
<stdio.h>
void
addOne(int* ptr) {
(*ptr)++; // adding 1 to *ptr
}
int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
return 0;
}
--------------------------------------------------------------
C Dynamic
Memory Allocation:
As you
know, “an array is a collection of a fixed number of values. Once the size of
an array is declared, you cannot change it”.
Sometimes
the size of the array you declared may be insufficient. To solve this issue,
you can allocate memory manually during run-time. This is known as dynamic
memory allocation in C programming.
To
allocate memory dynamically, library functions are malloc(), calloc(),
realloc() and free() are used. These functions are defined in the
<stdlib.h> header file.
C malloc()
The name
"malloc" stands for memory allocation.
The
malloc() function reserves a block of memory of the specified number of bytes.
And, it returns a pointer of void which can be casted into pointers of any
form.
Syntax of
malloc()
ptr =
(castType*) malloc(size);
Example:
ptr =
(float*) malloc(100 * sizeof(float));
The above
statement allocates 400 bytes of memory. It's because the size of float is 4
bytes. And, the pointer ptr holds the address of the first byte in the
allocated memory.
The
expression results in a NULL pointer if the memory cannot be allocated.
C calloc()
The name
"calloc" stands for contiguous allocation.
The
malloc() function allocates memory and leaves the memory uninitialized, whereas
the calloc() function allocates memory and initializes all bits to zero.
Syntax of
calloc()
ptr =
(castType*)calloc(n, size);
Example:
ptr =
(float*) calloc(25, sizeof(float));
The above
statement allocates contiguous space in memory for 25 elements of type float.
C free()
Dynamically
allocated memory created with either calloc() or malloc() doesn't get freed on
their own. You must explicitly use free() to release the space.
Syntax of
free()
free(ptr);
This
statement frees the space allocated in the memory pointed by ptr.
-----------------
Example 1:
malloc() and free()
// 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 memory cannot be allocated
if(ptr == NULL) {
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;
}
---------------
Output
---------------
Enter
number of elements: 3
Enter
elements: 100
20
36
Sum = 156
Here, we
have dynamically allocated the memory for n number of int.
-----------------
Example 2:
calloc() and free()
// 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*) calloc(n, sizeof(int));
if(ptr == NULL) {
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);
free(ptr);
return 0;
}
---------------
Output
---------------
Enter
number of elements: 3
Enter
elements: 100
20
36
Sum = 156
C
realloc()
If the
dynamically allocated memory is insufficient or more than required, you can
change the size of previously allocated memory using the realloc() function.
Syntax of
realloc()
ptr =
realloc(ptr, x);
Here, ptr
is reallocated with a new size x.
Example 3:
realloc()
#include
<stdio.h>
#include
<stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously
allocated memory:\n");
for(i = 0; i < n1; ++i)
printf("%pc\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated
memory:\n");
for(i = 0; i < n2; ++i)
printf("%pc\n", ptr + i);
free(ptr);
return 0;
}
-----------------
Output
-----------------
Enter
size: 2
Addresses
of previously allocated memory:
26855472
26855476
Enter the
new size: 4
Addresses
of newly allocated memory:
26855472
26855476
26855480
26855484
------------------
Example:
Largest Element in an array
#include
<stdio.h>
int main()
{
int n;
double arr[100];
printf("Enter the number of elements (1
to 100): ");
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
printf("Enter number%d: ", i +
1);
scanf("%lf", &arr[i]);
}
// storing the largest number to arr[0]
for (int i = 1; i < n; ++i) {
if (arr[0] < arr[i]) {
arr[0] = arr[i];
}
}
printf("Largest element = %.2lf",
arr[0]);
return 0;
}
-----------------
Output
-----------------
Enter the
number of elements (1 to 100): 5
Enter
number1: 34.5
Enter
number2: 2.4
Enter
number3: -35.5
Enter
number4: 38.7
Enter
number5: 24.5
Largest
element = 38.70
----------------
Example:
Population Standard Deviation
// SD of a
population
#include
<math.h>
#include
<stdio.h>
float
calculateSD(float data[]);
int main()
{
int i;
float data[10];
printf("Enter 10 elements: ");
for (i = 0; i < 10; ++i)
scanf("%f", &data[i]);
printf("\nStandard Deviation =
%.6f", calculateSD(data));
return 0;
}
float
calculateSD(float data[]) {
float sum = 0.0, mean, SD = 0.0;
int i;
for (i = 0; i < 10; ++i) {
sum += data[i];
}
mean = sum / 10;
for (i = 0; i < 10; ++i) {
SD += pow(data[i] - mean, 2);
}
return sqrt(SD / 10);
}
-----------------
Output
-----------------
Enter 10
elements: 1
2
3
4
5
6
7
8
9
10
Standard
Deviation = 2.872281
------------------
Multiply
Matrices by Passing it to a Function
#include
<stdio.h>
//
function to get matrix elements entered by the user
void
getMatrixElements(int matrix[][10], int row, int column) {
printf("\nEnter elements: \n");
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
printf("Enter a%d%d: ", i +
1, j + 1);
scanf("%d",
&matrix[i][j]);
}
}
}
//
function to multiply two matrices
void
multiplyMatrices(int first[][10],
int second[][10],
int result[][10],
int r1, int c1, int r2,
int c2) {
// Initializing elements of matrix mult to
0.
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
result[i][j] = 0;
}
}
// Multiplying first and second matrices and
storing it in result
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
for (int k = 0; k < c1; ++k) {
result[i][j] += first[i][k] *
second[k][j];
}
}
}
}
//
function to display the matrix
void
display(int result[][10], int row, int column) {
printf("\nOutput Matrix:\n");
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
printf("%d ", result[i][j]);
if (j == column - 1)
printf("\n");
}
}
}
int main()
{
int first[10][10], second[10][10],
result[10][10], r1, c1, r2, c2;
printf("Enter rows and column for the
first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for the
second matrix: ");
scanf("%d %d", &r2, &c2);
// Taking input until
// 1st matrix columns is not equal to 2nd
matrix row
while (c1 != r2) {
printf("Error! Enter rows and
columns again.\n");
printf("Enter rows and columns for
the first matrix: ");
scanf("%d%d", &r1,
&c1);
printf("Enter rows and columns for
the second matrix: ");
scanf("%d%d", &r2,
&c2);
}
// get elements of the first matrix
getMatrixElements(first, r1, c1);
// get elements of the second matrix
getMatrixElements(second, r2, c2);
// multiply two matrices.
multiplyMatrices(first, second, result, r1,
c1, r2, c2);
// display the result
display(result, r1, c2);
return 0;
}
-----------------
Output
-----------------
Enter rows
and column for the first matrix: 2
3
Enter rows
and column for the second matrix: 3
2
Enter
elements:
Enter a11:
2
Enter a12:
-3
Enter a13:
4
Enter a21:
53
Enter a22:
3
Enter a23:
5
Enter
elements:
Enter a11:
3
Enter a12:
3
Enter a21:
5
Enter a22:
0
Enter a31:
-3
Enter a32:
4
Output
Matrix:
-21 22
159 179
------------------
Program to
Find the Transpose of a Matrix
#include
<stdio.h>
int main()
{
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
// asssigning elements to the matrix
printf("\nEnter matrix
elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i
+ 1, j + 1);
scanf("%d", &a[i][j]);
}
// printing the matrix a[][]
printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}
// computing the transpose
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}
// printing the transpose
printf("\nTranspose of the
matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}
Run The Code
Output
Enter rows
and columns: 2
3
Enter
matrix elements:
Enter
element a11: 1
Enter
element a12: 4
Enter
element a13: 0
Enter
element a21: -5
Enter
element a22: 2
Enter
element a23: 7
Entered
matrix:
1 4 0
-5 2 7
Transpose
of the matrix:
1 -5
4 2
0 7
----------
*** See You Again ***
************************
Share and Subscribe with Like
************************
No comments:
Post a Comment