0% found this document useful (0 votes)
12 views

c lagng-converted (12)

Uploaded by

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

c lagng-converted (12)

Uploaded by

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

Unit I

Procedural Language:
In procedural languages, the program code is written as a sequence of
instructions. User has to specify “what to do” and also “how to do” (step by
step procedure). These instructions are executed in the sequential order.
These instructions are written to solve specific problems.

Examples of Procedural languages:


FORTRAN, COBOL, ALGOL, BASIC, C and Pascal.

C programming is a general-purpose, procedural, Structured computer


programming language developed in 1972 by Dennis M. Ritchie at the Bell
Telephone Laboratories to develop the UNIX operating system.

Why to Learn C Programming?

C programming language is a MUST for students and working professionals


to become a great Software Engineer specially when they are working in
Software Development Domain. I will list down some of the key advantages
of learning C Programming:
• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms

Applications of C Programming
C was initially used for system development work, particularly the programs
that make-up the operating system. C was adopted as a system development
language because it produces code that runs nearly as fast as the code
written in assembly language. Some examples of the use of C are -
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
Structure of c program

Hello World

#include <stdio.h>
main()
{
/* my first program in C */
printf("Hello, World! \n");

Let us take a look at the various parts of the above program −


• The first line of the program #include <stdio.h> is a preprocessor
command, which tells a C compiler to include stdio.h file before going
to actual compilation.
• The next line main() is the main function where the program execution
begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to
add additional comments in the program. So such lines are called
comments in the program.
• The next line printf(...) is another function available in C which causes
the message "Hello, World!" to be displayed on the screen.

Compile and Execute C Program
Let us see how to save the source code in a file, and how to compile and run
it. Following are the simple steps −
• Open a text editor and add the above-mentioned code.
• Save the file as hello.c
• Open a command prompt and go to the directory where you have
saved the file.
• Type gcc hello.c and press enter to compile your code.
• If there are no errors in your code, the command prompt will take you to
the next line and would generate a.out executable file.
• Now, type a.out to execute your program.
• You will see the output "Hello World" printed on the screen.

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

Here, int is a keyword that indicates a 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 C.

A list of 32 reserved keywords in c language

Auto double int struct

Break else long switch

Case enum register typedef


Char extern return union

Const float short unsigned

Continue for signed void

Default goto sizeof volatile

Do if static while

C Identifiers
Identifiers are names given to different entities such as constants, variables, structures, functions,
etc.
int money;

Here, money is identifier.

Also remember, identifier names must be different from keywords. You cannot use int as an

identifier because is a keyword.

Rules for naming identifiers

1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.

2. The first letter of an identifier should be either a letter or an underscore.

3. You cannot use keywords like int, while etc. as identifiers.

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


Variables

Variables are memory locations(storage area) in the C programming language.


The primary purpose of variables is to store data in memory for later use.
Unlike constants which do not change during the program execution, variables value may
change during execution. If you declare a variable in C, that means you are asking the operating
system to reserve a piece of memory with that variable name.

type variable_name;

or
type variable_name, variable_name, variable_name;

Variable Declaration and Initialization


Example:

int width, height=5;


char letter='A';
float age, area;
double d;
age = 26.5;

C programming language offers various types of operators having different


functioning capabilities.

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operator
7. Bitwise Operators
8. Special Operators
Arithmetic Operators
Arithmetic Operators are used to performing mathematical calculations like
addition (+), subtraction (-), multiplication (*), division (/) and modulus
(%).These are binary operators(apply more than one operands)

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

C Program to Add Two Numbers


Example:
#include <stdio.h>
void main()
{
int i=5,j=2,k,l,m,n; /* Variables Defining and Assign
values */
k=i+j;
printf("Sum of two numbers is %d\n", k);
l=i*j;
printf("Multiplication of two numbers is %d\n", l);
m=i+j;
printf("Division of two numbers is %d\n", m);
n=i%j;
printf("Modulus of two numbers is %d\n", n);
}
Program Output:
Sum of two numbers is 7
Multiplication of two numbers is 10
Division of two numbers is 2
Modulus of two numbers is 1

Increment and Decrement Operators are useful operators generally used to


minimize the calculation, i.e. ++x and x++ means x=x+1 or --x and x−−means
x=x-1. But there is a slight difference between ++ or −− written before or after
the operand. Applying the pre-increment first add one to the operand and then
the result is assigned to the variable on the left whereas post-increment first
assigns the value to the variable on the left and then increment the
operand.These are unary operators.

Operator Description

++ Increment

−− Decrement

Example: To Demonstrate prefix and postfix modes.


#include <stdio.h>
//stdio.h is a header file used for input.output purpose.

void main()
{
//set a and b both equal to 5.
int a=5, b=5;
//Print them and decrementing each time.
//Use postfix mode for a and prefix mode for b.
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
}
Program Output:
5 4
4 3
3 2
2 1
1 0

Relational Operators
Relational operators are used to comparing two quantities or values.
Operator Description

== Is equal to

!= Is not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to


#include <stdio.h>

int main()
{
int m=40,n=20;
if (m = = n)
printf("m and n are equal");
else
printf("m and n are not equal");

or

#include <stdio.h>

int main()
{
int m=40,n=20;
if (m != n)
printf("m and n are no equal");
else
printf("m and n are equal");

Logical Operators
C provides three logical operators when we test more than one condition to
make decisions. These are: && (meaning logical AND), || (meaning logical
OR) and ! (meaning logical NOT).
Operator Description

&& And operator. It performs logical conjunction of two expressions. (if both
expressions evaluate to True, result is True. If either expression evaluates
to False, the result is False)
|| Or operator. It performs a logical disjunction on two expressions. (if either
or both expressions evaluate to True, the result is True)

! Not operator. It performs logical negation on an expression.

include <stdio.h>

int main()
{
int m=40, n=20;
int o=20, p=30;
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. " \
"But, status is inverted as false\n");
}
}
OUTPUT:
&& Operator : Both conditions are true
|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false
Bitwise Operators
C provides a special operator for bit operation between two variables.
Operator Description

<< Binary Left Shift Operator

>> Binary Right Shift Operator

~ Binary Ones Complement Operator

& Binary AND Operator

^ Binary XOR Operator

| Binary OR Operator

Bitwise AND operator &


The output of bitwise AND is 1 if the corresponding
bits of two operands is 1. If either bit of an operand is
0, the result of corresponding bit is evaluated to 0.

Let us suppose the bitwise AND operation of two


integers 12 and 25.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)


Bit Operation of 12 and 25

00001100

& 00011001

________

00001000 = 8 (In decimal)

Example #1: Bitwise AND

#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}

Output

Output = 8
Bitwise OR operator |
The output of bitwise OR is 1 if at least one
corresponding bit of two operands is 1. In C
Programming, bitwise OR operator is denoted by |.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25

00001100
| 00011001
________
00011101 = 29 (In decimal)

Example #2: Bitwise OR


#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a|b);
return 0;
}
Output

