Nothing Special   »   [go: up one dir, main page]

0% found this document useful (0 votes)
28 views22 pages

CP Unit-III - RIT CSE

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

Programming For Problem Solving Using C

UNIT-III
ARRAY: An array is a group of related data items that share a common name and stored in
contiguous memory locations.
Arrays offer a convenient means of grouping together several related variables, in one
dimension or more dimensions. An array is also known as subscripted variable. Before using an
array its type and dimension must be declared. The elements are always stored in contiguous
memory locations. First element is at position „0‟, so the last element is at position 1 less than the
size of the array.

Examples:
product part numbers:
int part_numbers[ ] = {123, 326, 178, 1209};
student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};

One-Dimensional Arrays
A one-dimensional array is a list of related variables. The general form of a one-dimensional
array declaration is:

type variable_name [size]

type : base type of the array, determines the data type of each element in the array
size: how many elements the array will hold
variable_name : the name of the array

Examples:
int sample[10];
float float_numbers[100];
char last_name[40];

Initialization of arrays:
We can initialize the elements of an array in the same way as the ordinary variables when they
are declared.
type array-name [size] = {list of values};
The values in the list are separated by commas. If the number of values in the list is less than the
size, then only that many elements will be initialized. The remaining elements will be set to zero
automatically.

Ex.
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};

CSE, RIT Page 1


ACCESSING ELEMENTS OF AN ARRAY:
Once an array is declared, the individual elements of the array can be referred by the use of
subscript. Subscript specifies the element position in the array. Subscript starts at 0. i.e. first
number is started at position 0, second number is started at position 1 etc.

Entering data into an array


int num[10];
for (i=0; i<10; i++)
{
printf (“enter a number”);
scanf (“%d”, & num [i]);
}
Reading data from an array
To add the elements of an array to variable sum
sum=0;
for (i=0; i<10; i++)
sum = sum + a [i];

EXAMPLES

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

CSE, RIT Page 2


Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

Example 2 (finding minimum and maximum element of an array)

#include<stdio.h>

int main()
{
int my_arr[100];
int n,i, max, min;
printf(“enter the number of elements of the array”);
scanf(“%d”, &n);
printf(“Enter elements into the array”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
max = min = my_arr[0];

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


{
// if value of current element is greater than previous value
// then assign new value to max
if(my_arr[i] > max)
{
max = my_arr[i];
}

// if the value of current element is less than previous element


// then assign new value to min
if(my_arr[i] < min)
{
min = my_arr[i];
}
}

printf("Lowest value = %d\n", min);


printf("Highest value = %d", max);

// signal to operating system everything works fine


return 0;
}
CSE, RIT Page 3
Output:
Enter the number of elements in the array: 5
Enter the elements into the array: 10 34 56 98 33
Lowest value= 10
Highest value= 98

Example-3 ( C Program to Print Even and Odd numbers of an array)


#include<stdio.h>
int main()
{
int n, a[20];

printf("Enter the size of the array: ");


scanf("%d", &n);

printf("Enter array elements: \n");


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

printf("Even numbers in the array are: \n");


for(int i=0; i<n; i++)
{
if(a[i]%2==0)
printf("%d ", a[i]);
}

printf("\nOdd numbers in the array are: \n");


for(int i=0; i<n; i++)
{
if(a[i]%2!=0)
printf("%d ", a[i]);
}

return 0;
}
OUTPUT:
Enter the size of the array: 5
Enter array elements:
10
15
20
54
26
Even numbers in the array are:
CSE, RIT Page 4
10 20 54 26
Odd numbers in the array are:
15

EXAMPLE-4 ( C PROGRAM TO SORT ELEMENTS OF AN ARRAY IN ASCENDING


ORDER)

#include <conio.h>
int main()
{
int a[10000],i,n,j,temp;

printf("Enter size of the array : ");


scanf("%d", &n);
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}

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


{

for(j=0; j<n-i-1; j++)


{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}

}
printf("\narray elements in ascending order:\n ");

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


{
printf("%d ",a[i]);
}

CSE, RIT Page 5


Output:

Enter size of the array: 5


Enter elements in array: 1
0
-5
25
-10

array elements in ascending order:


-10 -5 0 1 25

APPLICATIONS OF ARRAYS
1) Array stores data elements of the same data type.
2) Maintains multiple variable names using a single name. Arrays help to maintain large data
under a single variable name. This avoid the confusion of using multiple variables.
3) Arrays can be used for sorting data elements. Different sorting techniques like Bubble sort,
Insertion sort, Selection sort etc use arrays to store and sort elements easily.
4) Arrays can be used for performing matrix operations. Many databases, small and large, consist
of one-dimensional and two-dimensional arrays whose elements are records.
5) Arrays can be used for CPU scheduling.
6) Arrays are also used to implement other data structures like Stacks, Queues, Heaps, Hash
tables etc.

