Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 28

1

Fundamentals of Computer
Programming

Jehangir Arshad Meo


(Lecturer)

Mechanical Engineering Department


COMSATS Institute of Information Technology, Sahiwal
oScalar variables: capable of holding a single data item

oAggregate variables: capable of holding a collections of


values.
Introduction(Arrays):
 An array is a collection of same type of elements which are sheltered
under a common name.

 May be type of any kind of variable


 May even be collection of arrays!

 For ease of access to any member of array


 For passing to programs as a group

3
Why arrays are used?
 Some times we need consequent memory locations to store data that
should be of same type , same name and searching sorting of that data
should also be easy.

 For example if we want to store a name or storing multiple names.

 To get above given purposes c language gives the concept of arrays.

4
Format/ Declaring Arrays :
Specify array name and position number (index)

Format: data type array name[ position number ]

◦ Data type: The type of data that is to be stored in array.


◦ Array Name: Name of array
◦ Index: Number of specific position of array element

 Declaring multiple arrays of same type:

◦ Use comma separated list, like regular variables


int b[ 100 ] , a[52] , m[4];

 N-element array c:

c[ 0 ], c[ 1 ] … c[ n - 1 ]
Nth element as position N-1

int c[ 10 ]; // array of 10 integers


float d[ 3284 ]; // array of 3284 floats

5
Example:
int C[12]
 An array of ten integers
 C[0], C[1], …, C[11]

double B[20]
 An array of twenty long floating point numbers
 B[0], B[1], …, B[19]

Array indexes always start at zero in C

6
 

Name of array (Note

Arrays
that all elements of
this array have the
same name, c)

. c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78

Position number of the


element within array c

7
Initialization of Arrays:
◦ Initializer list
 Specify each element when array declared

int n[ 5 ] = { 1, 2, 3, 4, 5 };

 If not enough initializers, rightmost elements 0


 If too many, syntax error

◦ If array size omitted, initializers determine size

int n[] = { 1, 2, 3, 4, 5 };
 5 initializers, therefore 5 element array

8
Always initialize array when you declare it

int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int a[10] = {1 , 2, 3, 4, 5, 6};


/* {1, 2, 3, 4, 5, 0, 0, 0, 0, 0} */

int a[10] = {0};


/* {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} */
Initialization of array for String:
 There are two ways:

Char arr[] = “code”;


 OR

char arr[] = {'c','o','d','e','\0'};

 In the above declaration initialization, we have initialized


array with a series of character followed by a ‘\0′ (null) byte.
The null byte is required as a terminating byte when string is
read as a whole.

10
Example (Accessing values in an
array):
int arr[10]; //array of 10 elements
int i = 0;
for(i=0;i<sizeof(arr);i++)
{
arr[i] = i; // Initializing each element separately
}
int j = arr[5];
// Accessing the 5th element of integer array arr and assigning its
value to integer 'j'.
printf("the value of 5th element is %d\n", arr[5] );

11
The sizeof operator can determine the size of an
array (in bytes).
int a[10];
Measure the size of an array:
Sizeof(a) / sizeof(a[0]);

#define SIZE ((int) (sizeof(a) / sizeof(a[0])))


Types of Arrays:
There are two types of arrays:

 One-dimensional arrays

 Multi-dimensional arrays

13
The simplest kind of arrays. The elements, the values of
the items, of a one-dimensional array are conceptually
arranged one after another in a single row.

int a[8];

#define N 8
……
int a[N];
Multi-Dimensional arrays:
  If we want to store multiple strings in an array. Well, that wont be possible
using single dimensional arrays. We need to use bi-dimensional arrays in this
case. Something like :

Char arr[5][10];

 The above declaration can be thought of as 5 rows and 10 columns. Where


each row may contain a different name and columns may limit the number of
characters in the name.

 So we can store 5 different names with max length of 10 characters each.

15
int m[5][9]; // 5 rows 9 columns

0 1 2 3 4 5 6 7 8
0

1
2
3
4