Output = 29

Bitwise XOR (exclusive OR) operator ^

The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It

is denoted by ^.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25

00001100
^ 00011001
________
00010101 = 21 (In decimal)

Example #3: Bitwise XOR


#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a^b);
return 0;
}

Output

Output = 21

Bitwise complement operator ~

Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0

and 0 to 1. It is denoted by ~.

35 = 00100011 (In Binary)

Bitwise complement Operation of 35

~ 00100011
________
11011100 = 220 (In decimal)

Assignment Operators
Assignment operators applied to assign the result of an expression to a
variable. C has a collection of shorthand assignment operators.
Operator Description

= Assign

+= Increments then assign

-= Decrements then assign

*= Multiplies then assign

/= Divides then assign

%= Modulus then assign

<<= Left shift and assign

>>= Right shift and assign

&= Bitwise AND assign

^= Bitwise exclusive OR and assign

|= Bitwise inclusive OR and assign

Conditional Operator
C offers a ternary operator which is the conditional operator (?: in
combination) to construct conditional expressions.
Operator Description

?: Conditional Expression

#include <stdio.h>
int main()
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}

Special Operators
C supports some special operators
Operator Description

sizeof() Returns the size of a memory location.

& Returns the address of a memory location.

* Pointer to a variable.

Control Statements
The control statements are used to control the cursor in a program according to the condition or
according to the requirement in a loop. There are mainly three types of control statements or
flow controls. These are illustrated as below:

• Branching
• Looping
• Jumping

Branching Statement
1. if statement
a. Simple if statement
b. if-else statement
c. nested if statement
d. else-if or ladder if or multi-condition if statement
2. switch statement
3. conditional operator statement