TWO-DIMENSIONAL ARRAYS
So far we have looked at arrays with only one dimension. It is also possible for arrays to have
two or more dimensions. The two dimensional array is also called a matrix.

Consider the following data table


Sub1 Sub2 Sub3 Sub4
Student1 10 20 30 40
Student2 5 7 8 15
Student3 3 2 4 50

The table contains a total of 12 values, i.e in each line. We can think of this table as a matrix
consisting of 3 rows and 4 columns. Each row represents the marks obtained in 4 subjects by a
particular student. Each column represents the marks obtained in a particular subject.
In mathematics, we represent a particular value in a matrix by using two subscripts, such as vij.
Here v denotes the entire matrix and vij refers to the value in the ith row and jth column.
For example in the above table v23 refers to the value 50. C allows us to define such tables of
items by using two-dimensional arrays, the above table can be defined in C as
int v[3][4];

Declaring Two dimensional array:


CSE, RIT Page 6
type array_name [row-size] [col-size];

ex: int A[3][2];

This array A consists of 3 rows and 2 columns and 6 elements altogether.


Initilization:
Like Single dimensional arrays the initialization can be done in two dimensional arrays. The
general form is
Syntax:
Type Arrayname [row size][col size]={list of values};

Ex. int A[3][2]={{1,2},{3,4},{5,6}};

This declares an Array with 3 rows and 2 columns.


Array looks like the below matrix
12
34
56

If the values are missing in an initializer, they are automatically set to zero. For instance the
statement static int num[2][3] = {{1,1},{2}};
will initialize the first two elements of the first row to one, the first element of the second row to
two. And all other elements to zero.

Array elements in Memory:

Consider the following array declaration


int a[3][3];
12 22 23
a= 33 11 13
14 15 11
This declaration allots 18 bytes in memory as each integer occupies 2 bytes. i.e 9* 2=18. The
elements are stored in contiguous memory locations in the order of row. That means all the
elements in first row and then next row elements follows. The arrangement of memory for the
above examples.

a[0][0] a[0][1] A[0][2] a[[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2]

12 22 23 33 11 13 14 15 11

1002 1004 1006 1008 1010 1012 1014 1016 1018

.Ex: Matrix Addition Program

CSE, RIT Page 7


/* program to add two matrices */
#include<stdio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],m,n,i,j;
printf("enter a size of the array :" );
scanf("%d%d",&m,&n);
printf("enter the elements of matrix A\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("enter the elements of matrix B\n");
for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&b[i][j]);
for (i=0;i<m;i++)
for (j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("The two dimensional array\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ",c[i][j]);
printf("\n");
}
return 0;
}

Ex: Matrix Multiplication Program


#include<stdio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
clrscr();
printf("enter a size of the array A:" );
scanf("%d%d",&m,&n);
printf("enter the elements of matrix A\n");