.
int m[5][9] = { {1,1,1,1,1,1,1,1,1},
{0,1,0,0,0,1,1,0,1},
{0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,1,1},
int m[3][9] = { {1,1,1,1,1,1,1,1,1},
{1,0,1,0,1,0,1,0,1}} {0,1,0,0,0,1,1,0,1},
{0,0,0,0,0,0,0,0,0}}
int m[2][9] = { {1,1,1,1,1,1,1,1,1},
{0,1,0,0,0,1,1,0,1}}
Write a program to copy elements
of one array to the other?
#include <stdio.h>
int main()
{
int iMarks[4];
short newMarks[4];
iMarks[0]=78;
iMarks[1]=64;
iMarks[2]=66;
iMarks[3]=74;
for(i=0; i<4; i++)
newMarks[i]=iMarks[i];
for(j=0; j<4; j++)
printf("%d\n", newMarks[j]);
return 0;
}

18
Program that stores roll numbers and marks obtained by
a student side by side in matrix.
#include<stdio.h>
main ( )
{
int stud [4] [2];
int i, j;
for (i=0; i<=3; i ++)
{
printf ("\n Enter roll no. and marks");
scanf ("%d%d", &stud [i] [0], &stud [i] [1] );
}
for (j = 0; j<=3; j ++)
printf ("\n %d %d", stud [i] [0], stud [i] [1]);
}

19
Sorting of Arrays
 It is an important computing application

 Virtually every organization must sort some data


 Massive amounts must be sorted.

 Bubble sort (sinking sort):


 Several passes through the array

 Successive pairs of elements are compared


 If increasing order (or identical), no change
 If decreasing order, elements exchanged

 Repeat these steps for every element

20
Sorting Arrays
 Example:
 Go left to right, and exchange elements as necessary
 One pass for each element
 Original: 3 4 2 7 6
 Pass 1: 3 2 4 6 7 (elements exchanged)
 Pass 2: 2 3 4 6 7
 Pass 3: 2 3 4 6 7 (no changes needed)
 Pass 4: 2 3 4 6 7

 Small elements "bubble" to the top (like 2 in this example)

21
Sorting Arrays
Swapping variables
int x = 3, y = 4;
y = x;
x = y;
What happened?
Both x and y are 3!
Need a temporary variable
Solution
int x = 3, y = 4, temp = 0;
temp = x; // temp gets 3
x = y; // x gets 4
y = temp; // y gets 3

22
Searching Arrays:
Search of an array for a key value is of two types:

1- Linear Search

2- Binary Search

23
Linear search:
 Array is not in sorted form.

 Compare each element of array with key value

 Start at one end, go to other

 Useful for small and unsorted arrays

 Inefficient
 If search key not present, examines every element

24
Binary search:
 Array should be in sorted form.

 Array is divided in two parts.

 Medium value is calculated.

 Then key value is compared with the medium value if the value is less then the medium
then upper part of the array is skipped and value is compared only with the lesser values.

 If the value is greater then the medium then the lower part of the array is skipped and value
is compared only with the larger values.
 It is much faster way of array searching

25
Binary Searching Arrays:
 Binary search
 Only used with sorted arrays
 Compare middle element with key
If equal, match found
 If key < middle

 Repeat search on first half of array

 If key > middle

 Repeat search on last half

 Very fast
N
 At most N steps, where 2 > # of elements
 30 element array takes at most 5 steps
5
2 > 30

26
Array Sorting:
#include<stdio.h>
int main(){ Output:
int s,i,j,temp,a[20];
 
 
printf("Enter total elements: ");
scanf("%d",&s);
Enter total elements: 5
 
printf("Enter %d elements: ",s);
for(i=0;i<s;i++){
Enter 5 elements: 4 5 0 21 7
      scanf("%d",&a[i]);
} The array after sorting
for(i=0;i<s;i++){
  for(j=i+1;j<s;j++){ is:  0 4 5 7 21
           if(a[i]>a[j]){
              temp=a[i];
               a[i]=a[j];
              a[j]=temp;
           }
       }
  }
  printf("After sorting is: ");
  for(i=0;i<s;i++){
      printf(" %d",a[i]);
}
return 0;
} 27
Link for help:
Video for searching:
http://xoax.net/comp_sci/crs/algorithms/lessons/Lesso
n5/

Basics of arrays:
http://www.augustcouncil.com/~tgibson/tutorial/arr.ht
ml

28

You might also like