Structured Programming Approach Module VIII - Additional C Data Types Arrays Prof: Muhammed Salman...

Preview:

Citation preview

Structured Programming Approach

Module VIII - Additional C Data TypesArrays

Prof: Muhammed Salman Shamsi

Introduction

• A scalar variable is a single variable whose stored value is an atomic type.

• An aggregate type, which is referred to as both a structured type and a data structure, is any type whose values can be decomposed and are related by some defined structure.

• Scalar type

• Ex:

int a,b;

a=3;b=4;

float c;

c=5.543

• Aggregate type

• Ex:

Example

5.543

43

a b

c

5 4 3 5

5 4.56 6.78 1

5 A 6.78 C

Arrays

• An array is a collection of individual data elements that is ordered, fixed in size, and homogeneous.

One Dimesional Arrays

The syntax for declaration of a one-dimensional array is

data_type array_name[SIZE];

Initialization of Array

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

(b) double a[5] = {3.67, 1.21,5.87,7.45,9.12};

(c) int arr[] = {3,1,5,7,9};

Storing values given by the user in an array

• Reading the input into an array is done as shown. int a[10]; /* an array with 10 “int” elements */

int i;

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

scanf(“%d”, &a[i]);

• The idea is that first a value must be read and copied into a[0], then another value read and copied into a[1], and so on, until all the input values have been read.

scanf("%d",&a[0]);..scanf("%d",&a[9]);

Printing values of arrays

• The following code segment prints the elements of an array, a[10].

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

printf(“%d”, a[i]);

printf("%d",a[0]);..printf("%d",a[9]);

I/O statement for Arrays and scalar type

• Arrays input and output statement are similar to those of scalar types with an exception of loop for arrays.

• Reason:

Arrays are set of elements (aggregate type)

Scalar type have single value (atomic)

Printing an array

Printing binary equivalent of a

decimal number using array.

Fibonacci series using an array

WAP to search an element in an array

Bubble Sort• A bubble sort compares adjacent array

elements and exchanges their values if they are out of order.

• Each pass through the list places the next largest value in its proper place. In essence, each item “bubbles” up to the location where it belongs.

• This sort continues until no exchanges are performed.

ExampleLet us take the array of numbers "5 1 4 2 8", and sort

the array from lowest number to greatest number using bubble sort. In each step, elements written in bold are being compared. Three passes will be required.

First Pass:( 5 1 4 2 8 ) -->( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and

swaps since 5 > 1.( 1 5 4 2 8 ) --> ( 1 4 5 2 8 ), Swap since 5 > 4( 1 4 5 2 8 ) --> ( 1 4 2 5 8 ), Swap since 5 > 2( 1 4 2 5 8 ) --> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),

algorithm does not swap them.

Second Pass:

( 1 4 2 5 8 ) --> ( 1 4 2 5 8 )

( 1 4 2 5 8 ) --> ( 1 2 4 5 8 ), Swap since 4 > 2

( 1 2 4 5 8 ) --> ( 1 2 4 5 8 )

( 1 2 4 5 8 ) --> ( 1 2 4 5 8 )

Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:

( 1 2 4 5 8 ) --> ( 1 2 4 5 8 )

( 1 2 4 5 8 ) --> ( 1 2 4 5 8 )

( 1 2 4 5 8 ) --> ( 1 2 4 5 8 )

( 1 2 4 5 8 ) --> ( 1 2 4 5 8 )

Hence the sorted array is "1 2 4 5 8"

Graphically

Optimization of bubble sort

• A small improvement can be made if each pass you keep track of whether or not an element was swapped. If not, you can safely assume the list is sorted.

Program

OutputHow many numbers 5

Enter the array elements 67529

The numbers in sorted order 2 5 6 7 9

STRINGS: ONE-DIMENSIONAL CHARACTER ARRAYS

Strings in C are represented by arrays of characters. The end of the string is marked with a special character, the null character, which is a character all of whose bits are zero, i.e., a NUL (not a NULL).

The null or string-terminating character is represented by another character escape sequence, \0.

Declaration of a String

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

char greeting[] = "Hello";

STRING INPUT/OUTPUT

• One special case, where the null character is not automatically appended to the array, is when the array size is explicitly specified and the number of initializers completely fills the array size.

• printf() with the width and precision modifiers in the %s conversion specifier may be used to display a string.

• The %s format does not require the ampersand before the string name in scanf().

String Printing

#include <stdio.h>

int main()

{

char s[]=“Hello, World”;

printf(“>>%s<<\n”,s);

printf(“>>%20s<<\n”,s);

printf(“>>%-20s<<\n”,s);

printf(“>>%.4s<<\n”,s);

printf(“>>%-20.4s<<\n”,s);

printf(“>>%20.4s<<\n”,s);

return 0;

}

producing the output

>>Hello, World<<>> Hello, World<<>>Hello, World <<>>Hell<<>>Hell <<>> Hell<<

String Input

#include <stdio.h>int main(){char ch;char str[100];printf(“Enter any character \n”);scanf(“%c”, &ch);printf(“Entered character is %c \n”, ch);printf(“Enter any string ( upto 100 character ) \n”);scanf(“%s”, str);printf(“Entered string is %s \n”, str);}

Output

Enter any character

q

Entered character is q

