Computer Programming: C For Statistics
Computer Programming: C For Statistics
Computer Programming: C For Statistics
Computer Programming
Computer programming is a process of formulating a computing problem to executable
computer programs. Programming involves activities such as analysis, generating algorithms
and implementation of algorithms in a target programming language.
Programming Language
A ‘Programming Language’ is a formal language that specifies a set of instructions that can
be used to produce various kinds of output. Programming languages generally consist of
instructions for a computer. Programming languages can be used to create programs that
implement specific algorithms.
Basically, programming languages can be divided into the following two categories
according to how the computer understands them.
1. Low-level language
2. High-level language
Low-level language
Low-level computer languages are either machine languages or languages very close them. A
computer cannot understand instructions given to it in high-level languages or in English. It
can only understand and execute instructions given in the form of machine language i.e.
binary (0 and 1). There are two types of low-level languages:
1. Machine Language
2. Assembly Language
Machine Language
Machine language is the lowest and most elementary level of programming language.
Machine language is basically the only language that a computer can understand. In fact, a
manufacturer designs a computer to obey just one language, its machine language, which is
represented inside the computer by a string of binary digits (bits) 0 and 1. The symbol 0
stands for the absence of an electric pulse and the 1 stands for the presence of an electric
pulse. Since a computer is capable of recognizing electric signals, it understands machine
language.
Advantages Disadvantages
1. Machine language makes fast and 1. All operation codes have to be
efficient use of the computer. remembered
2. It requires no translator to translate the
2. All memory addresses have to be
code. It is directly understood by the
remembered.
computer.
3. It is hard to find errors in a program
written in the machine language.
C for Statistics – ratulchakraborty@gmail.com
1
Assembly Language
Assembly language is a modified version of machine language in which instructions are
given in the form of alphanumeric symbols like ADD, SUM, MOV etc. instead of 0’s and l’s.
Because of this feature, assembly language is also known as ‘Symbolic Programming
Language.' This language is also very difficult and needs a lot of practice to master it because
there is only a little English support in this language. The instructions of the assembly
language are converted to machine codes by a language translator (known as ‘Assembler’)
and then they are executed by the computer.
Advantages Disadvantages
1. Assembly language is easier to understand 1. Like machine language, it is also machine
and use as compared to machine language. dependent/specific.
2. Since it is machine dependent, the
2. It is easy to locate and correct errors. programmer also needs to understand the
hardware.
3. It is easy to modify.
High-Level Language
High-level computer languages use formats that are similar to English. The purpose of
developing high-level languages was to enable people to write programs easily in their own
native language environment (English). High-level languages are basically symbolic
languages that use English words and mathematical symbols rather than alphanumeric
symbols. Each instruction in the high-level language is translated into many machine
language instructions by a high-level language translator (‘Compiler’ or ‘Interpreter’).
Advantages Disadvantages
1. A high-level language has to be translated
1. High-level languages are user-friendly. into the machine language by a translator,
which takes up time.
2. They are similar to English and use 2. The object code generated by a translator
English vocabulary and well-known might be inefficient compared to an
symbols. equivalent assembly language program.
3. They are easier to learn.
4. They are easier to maintain.
5. They are problem-oriented rather than
machine based.
6. A program written in a high-level
language can be translated into many
machine languages and can run on any
computer for which there exists an
appropriate Compiler / Interpreter.
Compiler
Compiler is a computer program that translates code written in a high-level programming
language (like C, C++, JavaScript or Java) into low-level code directly executable by the
computer or another program such as a virtual machine.
For example, the Java compiler converts Java code to Java Bytecode executable by the JVM
(Java Virtual Machine). Other examples are V8, the JavaScript engine from Google Chrome
which converts JavaScript code to machine code or GCC which can convert code written in
programming languages C and C++ to native machine code.
Interpreter
An interpreter is a special kind of program for the conversion of a high-level program
statement into machine code just before the program statement is to be executed. During each
conversion, the interpreter converts the source code into an intermediate code before
processing it into the machine for the generation of machine code. Each part of the code is
As interpreters check the source code line by line, translation and execution occurs
immediately one statement at a time. As a result, they are 2 to 10 times slower than
compilers. But this very disadvantage makes interpreters easier to user, especially for
beginners; errors once found are immediately displayed and corrected by the user, before the
program is executed.
C Language
C Programming is an ANSI/ISO standard and powerful programming language for
developing real time applications. C programming language was invented by Dennis Ritchie
at the Bell Laboratories in 1972. It was invented for implementing UNIX operating system. C
is most widely used programming language even today. C programming is considered as the
base for other programming languages, that is why it is known as mother language.
In the 1960s Ritchie worked, with several other employees of Bell Labs, on a project called
Multics. The goal of the project was to develop an operating system for a large computer that
could be used by a thousand users. In 1969 Bell Labs withdrew the project, because the
project could not produce an economically useful system. So the employees of Bell Labs had
to search for another project to work on (mainly Dennis M. Ritchie and Ken Thompson). At
that time a complete Operating System known as UNIX was born. The whole system was
written in assembly code. Besides Assembler and Fortran, UNIX also had an interpreter for
the programming language B which was developed in 1969-70 by Ken Thompson based on
BCPL (Basic Combined Programming Language).
In the early days computer code was written in assembly code. To perform a specific task,
one had to write many pages of code. A high-level language like B made it possible to write
the same task in just a few lines of code. So the language B was used for further development
of the UNIX system because of its efficient and faster coding techniques.
A drawback of the B language was the absence of data-types. The lack of this thing formed
the reason for Dennis M. Ritchie to develop the programming language C. So in 1971-73
Dennis M. Ritchie turned the B language into the C language, keeping most of the language B
syntax while adding data-types and many other changes. The C language had a powerful mix
of high-level functionality and the detailed features required to program an Operating
System. Therefore many of the UNIX components were eventually rewritten in C (the UNIX
kernel itself was rewritten in 1973).
The programming language C was written down, by Kernighan and Ritchie, in their classic
book “The C Programming Language, 1st edition”. For years this book was the standard on
the language C. In 1983 a committee was formed by the American National Standards
Institute (ANSI) to develop a modern definition for the programming language C. In 1988
they delivered the final standard definition ANSI C. (The standard was based on the book
from “The C Programming Language, 1st edition”). The standard ANSI C made little
changes on the original design of the C language. (They had to make sure that old programs
still worked with the new standard). Later on, the ANSI C standard was adopted by the
The source code written in text file is the human readable source for our program. It needs to
be "compiled" into machine language so that our CPU can actually execute the program as
per the instructions given. A compiler compiles the source codes into final executable
programs. A list of most frequently used C compilers are given below:
C Program Structure
A C program basically consists of the following parts:
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
Let us look at a simple code that would print the words "Hello, World":
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World");
return 0;
}
Basic Syntax
Almost every program we write on a computer has different type of format. That format is
called as Syntax. A syntax is a set of rules, principles, and processes that govern the structure
of a program in any given computer language.
printf("Hello, World");
Semicolons: In a C program, the semicolon is used to mark the end of a statement and
beginning of another statement. Absence of semicolon at the end of any statement will
mislead the compiler to think that this statement is not yet finished and it will add the
next consecutive statement after it, which may lead to compilation (syntax) error.
Comments: Comments are plain simple text in C programs that are not compiled by
the compiler. We write comments for better understanding of the program. Though
writing comments is not compulsory, but it is recommended to make our program
more descriptive. It makes the code more readable.
It should be noted that we cannot have comments within comments and they do not
occur within a string.
Keywords: Keywords are preserved words that have special meaning in C language.
The meaning of C language keywords has already been described to the C compiler.
These meaning cannot be changed. Thus, keywords cannot be used as variable names
because that would try to change the existing meaning of the keyword, which is not
allowed. There are total 32 keywords in C language.
Data Types in C
In C programming, variables and functions should be declared before it can be used. Each
variable and function in C has an associated data type. Data types simply refer to the type and
size of data associated with variables and functions. Different data types have different ranges
upto which they can store numbers. These ranges may vary from compiler to compiler.
Memory Format
Data Type Range Description
(in bytes) Specifier
The most basic data
type in C. It stores a
single character and
char 1 -128 to 127 %c
requires a single byte of
memory in almost all
compilers.
unsigned char 1 0 to 255 %c
short int 2 -32,768 to 32,767 %hd
unsigned short
2 0 to 65,535 %hu
int
-2,147,483,648 to As the name suggests,
int 4 2,147,483,647 %d an int variable is used to
ie. -(2^31) to (2^31)-1 store an integer.
unsigned int 4 0 to 4,294,967,295 %u
-2,147,483,648 to
long int 4 2,147,483,647 %ld
ie. -(2^31) to (2^31)-1
unsigned long 0 to 4,294,967,295
4 %lu
int ie. 0 to (2^32)-1
−9,223,372,036,854,775,807
to
long long int 8 %lld
9,223,372,036,854,775,807
ie. -(2^63) to (2^63)-1
0 to
unsigned long
8 18,446,744,073,709,551,615 %llu
long int
ie. 0 to (2^64)-1
%f, %g, It is used to store
float 4 1.18E-38 to 3.4E+38 %G, %e, decimal numbers with 6
%E digits of precision.
%lf, %lg, It is used to store
double 8 2.23E-308 to 1.79E+308 %lG, %le, decimal numbers with
%lE 15 digits of precision.
%Lf, %Lg, It is used to store
long double 12 3.4E-4932 to 1.1E+4932 %LG, %Le, decimal numbers with
%LE 18 digits of precision.
The void type specifies
that no value is
void available. This can be
used in functions and
pointers.
3. User defined data types: The user defined data types enable a programmer to invent
his own data types and define what values it can take on. C supports two types of user
defined data types:
Structures: A structure is a collection of variables, constants and arrays of
various data types. The main difference between an array and a structure is
that the members of a structure are of different types. This offers excellent
flexibility when working with structures. Now, consider the following
example:
#include <stdio.h>
int main()
{
student x;
return 0;
}
Here we define a structure named student with four variables name, age,
weight & height. In the main function we create a variable x of type student
and assign values to its all member variables.
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main()
{
union Data data;
data.i = 10;
data.f = 220.5;
return 0;
}
Output
Here, we can see that the values of data.i got corrupted after assigning values
to data.f. Similarly both the values of data.i and data.f got corrupted after the
assignment of string “C Programming” to data.str.
Structure Union
Keyword struct defines a structure. Keyword union defines a union.
When a variable is associated with a When a variable is associated with a union,
structure, the compiler allocates the the compiler allocates the memory by
memory for each member. The size considering the size of the largest memory.
of structure is greater than or equal to So, size of union is equal to size of largest
the sum of sizes of its members. member.
Each member within a structure is
Memory allocated is shared by individual
assigned unique storage area of
members of union.
location.
Altering the value of member will
Altering the value of any of the member will
not affect other members of the
alter other member values.
structure.
All member can be accessed at a
Only one member can be accessed at a time.
time.
Qualifiers in C
Qualifiers in C alters the meaning of base data types to yield a new data type. Different types
of qualifiers are as follows:
Size qualifiers: Size qualifiers alter the size of a basic data type. There are two size
qualifiers, long and short. For example:
1. long double x; Here size of double is 8 bytes. However, when long
keyword is used, that variable becomes 12 bytes.
2. short int x; Here size of int is 4 bytes. However, when short keyword is
used, that variable becomes 2 bytes.
Sign qualifiers: Integers and floating point variables can hold both negative and
positive values. However, if a variable needs to hold positive value only, unsigned
qualifier is used. For example: unsigned int x; There is another qualifier
signed which can hold both negative and positive value. However, it is not
necessary to define variable signed since a variable is signed by default. It is
important to note that, sign qualifiers can be applied to int and char types only.
Volatile qualifiers: A variable should be declared volatile whenever its value can
be changed by some external sources outside the program.
Operators in C
Example
#include <stdio.h>
int main()
{
int a = 10, b = 20;
float c = 3.6, d = 6.8;
return 0;
}
++a = 11
b++ = 20
b = 21
++c = 4.6
d++ = 6.8
d = 7.8
Other Operators
Decision making in C
Decision making is about deciding the order of execution of statements based on certain
conditions or repeat a group of statements until certain specified conditions are met. C
language handles decision-making by supporting the following statements:
if(expression)
{
statement-inside;
}
statement-outside;
if(expression)
{
statement-block-1;
}
else
{
statement-block-2;
}
if(expression)
{
if(expression1)
{
statement-block-1;
}
else
{
statement-block-2;
}
}
else
{
statement-block-3;
}
if(expression1)
{
statement-block-1;
}
C for Statistics – ratulchakraborty@gmail.com
16
else if(expression2)
{
statement-block-2;
}
else if(expression3 )
{
statement-block-3;
}
else
default-statement;
The expressions will be tested from the top (of the ladder) to downwards. As
soon as a true condition is found, the statement associated with it is executed.
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
goto label;
..
.
Labe_l: statement;
..
.
Here labe_l can be any plain text except C keyword and it can be set anywhere in the
C program above or below to goto statement.
Loops in C
We may encounter situations, when a block of code needs to be executed several number of
times. In C language a loop statement allows us to execute a statement or a group of
statements multiple times. Given below is the general form of a loop statement in C.
As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is
false then the execution breaks out of the loop. After the loop is successfully executed the
for loop: for loop executes a sequence of statements multiple times and abbreviates
the code. The syntax of for loop is:
A for loop is commonly used when the number of iterations is known. However we
can terminate a for loop with break statement for some terminating condition.
while(testExpression)
{
//codes
}
Here the while loop evaluates the testExpression. If the testExpression is true, codes
inside the body of while loop are exectued. The testExpression is evaluated again.
The process goes on until the testExpression is false. When the testExpression is false,
the while loop is terminated.
do
{
// codes
}
while(testExpression);
Functions in C
A function is a block of code that performs a particular task. There are many situations where
we might need to write same line of code for more than once in a program. This may lead to
unnecessary repetition of code, bugs and even becomes boring for the programmer. So, C
language provides an approach in which we can declare and define a group of statements
once in the form of a function and it can be called and used whenever required. Every C
program has at least one function, which is main().
Library functions: Library functions are those functions which are already defined in
C library. Example: printf(), scanf(), log(), sin() etc. We just need to
include appropriate header files and libraries to use these functions.
There are many library functions available in C programming for writing a good and
efficient program. But, why should we use it? Below are the 4 most important
advantages of using standard library functions.
1. One of the most important reasons you should use library functions is simply
because they work. These functions have gone through multiple rigorous
testing and are easy to use.
2. Since, the functions are "standard library" functions, a dedicated group of
developers constantly make them better. In the process, they are able to create
the most efficient code optimized for maximum performance.
3. Since the general functions like printing to a screen, calculating the square
root, and many more are already written. We shouldn't worry about creating
them once again. It saves valuable time and our code may not always be the
most efficient.
4. With ever changing real world needs, our application is expected to work
every time, everywhere. These library functions help us in that they do the
same thing on every computer. This saves time, effort and makes our program
portable.
Like any variable or an array, a function must also be declared before it’s used.
Function declaration informs the compiler about the function name, parameters, and
its return type. Functions should be declared in header files or before the definition of
main() function. The actual body of the functions can be defined separately after
main() function. General syntax for function declaration is,
The function body contains the declarations and the statements (algorithm) necessary
for performing the required task. The body is enclosed within curly braces { ... }
and consists of the following three parts.
Example
#include <stdio.h>
int main()
{
float max_val, min_val;
return 0;
}
return result;
}
return result;
}
Output
Calling a function
While creating a C function, we give a definition of what the function has to do. To use a
function, we have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main
program.
To call a function, we simply need to pass the required parameters along with the function
name, and if the function returns a value, then we can store the returned value.
Function Arguments
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:
1. Call by value: The call by value method of passing arguments to a function 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.
#include <stdio.h>
int main()
{
int x = 10, y = 20;
return 0;
}
temp = a;
a = b;
b = temp;
}
Output
The output shows that there are no changes in the values of x & y after using of
swap() function, though they had been changed inside the function.
To pass a value by reference, argument pointers are passed to the functions just like
any other value. So accordingly we need to declare the function parameters as pointer
types as in the following example of swap() function, which exchanges the values of
the two integer variables pointed to, by their arguments.
#include <stdio.h>
int main()
{
int x = 10, y = 20;
return 0;
}
temp = *a;
*a = *b;
*b = temp;
}
Output
The output shows that the values of x & y changes after calling of swap() function
by reference.
C for Statistics – ratulchakraborty@gmail.com
26
Recursion in C functions
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function; otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
#include <stdio.h>
int main()
{
printf("5! = %llu\n", factorial(5));
printf("10! = %llu\n", factorial(10));
printf("20! = %llu\n", factorial(20));
printf("40! = %llu\n", factorial(40));
return 0;
}
Output
5! = 120
10! = 3628800
20! = 2432902008176640000
40! = 18376134811363311616
#include <stdio.h>
int main()
{
printf("1+2+...+10 = %llu\n", natural_sum(10));
printf("1+2+...+100 = %llu\n", natural_sum(100));
printf("1+2+...+1000 = %llu\n", natural_sum(1000));
printf("1+2+...+10000 = %llu\n", natural_sum(10000));
return 0;
}
Output
1+2+...+10 = 55
1+2+...+100 = 5050
1+2+...+1000 = 500500
1+2+...+10000 = 50005000
3. Fibonacci Series.
#include <stdio.h>
int main()
{
int i;
Output
#include <stdio.h>
int main()
{
printf("Total digits in 12337: %d\n",
count_digits(12337));
printf("Total digits in 6: %d\n",
count_digits(6));
printf("Total digits in -980700: %d\n",
count_digits(-980700));
return 0;
}
temp = num/10;
if(temp == 0) return 1;
else return count_digits(temp) + 1;
}
5. Length of a string.
#include <stdio.h>
int main()
{
char *string1 = "MBB College";
char *string2 = "Agartala";
return 0;
}
Output
#include <stdio.h>
int main()
return 0;
}
return common;
}
Output
7. Highest Common Factor (HCF) / Greatest Common Divisor (GCD) of two numbers
#include <stdio.h>
int main()
{
printf("GCD/HCF of 15 & 20: %d\n", hcf(15, 20));
printf("GCD/HCF of 118 & 3: %d\n", hcf(118, 3));
return 0;
}
#include <stdio.h>
int main()
{
printf("Binary of 17: %llu\n", int2binary(17));
printf("Binary of 1107: %llu\n", int2binary(1107));
printf("Binary of 319: %llu\n", int2binary(319));
return 0;
}
Output
n
9. Binomial coefficient of two numbers ( Cx )
#include <stdio.h>
int main()
{
printf("5C2: %llu\n", ncx(5, 2));
printf("10C7: %llu\n", ncx(10, 7));
Output
5C2: 10
10C7: 120
#include <stdio.h>
int main()
{
int i, n;
float data[100];
sort(data, 0, n-1);
printf("\nSorted observations:");
for(i=0; i<n; i++) printf("\t%g", data[i]);
return 0;
}
do{
C for Statistics – ratulchakraborty@gmail.com
33
while (x[i] < middle) i++;
while (x[j] > middle) j--;
if (i <= j) {
t = x[i];
x[i] = x[j];
x[j] = t;
i++;
j--;
}
}while (i <= j);
if(start < j) sort(x,start,j);
if(i < end) sort(x,i,end);
}
Output
Total observations: 10
Insert observations: 3 17 -5 8 7 10 1 8 12 2
Sorted observations: -5 1 2 3 7 8 8 10 12 17
Recursion makes program elegant and cleaner. All algorithms can be defined recursively
which makes it easier to visualize and prove.
If the speed of the program is vital then, we should avoid using recursion. Recursions use
more memory and are generally slow. Instead, we can use loop.
Sometimes, we may come across a situation, when we want to have a function, which can
take variable number of arguments / parameters, instead of predefined number of parameters.
The C programming language provides a solution for this situation and we are allowed to
define a function which can accept variable number of parameters based on our requirement.
The following example shows the construction of such a function which can take the variable
number of parameters and return their sum.
#include <stdio.h>
#include <stdarg.h>
int main() {
printf("Sum of 2.3,3.5,4.6,5.0 = %g\n",
C for Statistics – ratulchakraborty@gmail.com
34
sum(4, 2.3,3.5,4.6,5.0));
printf("Sum of 5.6,10.9,15.1 = %g\n",
sum(3, 5.6,10.9,15.1));
return 0;
}
return sum;
}
Output
It should be noted that the function sum() has been called twice and each time the first
argument represents the total number of variable arguments being passed.
C - Scope Rules
A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that region it cannot be accessed. There are three places where
variables can be declared in C programming language:
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.
C for Statistics – ratulchakraborty@gmail.com
35
Global Variables
Global variables are defined outside a function, usually on top of the program. Global
variables hold their values throughout the lifetime of our program and they can be accessed
inside any of the functions defined for the program. The following program show how global
variables are used in a program.
#include <stdio.h>
void change_global(int);
int main()
{
printf("Value of x, y: %d, %d\n", x, y);
x = 20;
y = 400;
printf("Value of x, y: %d, %d\n", x, y);
change_global(30);
printf("Value of x, y: %d, %d\n", x, y);
return 0;
}
x = newx;
y = newx;
}
Output
Here we can see that a program can have same name (y) for local and global variables but the
value of local variable inside a function will take preference.
Formal parameters are treated as local variables with-in a function and they take precedence
over global variables.
When a local variable is defined, it is not initialized by the system; we must initialize it
before use. Global variables are initialized automatically by the system when we define them
as follows:
It is a good programming practice to initialize variables properly; otherwise our program may
produce unexpected results, because uninitialized variables will take some garbage value
already available at their memory location.
Arrays in C
Array in C language is a collection or group of elements (data). All the elements of C array
are homogeneous (similar). It has contiguous memory location.
C array is beneficial if we have to store similar elements. Suppose we have to store marks of
50 students, one way to do this is allotting 50 variables. So it will be typical and hard to
manage. We can’t access the value of these variables with only 1 or 2 lines of code. In this
case using array we can access these elements easily by defining a single variable. Only few
lines of code are required to access the elements of array.
1. One-dimensional arrays
2. Multidimensional arrays
A one-dimensional array is like a list; A two dimensional array is like a table; The C
language places no limits on the number of dimensions in an array. Some texts refer to one-
dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term
arrays when the number of dimensions is more than two.
Declaration of Array
To declare an array in C, we have to specify the type of the elements and the number of
elements required by an array as follows:
data_type array_name[array_size];
int marks[100];
Here, int is the data_type, marks is the array_name and 100 is the array_size.
Elements of an Array
We can access elements of an array by indices. Suppose we declared an array marks as above. The
first element is marks[0], second element is marks[1] and so on.
Example
Here will obtain the Mean Deviation about Mean of a data-set using array.
#include <stdio.h>
#include <math.h>
int main()
{
int i, n;
/*The one dimensional data array 'x' with a capacity 100 elements*/
float x[100];
float mean = 0, MD = 0;
printf("\nObservations: ");
for(i=0; i<n; i++){
scanf("%f", &x[i]);
C for Statistics – ratulchakraborty@gmail.com
38
mean += x[i];
}
mean = mean / n;
MD = MD / n;
return 0;
}
Output
Total observations: 5
Observations: 12 23 7 45 10
Advantage of Array
Disadvantage of Array
Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the
limit. So, it doesn't grow the size dynamically.
Now, consider the following example, where the average(..) function takes an array as an
argument along with another argument and based on the passed arguments, it returns the
average of the numbers passed through the array.
#include <stdio.h>
int main()
{
/*The one dimensional data array 5 elements*/
float data[5] = {10, 23, 37, 41, 50};
return 0;
}
avg = avg/n;
return avg;
}
Average = 32.2
C programming does not allow returning an entire array from a function. However, you can
return a pointer to an array by specifying the array's name without an index. While returning
an address of a local variable from a function, it should be remember that we have to define
the local variable as static variable.
Consider the following example where a function returns a pointer to an array of random
numbers.
#include <stdio.h>
int *rand_numbers();
main()
{
int i, *rnd;
rnd = rand_numbers();
return 0;
}
return r;
}
Output
10 random numbers: 9644 18684 1554 1009 11360 18594 32 3593 31637 4038
A Pointer in C language is a variable which holds the address of another variable of same
data type. Pointers are used in C program to access the memory and manipulate the address.
Pointers are one of the most distinct and exciting features of C and C++ programming
language that differentiates it from other popular programming languages like: Java and
Python. Before we start understanding what pointers are and what they can do, we have to
understand “Address of a memory location”.
Address in C
Whenever a variable is defined in C language, a memory location is assigned for it, in which
its value will be stored. We can easily check this memory address, using the & operator. If x
is the name of the variable, then &x will give it's address. Here & is known as reference
operator. In the scanf() function we use it to store the user inputted value of a variable in
the address of that variable like scanf(“%d”, &x);
Example
#include <stdio.h>
int main()
{
int x = 5;
return 0;
}
Output
Value: 5
Address: 2293572
In above source code, value 5 is stored in the memory location 2293572. x is just the name
given to that location. We may obtain different value of address while using this code.
https://www.studytonight.com/c/
https://www.tutorialspoint.com/cprogramming/index.htm
https://www.programiz.com/c-programming/c-data-types
https://fresh2refresh.com/c-programming/c-data-types/
https://www.javatpoint.com/data-types-in-c