1. if statement

a. Simple if statement

The if statement is a powerful decision making statement which can handle a single condition
or group of statements. These have either true or false action....
When only one condition occurs in a statement, then simple if statement is used having one
block.
/*Any Number is input through the keyboard and check number is greater than 0.*/

#include< stdio.h >

#include< conio.h >

void main()

int n;

n=1;

printf("Enter the Number");

scanf("%d",&n);

if(n>0)

printf("Number is greater than 0");

getch();

b. if-else statement

This statement also has a single condition with two different blocks. One is true block and
other is false block...
/*Any Number is input through the keyboard. write a program to find out whether It is and Odd
Number or Even Number.*/

#include< stdio.h >


#include< conio.h >
void main()
{
int n;
n=1;
clrscr();
printf("Enter the Number");
scanf("%d",&n);
if(n%2= =0)
{
printf("This is Even Number");
}
else
{
printf("This is Odd Number");
}
getch();
}

Output is as :
Enter the Number
4
This is Even Number

c. nested if statement
When an if statement occurs within another if statement, then such type of is called nested if
statement. /*If the ages of Ram, sham and Ajay are input through the keyboard, write a program
to determine the youngest of the three*/

#include< stdio.h >


#include< conio.h >
void main()
{
int ram,sham,ajay;
clrscr();
printf("Enter the Three Ages of Ram,Sham and Ajay\n");
scanf("%d%d%d",&ram,&sham,&ajay);
if(ram < sham)
{
if(ram < ajay)
{
printf("Ram is Youngest");
}
else
{
printf("Ajay is Youngest");
}
}
else
{
if(sham < ajay)
{
printf("Sham is Youngest");
}
else
{
printf("Ajay is Youngest");
}
}
getch();
}

Output is as :
Enter the three Ages of Ram,Sham and Ajay
14
17
19
Ram is Youngest

d. Ladder if or else if statement

When in a complex problem number of condition arise in a sequence, then we can use
Ladder-if or else if statement to solve the problem in a simple manner.
The marks obtained by a student in 5 different subjects are input through the keyboard. The student gets a
division as per the following rules:

=> Percentage above or equal to 60 - First Division


=> Percentage between 50 and 59 - Second Division
=> Percentage between 40 and 49 - Third Division
=> Percentage less than 40 - Fail

Method 1

/*Write a program to calculate the division obtained by the student. There are two ways in
which we can write a program for this example. These methods are given below: */

//Method-1
#include< stdio.h >
#include< conio.h >
void main()
{
int eng,math,com,sci,ss,total;
float per;
clrscr();
printf("Enter Five Subjects Marks\n");
scanf("%d%d%d%d%d",&eng,&math,&com,&sci,&ss);

total = eng + math + com + sci + ss ;


printf("Toal Marks : %d",total);
per = total * 100.00 / 500;
printf("\n Percentage : %f", per);

if(per >= 60)


{
printf("\n 1st Division");
}
else if(per >= 50)
{
printf("\n 2nd Division");
}
else if(per >= 40)
{
printf("\n 3rd Division");
}
else
{
printf("\n Sorry Fail");
}
getch();
}

METHOD 2

//Method-2
#include< stdio.h >
#include< conio.h >
void main()
{
int eng,math,com,sci,ss,total;
float per;
clrscr();
printf("Enter Five Subjects Marks\n");
scanf("%d%d%d%d%d",&eng,&math,&com,&sci,&ss);

total = eng + math + com + sci + ss ;


printf("Toal Marks : %d",total);
per = total * 100.00 / 500;
printf("\n Percentage : %f", per);

if(per >= 60)


{
printf("\n 1st Division");
}
if(per >= 50 && per < 60)
{
printf("\n 2nd Division");
}
if(per >= 40 && per < 50)
{
printf("\n 3rd Division");
}
if(per < 40)
{
printf("\n Sorry Fail");
}
getch();
}

2. switch statement
When number of conditions (multiple conditions) occurs in a problem and it is very difficult
to solve such type of complex problem with the help of ladder if statement, then there is need of
such type of statement which should have different alternatives or different cases to solve the
problem in simple and easy way. For this purpose switch statement is used. .

/*WAP to print the four-days of week from monday to thrusday which works upon the choice as
S,M,T,H using switch case*/

