Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views79 pages

C Programming Ndii

C programming for nd11

Uploaded by

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

C Programming Ndii

C programming for nd11

Uploaded by

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

FEDERAL COLLEGE OF ANIMA HEALTH AND

PRODUCTION TECHNOLOGY

COMPUTER TECHNOLOGY DEPARTMENT

SOFTWARE LABOURAORY PRACTICAL

LEARNING MANUAL

FOR

C PROGRAMMING COURSE ( COM 121 )

FOR NDII STUDENTS

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?

C is a general-purpose programming language created by Dennis Ritchie at the Bell


Laboratories in 1972.

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.

C is a powerful general-purpose programming language. It can be used to develop


software like operating systems, databases, compilers, and so on. C programming is
an excellent language to learn to program for beginners.

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?

It is one of the most popular programming languages in the world


If you know C, you will have no problem learning other popular programming
languages such as Java, Python, C++, C#, etc, as the syntax is similar
C is very fast, compared to other programming languages, like Java and Python
C is very versatile; it can be used in both applications and technologies

Difference between C and 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

C is a general-purpose programming language, developed in 1972, and still quite


popular.
C is very powerful; it has been used to develop operating systems, databases,
applications, etc.
Example

C Keywords and Identifiers


Character set

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

C accepts both lowercase and uppercase alphabets as variables and functions.


Digits

0123456789

Special Characters

Special Characters in C Programming

, , < ,> , ., _ ,( , ) , ; , $ ,: , % , [ , ] , # , ? , ' , & , { , } , " , ^ , ! , * , / , | , -, \ , ~ , + ,

White space 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).

As C is a case sensitive language, all keywords must be written in lowercase. Here is


a list of all keywords allowed in ANSI C.

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;

Here, money and accountBalance are identifiers.

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.

C VARIABLES, CONSTANTS AND LITERALS


VARIABLES

In programming, a variable is a container (storage area) to hold data.


To indicate the storage area, each variable should be given a unique name (identifier).
Variable names are just the symbolic representation of a memory location. For
example:

int playerScore = 95;

Here, playerScore is a variable o f int type. Here, the variable is assigned an integer
value 95.

The value of a variable can be changed, hence the name variable.

char ch = 'a';
// some code
ch = 'l';

Rules for naming a variable

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:

int number = 5; // integer variable


number = 5.5; // error
double number; // error

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

An integer is a numeric literal(associated with numbers) without any fractional or


exponential part. There are three types of integer literals in C programming:
decimal (base 10)
octal (base 8)
hexadecimal (base 16)

For example:

Decimal: 0, -9, 22 etc


Octal: 021, 077, 033 etc
Hexadecimal: 0x7f, 0x2a, 0x521 etc

In C programming, octal starts with a 0, and hexadecimal starts with a 0x.

2. Floating-point Literals

A floating-point literal is a numeric literal that has either a fractional form or an


exponent form. For example:

-2.0
0.0000234
-0.22E-5

Note: E-5 = 10-5

3. Characters

A character literal is created by enclosing a single character inside single quotation


marks. For example: 'a', 'm', 'F', '2', '}' etc.

4. Escape Sequences

Sometimes, it is necessary to use characters that cannot be typed or has special


meaning in C programming. For example: newline(enter), tab, question mark etc.

In order to use these characters, escape sequences are used.


Escape Sequences

Escape Sequences Character


\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
For example: \n is used for a newline. The backslash \ causes escape from the normal
way the characters are handled by the compiler.

5. String Literals

A string literal is a sequence of characters enclosed in double-quote marks. For


example:

"good" //string constant


"" //null string constant
" " //string constant of six white space
"x" //string constant having a single character.
"Earth is round\n" //prints string with a newline

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,

const double PI = 3.14;

Notice, we have added keyword const.

Here, PI is a symbolic constant; its value cannot be changed.

const double PI = 3.14;


PI = 2.9; //Error

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

We can use int for declaring an integer variable.

int id;

Here, id is a variable of type integer.

You can declare multiple variables at once in C programming. For example,

int id, age;

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 and double are used to hold real numbers.

float salary;
double price;

In C, floating-point numbers can also be represented in exponential. For example,

float normalizationFactor = 22.442e2;

What's the difference between float and double?

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,

char test = 'h';

The size of the character variable is 1 byte.


void

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:

signed - allows for storage of both positive and negative numbers


unsigned - allows for storage of only positive numbers

For example,