for (i=0;i<m;i++)
for (j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("enter a size of the array B:" );
scanf("%d%d",&p,&q);
printf("enter the elements of matrix B\n");
for (i=0;i<p;i++)
for (j=0;j<q;j++)
CSE, RIT Page 8
scanf("%d",&b[i][j]);
if (n==p)
{
for (i=0;i<m;i++) /*initialisation of C*/
for (j=0;j<q;j++)
c[i][j]=0;

for (i=0;i<m;i++)
for (j=0;j<q;j++)
for (k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
printf("The Resultant array\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d ",c[i][j]);
printf("\n");
}
}
else
printf("Matrix multiplication is not possible\n");
}

C PROGRAM TO FIND TRANSPOSE OF A MATRIX

#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);

// asssigning elements to the matrix


printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

// printing the matrix a[][]


printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
CSE, RIT Page 9
}

// computing the transpose


for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}

// printing the transpose


printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}

OUTPUT:
Enter rows and columns: 2
3

Enter matrix elements:


Enter element a11: 1
Enter element a12: 4
Enter element a13: 0
Enter element a21: -5
Enter element a22: 2
Enter element a23: 7

Entered matrix:
1 4 0
-5 2 7

Transpose of the matrix:


1 -5
4 2
0 7

STRINGS:

A string is an array of characters. Any group of characters defined between double quotation
marks is a constant string.
Ex.
“c programming”
CSE, RIT Page 10
“Rama is a good boy”
Declaration:
char string_name[size];
A string variable is any valid C variable and is always declared as an array. The size determines
the number of characters in the string.
char city[10];
char name[20];
When the compiler assigns a character string to a character array, it automatically supplies a null
character („\0‟) at the end of the string. Therefore the size should be equal to the maximum
number of character in the string plus one. Character array may be initialized when they are
declared. C permits a character array to be initialized in either of the following two forms.

static char city [7] = {„g‟,‟u‟,‟n‟,‟t‟,‟u‟,‟r‟,‟\0‟};


city[7] = “guntur”;

The reason that city had to be 7 elements long is that the string „guntur‟ contains 6 characters and
one element space is provided for the null terminator.
C also permits us to initialize a character array without specifying the number of elements. In
such cases, the size of the array will be determined automatically based on the number of
elements initialized. For example
static char string [ ] = {„g‟,‟o‟,‟o‟,‟d‟,‟\0‟}
defines the array string as a five element array.

Reading strings from terminal:


The input function scanf() can be used with %s format specification to read in a string of
characters.
char address[15];
scanf(“%s”,address);

Note that unlike previous scanf() calls, in the case of character arrays, the ampersand (&) is not
required before the variable name.
The scanf() function automatically terminates the string that is read with a null character and
therefore the character

STRING INPUT OUTPUT FUNCTIONS


The following are the input and output functions of strings in c

Input functions: scanf(), gets()


Output functions: printf(), puts()

The scanf() and printf() are generic i/o functions that they support all built-in data types such as
int, float, long, double, strings,..etc. But gets() and puts() are specialized to scan and print only
string data. There is a little difference between scanf() and gets(), while reading string from
keyboard, the scanf() accepts character by character from keyboard until either a new line („\n‟)
or blank space is found, which ever comes earlier. Whereas “gets()” accepts until a newline is

CSE, RIT Page 11


found. That is it accepts white spaces & tab also, these input functions append a null character at
end of string, the formatted string %s is used in printf() and scanf().for example :

The scanf() function consider the jack and Jill as 3 strings, whereas gets() considers as single
string. In case to scan total string using scanf(), then it should be scanf(“%s%s%s”,
a,b,c); here a,b,c are three arrays.
The printf() and puts() is work in similar way. All I/O functions take first byte address (base
address of array) as argument and prints the given string using pointer.
Program : The following program is an example of string I/O functions.
#include<stdio.h>
#include<string.h>
int main()
{
char name[30];
printf(“Enter name: “);
gets(name); //Function to read string from user.
printf(“Name: “);
puts(name); //Function to display string.
return 0;
}
Output :
Enter name: INDIA IS A GREAT COUNTRY
Name: INDIA IS A GREAT COUNTRY

CSE, RIT Page 12


STRING HANDLING FUNCTIONS:

strcat() -- concatenates two strings.


