C Programming Ndii
C Programming Ndii
PRODUCTION TECHNOLOGY
LEARNING MANUAL
FOR
PREPARED
BY
ESUOA F.B
Week 1 & week 2
Introduction
What is C
Why Learn C
Difference between C and C++
Keywords and Identifier
Variables and Constants
C Data Types
C Input & Output
C Comments
C Operators
C Questions and Solution
Week 3 & week 4
C Flow Control
C if...else
C for Loop
C while Loop
C break and continue
C switch...case
C Programming goto
Control Flow Examples
Week 5 & week 6
C FUNCTIONS
C Programming Functions
C User-defined Functions
C Function Types
C Recursion
C Storage Class
C Function Examples
Week 7 & week 8
C Programming Arrays
C Programming Arrays
C Multi-dimensional Arrays
C Arrays & Function
Week 9 & week 10
C Programming Pointers
C Programming Pointers
C Pointers & Arrays
C Pointers And Functions
C Memory Allocation
Array & Pointer Examples
Week 11 & week 12
C Programming Strings
C Programming String
C String Functions
C String Examples
Week 13
Structure And Union
C Structure
C Struct & Pointers
C Struct & Function
C Unions
C struct Examples
Week 14
C Programming Files
C Files Input/Output
C Files Examples
What is C?
It is a very popular language, despite being old. The main reason for its popularity is
because it is a fundamental language in the field of computer science.
Our C tutorials will guide you to learn C programming one step at a time.
C is strongly associated with UNIX, as it was developed to write the UNIX operating
system.
Why Learn C?
C++ was developed as an extension of C, and both languages have almost the same
syntax
The main difference between C and C++ is that C++ support classes and objects,
while C does not
A character set is a set of alphabets, letters and some special characters that are valid
in C language.
Alphabets
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
0123456789
Special Characters
Blank space, newline, horizontal tab, carriage return and form feed.
C Keywords
Keywords are predefined, reserved words used in programming that have special
meanings to the compiler. Keywords are part of the syntax and they cannot be used as
an identifier. For example:
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
C Keywords
auto , double , int ,struct , break , else , long
switch , case , enum ,register , typedef , char
extern , return , union , continue , for , signed
void, do , if , static ,while , default , goto
sizeof, volatile ,const ,float, short
unsigned
All these keywords, their syntax, and application will be discussed in their respective
topics.
C Identifiers
Identifier refers to name given to entities such as variables, functions, structures etc.
Identifiers must be unique. They are created to give a unique name to an entity to
identify it during the execution of the program. For example:
int money;
double accountBalance;
Also remember, identifier names must be different from keywords. You cannot use int
as an identifier because int is a keyword.
Rules for naming identifiers
A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
The first letter of an identifier should be either a letter or an underscore.
You cannot use keywords like int, while etc. as identifiers.
There is no rule on how long an identifier can be. However, you may run into
problems in some compilers if the identifier is longer than 31 characters.
You can choose any name as an identifier if you follow the above rule, however, give
meaningful names to identifiers that make sense.
Here, playerScore is a variable o f int type. Here, the variable is assigned an integer
value 95.
char ch = 'a';
// some code
ch = 'l';
1 A variable name can only have letters (both uppercase and lowercase letters),
digits and underscore.
2. The first letter of a variable should be either a letter or an underscore.
3. There is no rule on how long a variable name (identifier) can be. However,
you may run into problems in some compilers if the variable name is longer than 31
characters.
Note: You should always try to give meaningful names to variables. For example:
firstName is a better variable name than fn.
C is a strongly typed language. This means that the variable type cannot be changed
once it is declared. For example:
Here, the type of number variable is int. You cannot assign a floating-point (decimal)
value 5.5 to this variable. Also, you cannot redefine the data type of the variable to
double. By the way, to store the decimal values in C, you need to declare its type to
either double or float.
Literals
Literals are data used for representing fixed values. They can be used directly in the
code. For example: 1, 2.5, 'c' etc.
Here, 1, 2.5 and 'c' are literals. Why? You cannot assign different values to these
terms.
1. Integers
For example:
2. Floating-point Literals
-2.0
0.0000234
-0.22E-5
3. Characters
4. Escape Sequences
5. String Literals
Constants
If you want to define a variable whose value cannot be changed, you can use the const
keyword. This will create a constant. For example,
C DATA TYPES
In C programming, data types are declarations for variables. This determines the type
and size of data associated with variables. For example,
int myVar;
Here, myVar is a variable of int (integer) type. The size of int is 4 bytes.
Basic types
Here's a table containing commonly used types in C programming for quick access.
Type Size (bytes) Format Specifier
int at least 2, usually 4 %d, %i
char 1 %c
float 4 %f
double 8 %lf
short int 2 usually %hd
unsigned int at least 2, usually 4 %u
long int at least 4, usually 8 %ld, %li
long long int at least 8 %lld, %lli
unsigned long int at least 4 %lu
unsigned long long int at least 8 %llu
signed char 1 %c
unsigned char 1 %c
long double at least 10, usually 12 or 16 %Lf
int
Integers are whole numbers that can have both zero, positive and negative values but
no decimal values. For example, 0, -5, 10
int id;
The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -
2147483648 to 2147483647.
float and double
float salary;
double price;
The size of float (single precision float data type) is 4 bytes. And the size of double
(double precision float data type) is 8 bytes.
char
Keyword char is used for declaring character type variables. For example,
void is an incomplete type. It means "nothing" or "no type". You can think of void as
absent.
For example, if a function is not returning anything, its return type should be void.
Note that, you cannot create variables of void type.
short and long
If you need to use a large number, you can use a type specifier long. Here's how:
long a;
long long b;
long double c;
Here variables a and b can store integer values. And, c can store a floating-point
number.
If you are sure, only a small integer ([−32,767, +32,767] range) will be used, you can
use short.
short d;
You can always check the size of a variable using the sizeof() operator.
signed and unsigned
In C, signed and unsigned are type modifiers. You can alter the data storage of a data
type by using them:
For example,
// valid codes
unsigned int x = 35;
int y = -35; // signed int
int z = 36; // signed int
Here, the variables x and num can hold only zero and positive values because we have
used the unsigned modifier.
Considering the size of int is 4 bytes, variable y can hold values from -231 to 231-1,
whereas variable x can hold values from 0 to 232-1.
In C programming, printf() is one of the main output function. The function sends
formatted output to the screen. For example,
Example 1: C Output
How does this program work?
All valid C programs must contain the main() function. The code execution begins
from the start of the main() function.
The printf() is a library function to send formatted output to the screen. The
function prints the string inside quotations.
To use printf() in our program, we need to include stdio.h header file using the
#include <stdio.h> statement.
The return 0; statement inside the main() function is the "Exit status" of the
program. It's optional.
To print float, we use %f format specifier. Similarly, we use %lf to print double
values
Example : Print Characters
C Input
In C programming, scanf() is one of the commonly used function to take input from
the user. The scanf() function reads formatted input from the standard input such as
keyboards.
Notice, that we have used &testInteger inside scanf(). It is because &testInteger gets
the address of testInteger, and the value entered by the user is stored in that address.
When a character is entered by the user in the above program, the character itself is
not stored. Instead, an integer value (ASCII value) is stored.
And when we display that value using %c text format, the entered character is
displayed. If we use %d to display the character, it's ASCII value is printed.
Here's how you can take multiple inputs from the user and display them.
Format Specifiers for I/O
%d for int
%f for float
%lf for double
%c for char
Here's a list of commonly used C data types and their format specifiers.
Data Type Format Specifier
int %d
char %c
float %f
double %lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned long int %lu
unsigned long long int %llu
signed char %c
unsigned char %c
long double %Lf
C COMMENTS
In programming, comments are hints that a programmer can add to make their code
easier to read and understand. For example,
1. Single-line Comments in C
In C, a single line comment starts with //. It starts and ends in the same line. For
example,
In the above example, // create integer variable and // print the age variable are two
single line comments.
We can also use the single line comment along with the code. For example,
Here, code before // are executed and code after // are ignored by the compiler.
2. Multi-line Comments in C
Use of Comments in C
If we write comments on our code, it will be easier to understand the code in the
future. Otherwise you will end up spending a lot of time looking at our own code and
trying to understand it.
Comments are even more important if you are working in a group. It makes it easier
for other developers to understand and use your code.
While debugging there might be situations where we don't want some part of the
code. For example,
In the program below, suppose we don't need data related to height. So, instead of
removing the code related to height, we can simply convert them into comments.
Now later on, if we need height again, all you need to do is remove the forward
slashes. And, they will now become statements not comments.
Note: Comments are not and should not be used as a substitute to explain poorly
written code. Always try to write clean, understandable code, and then use comments
as an addition.
In most cases, always use comments to explain 'why' rather than 'how' and you are
good to go.
C PROGRAMMING OPERATORS
An operator is a symbol that operates on a value or a variable. For example: + is an
operator to perform addition.
It is because both the variables a and b are integers. Hence, the output is also an
integer. The compiler neglects the term after the decimal point and shows answer 2
instead of 2.25.
The modulo operator % computes the remainder. When a=9 is divided by b=4, the
remainder is 1. The % operator can only be used with integers.
C programming has two operators increment ++ and decrement -- to change the value
of an operand (constant or variable) by 1.
An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =
C Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon
whether expression results true or false. Logical operators are commonly used in
decision making in C programming.
Operator Meaning Example
C Bitwise Operators
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof is a unary operator that returns the size of data (constants, variables, array,
structure, etc).
Example : sizeof Operator
CLASS WORK,ASSIGNMENT AND PRACTICE QUESTIONS
Explanation:
How "Hello, World!" program works?
The #include is a preprocessor command that tells the compiler to include the
contents of stdio.h (standard input and output) file in the program.
The stdio.h file contains functions such as scanf() and printf() to take input and
display output respectively.
If you use the printf() function without writing #include <stdio.h>, the program will
not compile.
The execution of a C program starts from the main() function.
printf() is a library function to send formatted output to the screen. In this program,
printf() displays Hello, World! text on the screen.
#include <stdio.h>
int main() {
int number;
// displays output
printf("You entered: %d", number);
return 0;
}
#include <stdio.h>
int main() {
#include <stdio.h>
int main() {
double a, b, product;
printf("Enter two numbers: ");
scanf("%lf %lf", &a, &b);
// Calculating product
product = a * b;
return 0;
}
#include <stdio.h>
int main() {
char c;
printf("Enter a character: ");
scanf("%c", &c);
return 0;
}
#include <stdio.h>
int main() {
int dividend, divisor, quotient, remainder;
printf("Enter dividend: ");
scanf("%d", ÷nd);
printf("Enter divisor: ");
scanf("%d", &divisor);
// Computes quotient
quotient = dividend / divisor;
// Computes remainder
remainder = dividend % divisor;
#include<stdio.h>
int main() {
int intType;
float floatType;
double doubleType;
char charType;
return 0;
}
#include <stdio.h>
int main() {
int a;
long b; // equivalent to long int b;
long long c; // equivalent to long long int c;
double e;
long double f;
return 0;
}
C IF...ELSE STATEMENT
C if Statement
if (test expression)
{
// code
}
The if statement evaluates the test expression inside the parenthesis ().
If the test expression is evaluated to true, statements inside the body of if are
executed.
If the test expression is evaluated to false, statements inside the body of if are not
executed.
When the user enters -2, the test expression number<0 is evaluated to true. Hence,
You entered -2 is displayed on the screen.
When the user enters 5, the test expression number<0 is evaluated to false and the
statement inside the body of if is not executed
C IF...ELSE STATEMENT
The if statement may have an optional else block. The syntax of the if..else
statement is:
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
How if...else statement works?
When the user enters 50, the test expression number%2==0 is evaluated to true.
Hence, the statement inside the body of else is executed.
C if...else Ladder
The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2
possibilities.
The if...else ladder allows you to check between multiple test expressions and execute
different statements.
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
This program given below relates two integers using either <, > and = similar to the
if...else ladder's example. However, we will use a nested if...else statement to solve
this problem.
If the body of an if...else statement has only one statement, you do not need to use
brackets {}.
if (a > b) {
printf("Hello");
}
printf("Hi");
is equivalent to
if (a > b)
printf("Hello");
printf("Hi");
C for Loop
In programming, a loop is used to repeat a block of code until the specified condition
is met.
for loop
while loop
do...while loop
We will learn about for loop in this tutorial. In the next tutorial, we will learn about
while and do...while loop.
for Loop
This process goes on until the test expression is false. When the test expression is
false, the loop terminates.
The value entered by the user is stored in the variable num. Suppose, the user entered
10.
The count is initialized to 1 and the test expression is evaluated. Since the test
expression count<=num (1 less than or equal to 10) is true, the body of for loop is
executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2. Again, the
test expression is evaluated. Since 2 is also less than 10, the test expression is
evaluated to true and the body of the for loop is executed. Now, sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false), and the loop
terminates.
In programming, loops are used to repeat a block of code until a specified condition is
met.
for loop
while loop
do...while loop
In the previous tutorial, we learned about for loop. In this tutorial, we will learn about
while and do..while loop.
while loop
while (testExpression) {
// the body of the loop
}
The while loop evaluates the testExpression inside the parentheses ().
If testExpression is true, statements inside the body of while loop are executed.
Then, testExpression is evaluated again.
The process goes on until testExpression is evaluated to false.
If testExpression is false, the loop terminates (ends).
Here, we have initialized i to 1.
When i = 1, the test expression i <= 5 is true. Hence, the body of the while loop is
executed. This prints 1 on the screen and the value of i is increased to 2.
Now, i = 2, the test expression i <= 5 is again true. The body of the while loop is
executed again. This prints 2 on the screen and the value of i is increased to 3.
This process goes on until i becomes 6. Then, the test expression i <= 5 will be
false and the loop terminates.
do...while loop
The do..while loop is similar to the while loop with one important difference. The
body of do...while loop is executed at least once. Only then, the test expression is
evaluated.
do {
// the body of the loop
}
while (testExpression);
The body of do...while loop is executed once. Only then, the testExpression is
evaluated.
If testExpression is true, the body of the loop is executed again and testExpression
is evaluated once more.
This process goes on until testExpression becomes false.
If testExpression is false, the loop ends.
Here, we have used a do...while loop to prompt the user to enter a number. The loop
works as long as the input number is not 0.
The do...while loop executes at least once i.e. the first iteration runs without checking
the condition. The condition is checked only after the first iteration has been executed.
do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
So, if the first input is a non-zero number, that number is added to the sum variable
and the loop continues to the next iteration. This process is repeated until the user
enters 0.
But if the first input is 0, there will be no second iteration of the loop and sum
becomes 0.0.
The break statement ends the loop immediately when it is encountered. Its syntax is:
break;
The break statement is almost always used with if...else statement inside the loop.
This program calculates the sum of a maximum of 10 numbers. Why a maximum of
10 numbers? It's because if the user enters a negative number, the break statement is
executed. This will end the for loop, and the sum is displayed.
In C, break is also used with the switch statement. This will be discussed in the next
tutorial.
C continue
The continue statement skips the current iteration of the loop and continues with the
next iteration. Its syntax is:
continue;
The continue statement is almost always used with the if...else statement.
Example : continue statement
In this program, when the user enters a positive number, the sum is calculated using
sum += number; statement.
When the user enters a negative number, the continue statement is executed and it
skips the negative number from the calculation.
C SWITCH STATEMENT
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of the
switch statement is much easier to read and write.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
How does the switch statement work?
The expression is evaluated once and compared with the values of each case label.
If there is a match, the corresponding statements after the matching label are
executed. For example, if the value of the expression is equal to constant2, statements
after case constant2: are executed until break is encountered.
If there is no match, the default statements are executed.
Notes:
If we do not use the break statement, all statements after the matching label are also
executed.
The default clause inside the switch statement is optional.
Example: Simple Calculator
The + operator entered by the user is stored in the operation variable. And, two
operands 34 and 66 are stored in variables n1 and n2 respectively.
C GOTO STATEMENT
The goto statement allows us to transfer control of the program to the specified label.
Syntax of goto Statement
goto label;
... .. ...
... .. ...
label:
statement;
The label is an identifier. When the goto statement is encountered, the control of the
program jumps to label: and starts executing the code.
Example: goto Statement
The use of goto statement may lead to code that is buggy and hard to follow. For
example,
one:
for (i = 0; i < number; ++i)
{
test += i;
goto two;
}
two:
if (test > 5) {
goto three;
}
... .. ...
Also, the goto statement allows you to do bad stuff such as jump out of the scope.
That being said, goto can be useful sometimes. For example: to break from nested
loops.
Should you use goto?
If you think the use of goto statement simplifies your program, you can use it. That
being said, goto is rarely useful and you can create any C program without using goto
altogether.
In the program, the integer entered by the user is stored in the variable num.
Then, whether num is perfectly divisible by 2 or not is checked using the modulus %
operator.
The five letters A, E, I, O and U are called vowels. All other alphabets except these 5
vowels are called consonants.
This program assumes that the user will always enter an alphabet character.
Program to Check Vowel or consonant
The second and third if statements check if n2 and n3 are the largest, respectively.
The biggest drawback of this program is that all 3 if statements are executed,
regardless of which number is the largest.
A leap year is exactly divisible by 4 except for century years (years ending with 00).
The century year is a leap year only if it is perfectly divisible by 400.
For example,
Suppose, you need to create a program to create a circle and color it. You can create
two functions to solve this problem:
Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.
Types of function
The printf() is a standard library function to send formatted output to the screen
(display output on the screen). This function is defined in the stdio.h header file.
Hence, to use the printf() function, we need to include the stdio.h header file using
#include <stdio.h>.
The sqrt() function calculates the square root of a number. The function is defined
in the math.h header file.
User-defined function
You can also create functions as per your need. Such functions created by the user are
known as user-defined functions.
How user-defined function works?
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
void functionName()
The control of the program jumps back to the main() function once code inside the
function definition is executed.
And, the compiler starts executing the codes inside functionName().
The control of the program jumps back to the main() function once code inside the
function definition is executed.
This is just an overview of user-defined functions. Visit these pages to learn more on:
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:
createCircle() function
color() function
Here is an example to add two integers. To perform this task, we have created an user-
Example defined addNumbers().
Function prototype
A function prototype gives information to the compiler that the function may later be
used in the program.
Syntax of function prototype
In the above example, int addNumbers(int a, int b); is the function prototype which
provides the following information to the compiler:
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
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.
In programming, argument refers to the variable passed to the function. In the above
example, two variables n1 and n2 are passed during the function call.
The parameters a and b accepts the passed arguments in the function definition. These
arguments are called formal parameters of the function.
The type of arguments passed to a function and the formal parameters must match,
otherwise, the compiler will throw an error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also
should be of float type.
The return statement terminates the execution of a function and returns a value to the
calling function. The program control is transferred to the calling function after the
return statement.
In the above example, the value of the result variable is returned to the main function.
The sum variable in the main() function is assigned this value.
Syntax of return statement
return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function and the return type specified in the
function prototype and function definition must match.
The output of all these programs below is the same, and we have created a user-
defined function in each example. However, the approach we have taken in each
example is different.
Example: No Argument Passed and No Return Value
The checkPrimeNumber() function takes input from the user, checks whether it is a
prime number or not, and displays it on the screen.
The return type of the function is void. Hence, no value is returned from the function.
Here, the getInteger() function takes input from the user and returns it. The code to
check whether a number is prime or not is inside the main() function.
If the passed argument is a prime number, the function returns 0. If the passed
argument is a non-prime number, the function returns 1. The return value is
assigned to the flag variable.
Well, it depends on the problem you are trying to solve. In this case, passing an
argument and returning a value from the function (example 4) is better.
C Recursion
A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
How recursion works?
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
To prevent infinite recursion, if...else statement (or similar approach) can be used
where one branch makes the recursive call, and other doesn't.
Example: Sum of Natural Numbers Using Recursion
Initially, the sum() is called from the main() function with number passed as an
argument.
C Storage Class
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope,
visibility and lifetime of a variable.
There are 4 types of storage class:
automatic
external
static
register
Local Variable
The variables declared inside a block are automatic or local variables. The local
variables exist only inside the block in which it is declared.
When you run the above program, you will get an error undeclared identifier i. It's
because i is declared inside the for loop block. Outside of the block, it's undeclared.
int main() {
int n1; // n1 is a local variable to main()
}
void func() {
int n2; // n2 is a local variable to func()
}
This means you cannot access the n1 variable inside func() as it only exists inside
main(). Similarly, you cannot access the n2 variable inside main() as it only exists
inside func().
Global Variable
Variables that are declared outside of all functions are known as external or global
variables. They are accessible from any function inside the program.
Example : Global Variable
Suppose, a global variable is declared in file1. If you try to use that variable in a
different file file2, the compiler will complain. To solve this problem, keyword extern
is used in file2 to indicate that the external variable is declared in another file.
Register Variable
The register keyword is used to declare register variables. Register variables were
supposed to be faster than local variables.
However, modern compilers are very good at code optimization, and there is a rare
chance that using register variables will make your program faster.
Unless you are working on embedded systems where you know how to optimize code
for the given application, there is no use of register variables.
Static Variable
The value of a static variable persists until the end of the program.
Example : Static Variable
#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}
Output
6 11
During the first function call, the value of c is initialized to 1. Its value is increased by
5. Now, the value of c is 6, which is printed on the screen.
During the second function call, c is not initialized to 1 again. It's because c is a static
variable. The value c is increased by 5. Now, its value will be 11, which is printed on
the screen.
Solutions:
Prime Numbers Between Two Integers
2. Check Prime and Armstrong
Solution:
// FCAHPT ,COMPUTER TECH DEPT.SOFTWARE LABOURATORY
EXPERIMENT
// PREPARED BY ESUOLA
//Check Prime and Armstrong
#include <math.h>
#include <stdio.h>
int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d", &n);
In main(), the flag variable stores the values returned by checkPrimeNumber() and
checkArmstrongNumber().
C Arrays
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];
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.
Few keynotes:
Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4]
Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1]
will be 2124d. Similarly, the address of mark[2] will be 2128d and so on.
This is because the size of a float is 4 bytes.
Here, we haven't specified the size. However, the compiler knows its size is 5 as we
are initializing it with 5 elements.
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Here's how you can take input from the user and store it in an array element.
// take input and store it in the 3rd element
scanf("%d", &mark[2]);
int testArray[10];
Now let's say if you try to access testArray[12]. The element is not available. This
may cause unexpected output (undefined behavior). Sometimes you might get an error
and some other time your program may run correctly.
Hence, you should never access elements of an array outside of its bound.
Multidimensional arrays
In this tutorial, you learned about arrays. These arrays are called one-dimensional
arrays.
C Multidimensional Arrays
In C programming, you can create an array of arrays. These arrays are known as
multidimensional arrays. For example,
float x[3][4];
Here, x 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.
Similarly, you can declare a three-dimensional (3d) array. For example,
float y[2][4][3];
Initialization of a 3d array
You can initialize a three-dimensional array in a similar way to a two-dimensional
array. Here's an example,
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
In C programming, you can pass an entire array to functions. Before we learn that,
let's see how you can pass individual elements of an array to functions.
#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}
int main() {
int ageArray[] = {2, 8, 4, 12};
Output
8
4
Here, we have passed array parameters to the display() function in the same way
we pass variables to a function.
// pass second and third elements to display()
display(ageArray[1], ageArray[2]);
We can see this in the function definition, where the function parameters are
individual variables:
#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
return sum;
}
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an
argument.
result = calculateSum(num);
This informs the compiler that you are passing a one-dimensional array to the
function.
To pass multidimensional arrays to a function, only the name of the array is passed
to the function (similar to one-dimensional arrays).
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
return 0;
}
Run Code
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
Notice the parameter int num[2][2] in the function prototype and function
definition:
// function prototype
void displayNumbers(int num[2][2]);
For example,
Assignment
1) C Program to Reverse a Sentence Using Recursion
2) C program to calculate the power using recursion
3) C Program to Calculate Average Using Arrays
4) C Program to Find Largest Element in an Array
5) C Program to Calculate Standard Deviation
6) C Program to Add Two Matrices Using Multi-dimensional Arrays
7) C Program to Multiply Two Matrices Using Multi-dimensional Arrays
8) C Program to Find Transpose of a Matrix
9) C Program to Multiply two Matrices by Passing Matrix to a Function
10) C Program to Access Array Elements Using Pointer
11) C Program Swap Numbers in Cyclic Order Using Call by Reference
12) C Program to Find Largest Number Using Dynamic Memory Allocation
13) C Program to Find the Frequency of Characters in a String
14) C Program to Count the Number of Vowels, Consonants and so on
15) C Program to Remove all Characters in a String Except Alphabets
16) C Program to Find the Length of a String
17) C Program to Concatenate Two Strings
18) C Program to Copy String Without Using strcpy()
19) C Program to Sort Elements in Lexicographical Order (Dictionary Order)
20) C Program to Store Information of a Student Using Structure