// valid codes
unsigned int x = 35;
int y = -35; // signed int
int z = 36; // signed int

// invalid code: unsigned int cannot hold negative integers


unsigned int num = -35;

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.

Derived Data Types


Data types that are derived from fundamental data types are derived types. For
example: arrays, pointers, function types, structures, etc.

C INPUT OUTPUT (I/O)


C Output

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.

Example : Integer Output


We use %d format specifier to print int types. Here, the %d inside the quotations will
be replaced by the value of testInteger.

Example : float and double Output

To print float, we use %f format specifier. Similarly, we use %lf to print double
values
Example : Print Characters

To print char, we use %c format specifier.

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.

Example : Integer Input/Output


Here, we have used %d format specifier inside the scanf() function to take int input
from the user. When the user enters an integer, it is stored in the testInteger variable.

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.

Example : Float and Double Input/Output


We use %f and %lf format specifier for float and double respectively.
Example : C Character I/O

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.

Example : ASCII Value


I/O Multiple Values

Here's how you can take multiple inputs from the user and display them.
Format Specifiers for I/O

As you can see from the above examples, we use

%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,

Here, // print Hello World to the screen is a comment in C programming. Comments


are completely ignored by C compilers.
Types of Comments

There are two ways to add comments in C:

// - Single Line Comment


/*...*/ - Multi-line Comment

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,

int age = 25; // create integer variable

Here, code before // are executed and code after // are ignored by the compiler.

2. Multi-line Comments in C

In C programming, there is another type of comment that allows us to comment on


multiple lines at once, they are multi-line comments.

To write multi-line comments, we use the /*....*/ symbol. For example,


In this type of comment, the C compiler ignores everything from /* to */.

Note: Remember the keyboard shortcut to use comments:

Single Line comment: ctrl + / (windows) and cmd + / (mac)


Multi line comment: ctrl + shift + / (windows) and cmd + shift + / (mac)

Use of Comments in C

1. Make Code Easier to Understand

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.

2. Using Comments for debugging

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.

C has a wide range of operators to perform various operations.


C Arithmetic Operators

An arithmetic operator performs mathematical operations such as addition,


subtraction, multiplication, division etc on numerical values (constants and variables).
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* multiplication
/ division
% remainder after division (modulo division)

Example : Arithmetic Operators

In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.

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.

Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,

// Either one of the operands is a floating-point number


a/b = 2.5
a/d = 2.5
c/b = 2.5

// Both operands are integers


c/d = 2

C Increment and Decrement Operators