strcmp() -- compares two strings.
strcpy() -- copies one string over another.
strlen() -- finds the length of the string.
strlwr()-Converts string to lower case
strupr()-Converts string to uppercase

ARRAYS OF STRINGS:
A string is a 1-D array of characters, so an array of strings is a 2-D array of characters. Just like
we can create a 2-D array of int, float etc; we can also create a 2-D array of character or array
of strings. Here is how we can declare a 2-D array of characters.
char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};

It is important to end each 1-D array by the null character, otherwise, it will be just an
array of characters. We can't use them as strings.

Declaring an array of strings this way is rather tedious, that's why C provides an
alternative syntax to achieve the same thing. This above initialization is equivalent to:

char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};

The first subscript of the array i.e 3 denotes the number of strings in the array and the
second subscript denotes the maximum length of the string. Recall the that in C, each
character occupies 1 byte of data, so when the compiler sees the above statement it
allocates 30 bytes (3*10) of memory.

We already know that the name of an array is a pointer to the 0th element of the array.
Can you guess the type of ch_arr?

The ch_arr is a pointer to an array of 10 characters or int(*)[10].

CSE, RIT Page 13


Therefore, if ch_arr points to address 1000 then ch_arr + 1 will point to address 1010.

From this, we can conclude that:

ch_arr + 0 points to the 0th string or 0th 1-D array.


ch_arr + 1 points to the 1st string or 1st 1-D array.
ch_arr + 2 points to the 2nd string or 2nd 1-D array.

In general, ch_arr + i points to the ith string or ith 1-D array.

We know that when we dereference a pointer to an array, we get the base address of
the array. So, on dereferencing ch_arr + i we get the base address of the 0th 1-D
array.

We know that when we dereference a pointer to an array, we get the base address of
the array. So, on dereferencing ch_arr + i we get the base address of the 0th 1-D
array.

From this we can conclude that:

*(ch_arr + 0) + 0 points to the 0th character of 0th 1-D array (i.e s)


*(ch_arr + 0) + 1 points to the 1st character of 0th 1-D array (i.e p)
*(ch_arr + 1) + 2 points to the 2nd character of 1st 1-D array (i.e m)

CSE, RIT Page 14


The following program demonstrates how to print an array of strings.

#include<stdio.h>

int main()
{
int i;

char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};

printf("1st way \n\n");

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


{
printf("string = %s \t address = %u\n", ch_arr + i, ch_arr + i);
}

// signal to operating system program ran fine


return 0;
}
Expected Output:

1 string = spike address = 2686736


2 string = tom address = 2686746
3 string = jerry address = 2686756

STRCAT():

strcat(str1, str2)
The strcat() function joins two strings together. Str1 and str2 are character arrays.
When the function strcat() is executed, str2 is appended to str1. It removes the „\0‟ at the end of
the string, and places str2 from there.