#include< stdio.h >


#include< conio.h >
void main()
{
char n;
clrscr();
printf("Enter the Choice from Four Days...\n")
printf("S = Sunday \n")
printf("M = Monday \n")
printf("T = Tuesday \n")
printf("H = Thursday \n\n")

scanf("%c",&n);

switch(n)
{
case 'S':
printf("Sunday");
break;

case 'M':
printf("Monday");
break;

case 'T':
printf("Tuesday");
break;

case 'H':
printf("Thursday");
break;

default:
printf("Out of Choice");
break;

}
getch();
}
Output is as :
Enter the Choice from Four Days...
S = Sunday
M = Monday
T = Tuesday
H = Thursday

S
Sunday

Conditional Control Statement

This statement is based on conditional operator. This statement solves the problem's condition
in a single line and is a fast executable operation. For this purpose we can take combination of ?
and :

/*The easiest way to use conditional control statement*/

#include< stdio.h >


#include< conio.h >
void main()
{
int n;
clrscr();
printf(“Enter year”);
scanf(“%d”, &n);

n%4==0 ? printf("Leap Year") : printf("Not Leap Year");

//OR

//printf(n%4==0 ? "Leap Year" : "Not Leap Year");

getch();
}

Output is as :
Enter year 2020
Leap Year

Looping

C programming has three types of loops:

1. for loop

2. while loop

3. do...while loop

1. For loop
A for loop is a more efficient loop structure in 'C' programming. The general structure of for loop
syntax in C is as follows:

for (initial value; condition; incrementation or decrementation )


{
statements;
}

• The initial value of the for loop is performed only once.


• The condition is a Boolean expression that tests and compares the counter to a fixed
value after each iteration, stopping the for loop when false is returned.
• The incrementation/decrementation increases (or decreases) the counter by a set value.

for loop Flowchart

Example 1: for loop

// Print numbers from 1 to 10


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

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


printf("%d\n ", i);

Output

1
2
3
4
5
6
7
8
9
10
// Print numbers from 10 to 1
#include <stdio.h>