C programming has two operators increment ++ and decrement -- to change the value
of an operand (constant or variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1.


These two operators are unary operators, meaning they only operate on a single
operand.
Example : Increment and Decrement Operators
Here, the operators ++ and -- are used as prefixes. These two operators can also be
used as postfixes like a++ and a--. Visit this page to learn more about how increment
and decrement operators work when used as postfix.
C Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =

Operator Example Same as


= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b

Example3: Assignment Operators


C Relational Operators

A relational operator checks the relationship between two operands. If the


relation is true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.

Operator Meaning of Operator Example


== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to
!= Not equal 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0

Example : Relational Operators

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

&& Logical AND. True If c = 5 and d = 2 then,


only if all operands are true expression ((c==5) &&
(d>5)) equals to 0.
|| Logical OR. True only If c = 5 and d = 2 then
if either one operand is true expression ((c==5) ||
(d>5)) equals to 1.
! Logical NOT. True If c = 5 then, expression !(c==5)
only if the operand is 0 equals to 0.

Example : Logical Operators

Explanation of logical operator program

(a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1


(true).
(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0
(false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1
(true).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

C Bitwise Operators

During computation, mathematical operations like: addition, subtraction,


multiplication, division, etc are converted to bit-level which makes processing faster
and saves power.
Bitwise operators are used in C programming to perform bit-level operations.

Operators Meaning of operators


& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right

Other Operators
Comma Operator

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

The sizeof operator

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

Write a C program to print a sentence


#include <stdio.h>
int main() {
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}

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.

Write a C program to print an integer entered by the user

#include <stdio.h>
int main() {
int number;

printf("Enter an integer: ");

// reads and stores input


scanf("%d", &number);

// displays output
printf("You entered: %d", number);

return 0;
}

Write a C program to add two integers entered by the User

#include <stdio.h>
int main() {

int number1, number2, sum;

printf("Enter two integers: ");


scanf("%d %d", &number1, &number2);

// calculate the sum


sum = number1 + number2;

printf("%d + %d = %d", number1, number2, sum);


return 0;
}
C program to multiply two floating-point numbers

#include <stdio.h>
int main() {
double a, b, product;
printf("Enter two numbers: ");
scanf("%lf %lf", &a, &b);

// Calculating product
product = a * b;

// %.2lf displays number up to 2 decimal point


printf("Product = %.2lf", product);

return 0;
}

C program to find ASCII value of a character entered by the user

#include <stdio.h>
int main() {
char c;
printf("Enter a character: ");
scanf("%c", &c);

// %d displays the integer value of a character


// %c displays the actual character
printf("ASCII value of %c = %d", c, c);

return 0;
}

C program to find quotient and remainder of Two Integers

#include <stdio.h>
int main() {
int dividend, divisor, quotient, remainder;
printf("Enter dividend: ");
scanf("%d", &dividend);
printf("Enter divisor: ");
scanf("%d", &divisor);

// Computes quotient
quotient = dividend / divisor;
// Computes remainder
remainder = dividend % divisor;

printf("Quotient = %d\n", quotient);


printf("Remainder = %d", remainder);
return 0;
}

C program to find the size of int, float, double and char

#include<stdio.h>
int main() {
int intType;
float floatType;
double doubleType;
char charType;

// sizeof evaluates the size of a variable


printf("Size of int: %zu bytes\n", sizeof(intType));
printf("Size of float: %zu bytes\n", sizeof(floatType));
printf("Size of double: %zu bytes\n", sizeof(doubleType));
printf("Size of char: %zu byte\n", sizeof(charType));

return 0;
}

C program to demonstrate the working of keyword long

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

printf("Size of int = %zu bytes \n", sizeof(a));


printf("Size of long int = %zu bytes\n", sizeof(b));
printf("Size of long long int = %zu bytes\n", sizeof(c));
printf("Size of double = %zu bytes\n", sizeof(e));
printf("Size of long double = %zu bytes\n", sizeof(f));

return 0;
}

C program to swap two numbers


#include<stdio.h>
int main() {
double first, second, temp;
printf("Enter first number: ");
scanf("%lf", &first);
printf("Enter second number: ");
scanf("%lf", &second);

// value of first is assigned to temp


temp = first;

// value of second is assigned to first


first = second;

// value of temp (initial value of first) is assigned to second


second = temp;

// %.2lf displays number up to 2 decimal points


printf("\nAfter swapping, first number = %.2lf\n", first);
printf("After swapping, second number = %.2lf", second);
return 0;
}

C IF...ELSE STATEMENT

C if Statement

The syntax of the if statement in C programming is:

if (test expression)
{
// code
}

How if statement works?

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?

If the test expression is evaluated to true,

statements inside the body of if are executed.


statements inside the body of else are skipped from execution.

If the test expression is evaluated to false,

statements inside the body of else are executed


statements inside the body of if are skipped from execution.

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.

Syntax of if...else Ladder

if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}

Example : C if...else Ladder


Nested if...else

It is possible to include an if...else statement inside the body of another if...else


statement.

Example : Nested if...else

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 {}.

For example this code

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.

C programming has three types of loops:

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

The syntax of the for loop is:

for (initializationStatement; testExpression; updateStatement)


{
// statements inside the body of loop
}

How for loop works?

The initialization statement is executed only once.


Then, the test expression is evaluated. If the test expression is evaluated to false,
the for loop is terminated.
However, if the test expression is evaluated to true, statements inside the body of
the for loop are executed, and the update expression is updated.
Again the test expression is evaluated.

This process goes on until the test expression is false. When the test expression is
false, the loop terminates.

Example: for loop

// Print numbers from 1 to 10#include <stdio.h>


int main() {
int i;

for (i = 1; i < 11; ++i)


{
printf("%d ", i);
}
return 0;
}
1. i is initialized to 1.
2. The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body
of for loop is executed. This will print the 1 (value of i) on the screen.
3. The update statement ++i is executed. Now, the value of i will be 2. Again,
the test expression is evaluated to true, and the body of for loop is executed.
This will print 2 (value of i) on the screen.
4. Again, the update statement ++i is executed and the test expression i < 11 is
evaluated. This process goes on until i becomes 11.
5. When i becomes 11, i < 11 will be false, and the for 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.

Then, the value of sum is printed on the screen

C WHILE AND DO...WHILE LOOP

In programming, loops are used to repeat a block of code until a specified condition is
met.

C programming has three types of loops.

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

The syntax of the while loop is:

while (testExpression) {
// the body of the loop
}

How while loop works?

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.

The syntax of the do...while loop is:

do {
// the body of the loop
}
while (testExpression);

How do...while loop works?

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.

Outside the loop, we print the value of sum.

C BREAK AND CONTINUE


C break

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.

Since the operation is -, the control of the program jumps to

printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

Finally, the break statement terminates the switch statement.

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.

Class Exercises and assignment


1. Write a C Program to Check Whether a Number is Even or Odd
Solution:
An even number is an integer that is exactly divisible by 2. For example: 0, 8, -24
An odd number is an integer that is not exactly divisible by 2. For example: 1, 7, -11,
15
Program to Check Even or Odd

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.

If the number is perfectly divisible by 2, test expression number%2 == 0 evaluates to


1 (true). This means the number is even.

However, if the test expression evaluates to 0 (false), the number is odd.


2. Write a C Program to Check Whether a Character is a Vowel or Consonant

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

3. Write a C Program to Find the Largest Number Among Three Numbers


Solution.
Using if Statement
Here, we have used 3 different if statements. The first one checks whether n1 is the
largest number.

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.

However, we want to execute only one if statement. We can do this by using an


if...else ladder.

Using if...else Ladder


4. Write a C Program to Check Leap Year

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,

1999 is not a leap year


2000 is a leap year
2004 is a leap year
Solution:
Program to Check Leap Year
C FUNCTIONS

A function is a block of code that performs a specific task.

Suppose, you need to create a program to create a circle and color it. You can create
two functions to solve this problem:

create a circle function


create a color function

Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.
Types of function

There are two types of function in C programming:

Standard library functions


User-defined functions

Standard library functions

The standard library functions are built-in functions in C programming.

These functions are defined in header files. For example,

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

... .. ...
... .. ...
}

The execution of a C program begins from the main() function.

When the compiler encounters functionName();, control of the program jumps to

void functionName()

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.
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.

Note, function names are identifiers and should be unique.

This is just an overview of user-defined functions. Visit these pages to learn more on:

User-defined Function in C programming


Types of user-defined Functions

Advantages of user-defined function

The program will be easier to understand, maintain and debug.


Reusable codes that can be used in other programs
A large program can be divided into smaller modules. Hence, a large project can be
divided among many programmers.
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:

createCircle() function
color() function

Example: User-defined 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 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 addNumbers(int a, int b); is the function prototype which
provides the following information to the compiler:

name of the function is addNumbers()


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.

Passing arguments to 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.

A function can also be called without passing an argument.


Return Statement

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.

Types of User-defined Functions in C Programming


These 4 programs below check whether the integer entered by the user is a prime
number or not.

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 empty parentheses in checkPrimeNumber(); inside the main() function indicates


that no argument is passed to the function.

The return type of the function is void. Hence, no value is returned from the function.

Example : No Arguments Passed But Returns a Value


The empty parentheses in the n = getInteger(); statement indicates that no argument is
passed to the function. And, the value returned from the function is assigned to n.

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.

Example : Argument Passed But No Return Value

The integer value entered by the user is passed to the checkPrimeAndDisplay()


function.

Here, the checkPrimeAndDisplay() function checks whether the argument passed is a


prime number or not and displays the appropriate message.

Example : Argument Passed and Returns a Value


The input from the user is passed to the checkPrimeNumber() function.

The checkPrimeNumber() function checks whether the passed argument is prime or


not.

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.

Depending on whether flag is 0 or 1, an appropriate message is printed from the


main() function.
Which approach is better?

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.

A function should perform a specific task. The checkPrimeNumber() function doesn't


take input from the user nor it displays the appropriate message. It only checks
whether a number is prime or not.

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();
... .. ...
}

