Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 10

COMPUTER PROGRAMMING

Engr. Anees Ahmed Soomro


Assistant Professor
CSE QUEST Nawabshah
INTRODUCTION TO COMPUTER PROGRAMMING

1) Concept of Array in C
2) Static and Dynamic array in C
3) Single dimensional and multidimensional array
4) Static and dynamic single and multidimensional array
Concept of array in C
• Array is collection of homogeneous elements in C
• Array is needed to be declared and initialized

Syntax:

Declaration
datatype variable_array[size];

int array[10];
Initialization
Single dimensional array
array[0]=20;
array[1]=30;
array[2]=40;
array[3]=50;
array[4]=60;
array[5]=70;
array[6]=80;
array[7]=90;
array[8]=90;
array[9]=100;

• First element can be accessed array[0]


• Last element can be accessed array[9] or array[size-1]
Average of week’s temperature
#include<stdio.h>
void main(void)
{
int temper[7];
int day,sum;
for(day=0;day<7;day++)
{
printf(“Enter temperature for day %d”,day);
scanf(“%d”,&temper[day]);
}
sum=0;
for(day=0;day<7;day++)
sum+=temper[day];
printf(“The average is %d”,sum/7);
}
Static and Dynamic array in C
Static single dimensional array

It is referring to individual elements of array.


i-e temper[2]

temper 0 1 2 3 4 5 6

temper[2] temper[5]
Dynamic initialization of array
#include<stdio.h>
#include<conio.h>
#define LIM 7

void main(void)
{
int temper[LIM]={50,25,30,35,40,45,41};
printf("1st day temperature is %d",temper[0]);
printf("2nd day temperature is %d",temper[1]);
printf("3rd day temperature is %d",temper[2]);
printf("4th day temperature is %d",temper[3]);
printf("5th day temperature is %d",temper[4]);
printf("6th day temperature is %d",temper[5]);
printf("7th day temperature is %d",temper[6]);
getch();
}
Multidimensional Array

Syntax:

Datatype variableName[size][size];

• It is known as two dimensional array


• It is also known as array of array
• Matrix example of array
Matrix example of array
#include<stdio.h>
#include<conio.h>
void main(void)
{
int matrix[2][2];
printf(“enter 1st row and 1st col”);
scanf(“%d”,&matrix[0][0]);
printf(“enter 1st row and 2nd col”);
scanf(“%d”,&matrix[0][1]);
printf(“enter 2nd row and 1st col”);
scanf(“%d”,&matrix[1][0]);
printf(“enter 2nd row and 2nd col”);
scanf(“%d”,&matrix[1][1]);
}
Multidimensional Array Dynamic Array initialization
#include<stdio.h>
#include<conio.h>
void main(void)
{
int matrix[2][2]={{2,3},{4,5}};

0,0 0,1 1,0 1,1

printf(Matrix[0][0]);
printf(Matrix[0][1]);
printf(Matrix[1][0]);
printf(Matrix[1][1]);
}
Matrix [3][2][1]={{{1},{2}},{{3},{4}},{{5},{6}}};
Matrix[2][2][2]={{{1,2},{3,4},{5,6},{7,8}}};
Matrix[2][2][2]={{{1,2},{3,4}},{{5,6},{7,8}}};

You might also like