main()
{
int i;

for (i = 10; i >= 1; i--)


printf("%d\n ", i);

Output

10
9
8
7
6
5
4
3
2
1

While Loop in C

A while loop is the most straightforward looping structure. Syntax of while loop in C
programming language is as follows:

while (condition) {
statements;
}
Example 1: while loop

// Print numbers from 1 to 10


#include <stdio.h>

main()
{
int i=1;

while(I < 11)


{
printf("%d\n ", i);
i++;

Output

1
2
3
4
5
6
7
8
9
10

Do while Loop in C
A do while loop is similar to while loop with one exception that it executes the statements
inside the body of do-while before checking the condition. On the other hand in the for and
while loop, first the condition is checked and then the statements in for and while loop are
executed. So you can say that if a condition is false at the first place then the do while would
run once, however the while loop would not run at all. Note that do-while runs at least once
even if the condition is false because the condition is evaluated, after the execution of the
body of loop.

Flow diagram of do while loop

Syntax of do-while loop

do
{
//Statements

}while(condition test);

#include <stdio.h>
main()
{
int j=1;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}while (j<=10);

Output

1
2
3
4
5
6
7
8
9
10
// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>
main()
{
int num, count, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &num);

for(count = 1; count <= num; count++)


{
sum = sum + count;
}

printf("Sum = %d", sum);

// Program to calculate the sum of first n natural numbers


// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>
main()
{
int num, count = 1, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &num);

while( count <= num)


{
sum = sum + count;
count++;
}

printf("Sum = %d", sum);

// Program to calculate the sum of square of first n natural


numbers
// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>
main()
{
int num, count = 1, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &num);

while( count <= num)


{
sum = sum + count*count;
count++;
}

printf("Sum = %d", sum);}


3. Jumping

Jump statements are used to interrupt the normal flow of program.

Types of Jump Statements

• Break
• Continue
• GoTo

Break Statement
Break

The break statement is used to terminate the loop or statement in which it present.
After that, the control will pass to the statements that present after the break
statement, if available. If the break statement present in the nested loop, then it
terminates only those loops which contains break statement.

Example of break statement

#include<stdio.h>
void main()
{
int a=1;

while(a<=10)
{
if(a==5)
break;

printf("\nStatement %d.",a);
a++;
}
printf("\nEnd of Program.");
}

Output :

Statement 1.
Statement 2.
Statement 3.
Statement 4.
End of Program.

Continue Statement
Continue
This statement is used to skip over the execution part of the loop on a certain
condition. After that, it transfers the control to the beginning of the loop. Basically, it
skips its following statements and continues with the next iteration of the loop.

Example of continue statement

#include<stdio.h>

void main()
{
int a=0;

while(a<10)
{

a++;

if(a==5)
continue;

printf("\nStatement %d.",a);

}
printf("\nEnd of Program.");
}

Output :

Statement 1.
Statement 2.
Statemnet 3.
Statement 4.
Statement 6.
Statement 7.
Statement 8.
Statement 9.
Statement 10.
End of Program.

Goto Statement
goto
The goto statement is a jump statement which jumps from one point
to another point within a function.

Syntax of goto statement

goto label;
----------
----------
label:
----------
----------

In the above syntax, label is an identifier. When, the control of


program reaches to goto statement, the control of the program will
jump to the label: and executes the code after it.
Example of goto statement

#include<stdio.h>

void main()
{
printf("\nStatement 1.");
printf("\nStatement 2.");
printf("\nStatement 3.");

goto last;

printf("\nStatement 4.");
printf("\nStatement 5.");

last:

printf("\nEnd of Program.");
}

Output :

Statement 1.
Statement 2.
Statement 3.
End of Program.
Scope rules

#include <stdio.h>

/* global variable declaration */


int g;

int main () {

/* local variable declaration */


int a, b;

/* actual initialization */
a = 10;
b = 20;
g = a + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b,


g);
return 0;
}

Arrays in C

An array in C or C++ is a collection of items stored at contiguous memory


locations and elements can be accessed randomly using indices of an array.
They are used to store similar type of elements as in the data type must be the
same for all elements. They can be used to store collection of primitive data
types such as int, float, double, char, etc of any particular type. To add to it, an
array in C or C++ can store derived data types such as the structures, pointers
etc. Given below is the picturesque representation of an array.

Why do we need arrays?


We can use normal variables (v1, v2, v3, ..) when we have a small number of
objects, but if we want to store a large number of instances, it becomes difficult
to manage them with normal variables. The idea of an array is to represent many
instances in one variable.
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.
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
Example 1: Array Input/Output

// Program to take 5 values from the user and store them in an


array
// Print the elements stored in the array
#include <stdio.h>

int main() {
int values[5];

printf("Enter 5 integers: ");

// taking input and storing it in an array


for(int i = 0; i < 5; ++i) {
scanf("%d", &values[i]);
}

printf("Displaying integers: ");

// printing elements of an array


for(int i = 0; i < 5; ++i) {
printf("%d\n", values[i]);
}
return 0;
}

Output

Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3

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 2: Calculate Average

// Program to find the average of n numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;

printf("Enter number of elements: ");


scanf("%d", &n);

for(i=0; i<n; ++i)


{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);

// adding integers entered by the user to the sum


variable
sum += marks[i];
}

average = sum/n;
printf("Average = %d", average);

return 0;
}

Output

Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
Two Dimensional or 2D Array in C
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D arrays
are created to implement a relational database lookalike data structure. It provides ease of
holding the bulk of data at once which can be passed to any number of functions wherever
required.

Declaration of two dimensional Array in C

The syntax to declare the 2D array is given below.

data_type array_name[rows][columns];

Consider the following example.

Int a[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.

Initialization of 2D Array in C

In the 1D array, we don't need to specify the size of the array if the declaration and initialization
are being done simultaneously. However, this will not work with 2D arrays. We will have to
define at least the second dimension of the array. The two-dimensional array can be declared and
defined in the following way.

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensional array example in C
#include<stdio.h>
int
main()
{
int i=0, j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf(" %d \t",arr[i][j]);
}//end of j
Printf(“\n”);
} //end of i
getch();
}

Output

1 2 3
2 3 4
3 4 5
4 5 6

C 2D array example: Storing elements in a matrix and printing it.


#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}

Output

Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements ....

56 10 30
34 21 34
45 56 78
/*
* C program to accept a matrix of order MxN and find its transpose
*/
#include <stdio.h>