Enter any string ( upto 100 character )

hello

Entered string is hello

String Manipulation

• C has the weakest character string capability of any general-purpose programming language.

• Strictly speaking, there are no character strings in C, just arrays of single characters that are really small integers.

• If s1 and s2 are such ‘strings’ a program cannot– assign one to the other: s1 = s2; <-Wrong– compare them like: s1 < s2; <-Wrong– concatenate them to form a single longer string: s1 +

s2; <-Wrong– return a string as the result of a function. return s1; <-Wrong

String Functions

S.N. Function & Purpose

1 strcpy(s1 , s2);Copies string s2 into string s1.

2 strcat(s1 , s2);Concatenates string s2 onto the end of

string s1.

3 strlen(s1);Returns the length of string s1.

4 strcmp(s1 , s2);Returns 0 if s1 and s2 are the same;

less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1 , ch);Returns a pointer to the first occurrence

of character ch in string s1.

6 strstr(s1 , s2);Returns a pointer to the first occurrence

of string s2 in string s1.

Write a program to check whether a given string is palindrome or not

#include <stdio.h>

#include <string.h>

int main()

{

char a[30];

int i,len,flag=0;

printf("\nENTER A STRING: ");

gets(a); //scanf("%s",a);

len=strlen(a);

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

{

if(a[i]==a[len-i-1])

flag=flag+1;

}

if(flag==len) printf("\nTHE STRING IS PALINDROME"); else printf("\nTHE STRING IS NOT PALINDROME"); return 0;}

/* OUTPUT:

ENTER A STRING: MASSAM

THE STRING IS PALINDROME

*/

The following program illustrates the comparison of two strings:

Putting strings together

Character Manipulation in the String

MULTIDIMENSIONAL ARRAYS

• Arrays with more than one dimension are called multidimensional arrays.

• An array of two dimensions can be declared as follows:– data_type array_name[size1][size2];

– Here, data_type is the name of some type of data, such as int. Also, size1 and size2 are the sizes of the array’s first and second dimensions, respectively.

• A three-dimensional array, such as a cube, can be declared as follows:– data_type array_name[size1][size2][size3]

Declaration of Two Dimensional Array

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

int a[2][3]={1,2,3,4,5,6}; //Gives Warning hence should not be used

int a[2][3];

int a[3][4];

#include <stdio.h> int main (){ /* an array with 5 rows and 2 columns*/ int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int i, j; /* output each array element's value */ for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 2; j++ ) { printf("a[%d][%d] = %d\n", i,j, a[i][j] ); } } return 0;}

Output

a[0][0]: 0a[0][1]: 0a[1][0]: 1a[1][1]: 2a[2][0]: 2a[2][1]: 4a[3][0]: 3a[3][1]: 6a[4][0]: 4a[4][1]: 8

0 0

1 2

2 4

3 6

4 8

Array a[5][2]

Transpose of a matrix

transp[3][3]mat[3][3]

row col rowcol

Transpose of Matrix

Write a program that uses a function to perform addition and subtraction of two matrices containing integer numbers.

#include <stdio.h>#define row 2#define col 3void mat_arith(int [][col], int [][col]); /* function prototype */int main(){

int a[row][col], b[row][col],i,j;printf("\n Enter the elements of the first matrix.\n");for(i=0; i<row; i++) /** Read first matrix elements **/

for(j=0; j<col; j++)scanf("%d",&a[i][j]);

printf("\n Enter the elements of the second matrix.\n");for(i=0; i<row; i++) /** Read second matrix elements **/

for(j=0; j<col; j++)scanf("%d",&b[i][j]);

mat_arith(a,b); /** function call **/}

void mat_arith(int a[][col], int b[row][])

{

int c[row][col],i,j,choice;

printf("\n For addition enter: 1 \n For subtraction enter: 2\n");

printf("\nEnter your choice: ");

scanf("%d",&choice);

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

for(j=0; j<col; j++)

{

if(choice==1)

c[i][j]= a[i][j] + b[i][j];

else if(choice==2)

c[i][j]= a[i][j] - b[i][j];

else

{

printf("\n Invalid choice. Task not done.");

return;

}

}printf("\n The resulting matrix is:\n ");

for(i=0; i<row; i++){

for(j=0; j<col; j++)printf("%d ", c[i][j]);

printf("\n\n ");}return;

}

Output Enter the elements of the first matrix.5 4 37 8 9

Enter the elements of the second matrix.9 8 76 5 4

For addition enter: 1 For subtraction enter: 2

Enter your choice: 1

The resulting matrix is: 14 12 10

13 13 13

ARRAYS OF STRINGS: TWO-DIMENSIONAL CHARACTER ARRAY

• A two-dimensional array of strings can be declared as follows:

<data_type> <string_array_name>[<row_size>] [<columns_size>];

• Consider the following example on declaration of a two-dimensional array of strings.

char s[5][30];

Initialization

• Two-dimensional string arrays can be initialized as shown– char s[5][10] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};

• which is equivalent to– s[0] C o w \0– S[1] G o a t \0– S[2] R a m \0– S[3] D o g \0– S[4] C a t \0

• Here every row is a string. That is, s[i] is a string. Note that the following declarations are invalid.– char s[5][] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};– char s[][] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};

Recommended