#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"sastry"};
char str[20];
clrscr();
printf("strings before concatenation\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);

CSE, RIT Page 15


strcat(str1,str2);
printf("strings After concatenation\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
getch();
}

STRCMP():

The strcmp() function compares two strings identified by the arguments and has a value 0 if they
are equal. If they are not equal, it has the numeric difference between the first non-matching
characters in the strings.

strcmp(str1, str2)

#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"ezra"};
char str[20];
clrscr();
printf("strings before comparision\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
if (strcmp(str1,str2)==0)
printf("strings are same\n");
else
printf("strings are different\n");
getch();
}

STRCPY():

strcpy(str1, str2);
Assigns the content of str2 to str1.

#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"sastry"};
char str[20];
clrscr();
CSE, RIT Page 16
printf("strings before copy\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
strcpy(str1,str2);
printf("strings after copy\n");
printf("str1=%s\n",str1);
printf("str2=%s\n",str2);
getch();
}

STRLEN():

Counts and returns the number of characters in string.


n = strlen(str);

#include <stdio.h>
#include <conio.h>
void main()
{
static char str1[10]={"ezra"};
static char str2[10]={"sastry"};
int n;
clrscr();
n=strlen(str1);
printf("length of string %s is %d\n",str1,n);
n=strlen(str2);
printf("length of string %s is %d\n",str2,n);
getch();
}

Ex: Program to check whether a given string is palindrome or not. (WITHOUT USING
STRING HANDLING FUNCTIONS)
#include<stdio.h>
int main()
{
char a[20],b[20];
int i,n=0,flag=0;
printf(“\n Enter a string”);
scanf(“%s”,a);
n=strlen(a);
for (i=0;i<n;i++)
{
b[i]=a[n-(i+1)];
}
for (i=0;i<n;i++)
{
CSE, RIT Page 17
if (b[i]!=a[i])
flag=1;
}
if (flag==1)
printf(“\n %s is not palindrome”,a);
else
printf(“\n %s is palindrome”,a);
}

Output:

Enter a string: MALAYALAM

string is palindrome

EXAMPLE: CHECK WHETHER A STRING IS PALLINDROM OR NOT (USING


STRING HANDLING FUNCTIONS)

#include <stdio.h>
#include <string.h>
int main()
{
char s1[1000],s2[1000];
printf("Enter the string: ");
gets(s1);
strcpy(s2,s1);
strrev(s2);
if(!strcmp(s1,s2))
printf("string is palindrome");
else
printf("string is not palindrome");
return 0;
}

Output:

CSE, RIT Page 18


Enter the string: MALAYALAM

string is palindrome

Example: Write a program in C to find the length of a string without using


library function.

#include <stdio.h>

#include <stdlib.h>

void main()

char str[100]; /* Declares a string of size 100 */

int l= 0;

printf("\n\nFind the length of a string :\n");

printf("---------------------------------\n");

printf("Input the string : ");

fgets(str, sizeof str, stdin);

while(str[l]!='\0')

l++;

printf("Length of the string is : %d\n\n", l-1);

CSE, RIT Page 19


OUTPUT:

find the length of a string :

---------------------------------

Input the string : COMPUTER SCIENCE

Length of the string is : 17

Example: (Write a program in C to count the total number of words in a string.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define str_size 100 //Declare the maximum size of the string
void main()
{
char str[str_size];
int i, wrd;
printf("\n\nCount the total number of words in a string :\n");
printf("------------------------------------------------------\n");
printf("Input the string : ");
fgets(str, sizeof str, stdin);
i = 0;
wrd = 1;
/* loop till end of string */
while(str[i]!='\0')
{
/* check whether the current character is white space or new line or tab character*/
if(str[i]==' ' || str[i]=='\n' || str[i]=='\t')
{

CSE, RIT Page 20


wrd++;
}

i++;
}
printf("Total number of words in the string is : %d\n", wrd-1);
}

OUTPUT:
Count the total number of words in a string :
------------------------------------------------------
Input the string : India is a great country
Total number of words in the string is : 5

Example: Write a program in C to count total number of alphabets, digits and special
characters in a string.

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#define str_size 100 //Declare the maximum size of the string

void main()

char str[str_size];

int alp, digit, splch, i;

alp = digit = splch = i = 0;

CSE, RIT Page 21


printf("\n\nCount total number of alphabets, digits and special characters :\n");

printf("--------------------------------------------------------------------\n");

printf("Input the string : ");

fgets(str, sizeof str, stdin);

/* Checks each character of string*/

while(str[i]!='\0')
{
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
{
alp++;
}
else if(str[i]>='0' && str[i]<='9')
{
digit++;
}
else
{
splch++;
}
i++;
}
printf("Number of Alphabets in the string is : %d\n", alp);
printf("Number of Digits in the string is : %d\n", digit);
printf("Number of Special characters in the string is : %d\n\n", splch);
}

OUTPUT:
Count total number of alphabets, digits and special characters :
--------------------------------------------------------------------
Input the string : Welcome to VISAKHA-6
Number of Alphabets in the string is : 16
Number of Digits in the string is : 1
Number of Special characters in the string is : 4

CSE, RIT Page 22

You might also like