void main()
{
static int array[10][10];
int i, j, m, n;

printf("Enter the order of the matrix \n");


scanf("%d %d", &m, &n);
printf("Enter the coefiicients of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
}

Functions in C
A function is a block of code that performs a particular task.
There are many situations where we might need to write same line of code for more than once in
a program. This may lead to unnecessary repetition of code, bugs and even becomes boring for
the programmer. So, C language provides an approach in which you can declare and define a
group of statements once in the form of a function and it can be called and used whenever
required.
These functions defined by the user are also know as User-defined Functions
C functions can be classified into two categories,
1. Library functions

2. User-defined functions

Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use
these functions. These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are defined by the user at
the time of writing program. These functions are made for code reusability and for saving time
and space.

Benefits of Using Functions

1. It provides modularity to your program's structure.

2. It makes your code reusable. You just have to call the function by its name to use it,

wherever required.

3. In case of large programs with thousands of code lines, debugging and editing becomes

easier if you use functions.

4. It makes the program more readable and easy to understand.

Function Declaration
General syntax for function declaration is,

returntype functionName(type1 parameter1, type2 parameter2,...);

Like any variable or an array, a function must also be declared before its used. Function
declaration informs the compiler about the function name, parameters is accept, and its return
type. The actual body of the function can be defined separately. It's also called as Function
Prototyping. Function declaration consists of 4 parts.

• returntype

• function name
• parameter list

• terminating semicolon

returntype

When a function is declared to perform some sort of calculation or any operation and is expected
to provide with some result at the end, in such cases, a return statement is added at the end of
function body. Return type specifies the type of value(int, float, char, double) that function is
expected to return to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.
functionName

Function name is an identifier and it specifies the name of the function. The function name is any
valid C identifier and therefore must follow the same naming rules like other variables in C
language.
parameter list

The parameter list declares the type and number of arguments that the function expects when it is
called. Also, the parameters in the parameter list receives the argument values when the function
is called. They are often referred as formal parameters.
Type of User-defined Functions in C
There can be 4 different types of user-defined functions, they are:

1. Function with no arguments and no return value

2. Function with no arguments and a return value

3. Function with arguments and no return value

4. Function with arguments and a return value


1. Function with no arguments and no return value

#include<stdio.h>

void sum(); // function declaration

main()
{
void sum(); // function declaration
sum(); // function call
}

void sum() // function definition


{
int i, j,k;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
k=i + j;
printf("The sum of number is: %d", k);
}

#include<stdio.h>

void sum() // function definition


{
int i, j,k;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
k=i + j;
printf("The sum of number is: %d", k);
}

main()
{

sum(); // function call


}
2. Function with no arguments and a return value

#include<stdio.h>

main()
{
int add;
int sum(); // function declaration
add = sum(); // function call
printf("The sum of number is: %d", add);

void sum() // function definition


{
int i, j,k;
printf("Enter 2 numbers ");
scanf("%d%d", &i, &j);
k=i + j;
return(k);
}

3. Function with arguments and no return value

#include<stdio.h>

main()
{
int I,j;
void sum(int,int); // function declaration
printf("Enter 2 numbers ");
scanf("%d%d", &i, &j);
sum(i,j); // function call

void sum(int x, int y) // function definition


{
int add;
add =x + y;
printf("The sum of number is: %d", add);
}
4. Function with arguments and a return value

#include<stdio.h>

main()
{
int add,I,j;
int sum(int, int); // function declaration
printf("Enter 2 numbers ");
scanf("%d%d", &i, &j);
add = sum(i,j); // function call
printf("The sum of number is: %d", add);

void sum(int x, int y) // function definition


{
int z;
z =x + y;
return(z);
}

Pointers in C
Pointer is a variable in C that holds the address of another variable. They
have data type just like variables, for example an integer type pointer can hold
the address of an integer variable and an character type pointer can hold the
address of char variable.

Syntax of pointer
data_type *pointer_name;

int *p, var;

Assignment
An integer type pointer can hold the address of another int variable. Here we
have an integer variable var and pointer p holds the address of var. To assign the
address of variable to pointer we use ampersand symbol (&).

p = &var;
#include <stdio.h>
int main()
{
int* pc, c;

c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22

pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22

c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11

*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}

Output

Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784


Content of pointer pc: 22

Address of pointer pc: 2686784


Content of pointer pc: 11
Address of c: 2686784
Value of c: 2

You might also like