The recursion continues until some condition is met to prevent it.

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.

Let's take an example.

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.

Let's take another example.

int main() {
int n1; // n1 is a local variable to main()
}

void func() {
int n2; // n2 is a local variable to func()
}

In the above example, n1 is local to main() and n2 is local 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

A static variable is declared by using the static keyword. For example;


static int i;

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.

Class work and assignment

1. Display all prime numbers between two Intervals


2. Check prime and Armstrong number by making functions
3. Check whether a number can be expressed as the sum of two prime numbers
4. Find the sum of natural numbers using recursion
5. Calculate the factorial of a number using recursion
6. Find G.C.D using recursion
7. Reverse a sentence using recursion
8. Calculate the power of a number using recursion

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 checkPrimeNumber(int n);


int checkArmstrongNumber(int n);

int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d", &n);

// check prime number


flag = checkPrimeNumber(n);
if (flag == 1)
printf("%d is a prime number.\n", n);
else
printf("%d is not a prime number.\n", n);

// check Armstrong number


flag = checkArmstrongNumber(n);
if (flag == 1)
printf("%d is an Armstrong number.", n);
else
printf("%d is not an Armstrong number.", n);
return 0;
}

// function to check prime number


int checkPrimeNumber(int n) {
int i, flag = 1, squareRoot;
// computing the square root
squareRoot = sqrt(n);
for (i = 2; i <= squareRoot; ++i) {
// condition for non-prime number
if (n % i == 0) {
flag = 0;
break;
}
}
return flag;
}
// function to check Armstrong number
int checkArmstrongNumber(int num) {
int originalNum, remainder, n = 0, flag;
double result = 0.0;

// store the number of digits of num in n


for (originalNum = num; originalNum != 0; ++n) {
originalNum /= 10;
}
for (originalNum = num; originalNum != 0; originalNum /= 10) {
remainder = originalNum % 10;

// store the sum of the power of individual digits in result


result += pow(remainder, n);
}
// condition for Armstrong number
if (round(result) == num)
flag = 1;
else
flag = 0;
return flag;
}

Explanation of the above code.

In this program, two user-defined functions checkPrimeNumber() and


checkArmstrongNumber() are created.

The checkPrimeNumber() function returns:

1 if the number entered by the user is a prime number.


0 if the number entered by the user is not a prime number.

Similarly, checkArmstrongNumber() function returns:

1 if the number entered by the user is an Armstrong number.


0 if the number entered by the user is not an Armstrong number.

Note: In checkPrimeNumber() and checkArmstrongNumber() functions, the flag


variables are the return value of the functions.

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

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.
Suppose you declared an array mark as above. The first element is mark[0], the
second element is mark[1] and so on.

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.

How to initialize an array?

It is possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

You can also initialize an array like this.

int mark[] = {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.

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

Change Value of Array elements

int mark[5] = {19, 10, 8, 17, 9}

// make the value of the third element to -1


mark[2] = -1;

// make the value of the fifth element to 0


mark[4] = 0;

Input and Output Array Elements

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

// take input and store it in the ith element


scanf("%d", &mark[i-1]);

Here's how you can print an individual element of an array.

// print the first element of the array


printf("%d", mark[0]);

// print the third element of the array


printf("%d", mark[2]);

// print ith element of the array


printf("%d", mark[i-1]);

Example 1: Array Input/Output


Here, we have used a for loop to take 5 inputs from the user and store them in an
array. Then, using another for loop, these elements are displayed on the screen.
Example : Calculate Average

Access elements out of its bound!

Suppose you declared an array of 10 elements. Let's say,

int testArray[10];

You can access the array elements from testArray[0] to testArray[9].

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

Here, the array y can hold 24 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};

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

Example : Two-dimensional array to store and print values


Pass arrays to a function in C

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.

Pass Individual Array Elements


Passing array elements to a function is similar to passing variables to a function.
Example : Pass Individual Array Elements

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

// pass second and third elements to display()


display(ageArray[1], ageArray[2]);
return 0;
}

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:

void display(int age1, int age2) {


// code
}

Example: Pass Arrays to Functions

// Program to calculate the sum of array elements by passing to a function

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

float calculateSum(float num[]) {


float sum = 0.0;

for (int i = 0; i < 6; ++i) {


sum += num[i];
}

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

However, notice the use of [] in the function definition.

float calculateSum(float num[]) {


... ..
}

This informs the compiler that you are passing a one-dimensional array to the
function.

Pass Multidimensional Arrays to a Function

To pass multidimensional arrays to a function, only the name of the array is passed
to the function (similar to one-dimensional arrays).

Example: Pass two-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]);
}
}

// pass multi-dimensional array to a function


displayNumbers(num);

return 0;
}

void displayNumbers(int num[2][2]) {


printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}

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

This signifies that the function takes a two-dimensional array as an argument. We


can also pass arrays with more than 2 dimensions as a function argument.

When passing two-dimensional arrays, it is not mandatory to specify the number of


rows in the array. However, the number of columns should always be specified.

For example,

void displayNumbers(int num[][2]) {


// code
}

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

You might also like