Array Programs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

Program to read and Display ARRAY elements

#include<stdio.h>

int main() {
int i, arr[50], num;

printf("\nEnter no of elements :");


scanf("%d", &num);

//Reading values into Array


printf("\nEnter the values :");
for (i = 0; i < num; i++) {
scanf("%d", &arr[i]);
}

//Printing of all elements of array


for (i = 0; i < num; i++) {
printf("\narr[%d] = %d", i, arr[i]);
}

return (0);
}

Copying Elements of one Arry into another Array


#include<stdio.h>

int main() {
int arr1[30], arr2[30], i, num;

printf("\nEnter no of elements :");


scanf("%d", &num);

//Accepting values into Array


printf("\nEnter the values :");
for (i = 0; i < num; i++) {
scanf("%d", &arr1[i]);
}
/* Copying data from array 'a' to array 'b */
for (i = 0; i < num; i++) {
arr2[i] = arr1[i];
}

//Printing of all elements of array


printf("The copied array is :");
for (i = 0; i < num; i++)
printf("\narr2[%d] = %d", i, arr2[i]);

return (0);
}

Reversal of an Array
#include<stdio.h>

int main() {
int arr[30], i, j, num, temp;

printf("\nEnter no of elements : ");


scanf("%d", &num);

//Read elements in an array


for (i = 0; i < num; i++) {
scanf("%d", &arr[i]);
}

j = i - 1; // j will Point to last Element


i = 0; // i will be pointing to first element

while (i < j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++; // increment i
j--; // decrement j
}
//Print out the Result of Insertion
printf("\nResult after reversal : ");
for (i = 0; i < num; i++) {
printf("%d \t", arr[i]);
}

return (0);
}

1 Enter no of elements : 5
2 11 22 33 44 55
3 Result after reversal : 55 44 33 22 11

Find Largest Element in Array

#include<stdio.h>

int main() {
int a[30], i, num, largest;

printf("\nEnter no of elements :");


scanf("%d", &num);

//Read n elements in an array


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

//Consider first element as largest


largest = a[0];

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


if (a[i] > largest) {
largest = a[i];
}
}

// Print out the Result


printf("\nLargest Element : %d", largest);

return (0);
}
Output:
Enter no of elements : 5
11 55 33 77 22
Largest Element : 77

Addition of All Elements of the Array

#include<stdio.h>

int main() {
int i, arr[50], sum, num;

printf("\nEnter no of elements :");


scanf("%d", &num);

//Reading values into Array


printf("\nEnter the values :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);

//Computation of total
sum = 0;
for (i = 0; i < num; i++)
sum = sum + arr[i];

//Printing of all elements of array


for (i = 0; i < num; i++)
printf("\na[%d]=%d", i, arr[i]);

//Printing of total
printf("\nSum=%d", sum);

return (0);
}
Output:
Enter no of elements : 3
Enter the values : 11 22 33
a[0]=11
a[1]=22
a[2]=33
Sum=66

To delete duplicate elements in an array


#include<stdio.h>

int main() {
int arr[20], i, j, k, size;

printf("\nEnter array size : ");


scanf("%d", &size);

printf("\nAccept Numbers : ");


for (i = 0; i < size; i++)
scanf("%d", &arr[i]);

printf("\nArray with Unique list : ");


for (i = 0; i < size; i++)
{
for (j = i + 1; j < size;)
{
if (arr[j] == arr[i])
{
for (k = j; k < size; k++)
{
arr[k] = arr[k + 1];
}
size--;
}
Else
j++;
}
}
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}

return (0);
}
Output:
Enter array size : 5
Accept Numbers : 1 3 4 5 3
Array with Unique list : 1 3 4 5

Searching an elements in ARRAY


Linear search c program
#include <stdio.h>

int main()
{
int array[100], search, c, n;

printf("Enter the number of elements in array\n");


scanf("%d",&n);

printf("Enter %d integer(s)\n", n);

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


scanf("%d", &array[c]);

printf("Enter the number to search\n");


scanf("%d", &search);

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


{
if (array[c] == search) /* if required element found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d is not present in array.\n", search);

return 0;
}

Sorting an array elements


void bubbleSort( int a[], int size )
{
int hold; // temporary location used to swap elements
// loop to control number of passes
for ( int pass = 1; pass < size; pass++ )
// loop to control number of comparisons per pass
for ( int j = 0; j < size - 1; j++ )
// swap elements if out of order
if ( a[ j ] > a[ j + 1 ] ) {
hold = a[ j ];
a[ j ] = a[ j + 1 ];
a[ j + 1 ] = hold;
} // end if
} // end function b

Exercise:
Find the smallest element in an array
Find Reverse of an array

Two Dimensional Array

Reading and Displaying Elements of 2D array


#include <stdio.h>

void main()
{
int i, j;
char a[3][4];
for(i = 0; i <= 2; i = i + 1)
for(j = 0; j <= 3; j = j + 1)
scanf(" %c", &a[i][j]);
for(i = 0; i <= 2; i = i + 1)
{
for(j = 0; j <= 3; j = j + 1)
printf("a[%d][%d] = %c\t", i, j, a[i][j]);
printf("\n");
}
}

C program to add two matrix

#include <stdio.h>

int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);

printf("Enter the elements of second matrix\n");

for (c = 0; c < m; c++)


for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);

printf("Sum of entered matrices:-\n");


for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}

return 0;
}

Show the output for each of the following programs. Use the following sample
array data:

int a[3][3] = {10, 20, 30, 40, 50, 60, 70, 80, 90};

#include <stdio.h>

void main()
{
int i, j;
int a[3][3] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
for(i = 0; i <= 2; i = i + 1)
{
for(j = 0; j <= 2; j = j + 1)
printf("a[%d][%d] = %d\t", i, j, a[i][j]);
printf("\n");
}
}

#include <stdio.h>

void main()
{
int i, j;
int a[3][3] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
for(i = 0; i <= 2; i = i + 1)
{
for(j = 0; j <= 2; j = j + 1)
printf("a[%d][%d] = %d\t", j, i, a[j][i]);
printf("\n");
}
}

#include <stdio.h>

void main()
{
int i, j;
int a[3][3] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
for(i = 0; i <= 2; i = i + 1)
{
for(j = 0; j <= 2; j = j + 1)
printf("a[%d][2 - %d] = %d ", i, j, a[i][2 - j]);
printf("\n");
}
}

#include <stdio.h>

void main()
{
int i, j;
int a[3][3] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
for(i = 0; i <= 2; i = i + 1)
{
for(j = 2; j >= 0; j = j - 1)
printf("a[2][%d] = %d\t", j, a[2][j]);
printf("\n");
}
}
Matrix multiplication

#include <stdio.h>

int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];

printf("Enter the number of rows and columns of first matrix\n");


scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);

printf("Enter the number of rows and columns of second matrix\n");


scanf("%d%d", &p, &q);

if (n != p)
printf("Matrices with entered orders can't be multiplied with each other.\n");
else
{
printf("Enter the elements of second matrix\n");

for (c = 0; c < p; c++)


for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

printf("Product of entered matrices:-\n");

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);

printf("\n");
}
}

return 0;
}

Find the Trace & Normal of a given Matrix


void main ()
{
static int array[10][10];
int i, j, m, n, sum = 0, sum1 = 0, a = 0, normal;

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


scanf("%d %d", &m, &n);
printf("Enter the n coefficients of the matrix \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
a = array[i][j] * array[i][j];
sum1 = sum1 + a;
}
}
normal = sqrt(sum1);
printf("The normal of the given matrix is = %d\n", normal);
for (i = 0; i < m; ++i)
{
sum = sum + array[i][i];
}
printf("Trace of the matrix is = %d\n", sum);
}

Program to find addition of Lower Triangular Elements of a matrix


#include<stdio.h>
#include<conio.h>

int main() {
int i, j, a[10][10], sum, rows, columns;

printf("\nEnter the number of Rows : ");


scanf("%d", &rows);

printf("\nEnter the number of Columns : ");


scanf("%d", &columns);

//Accept the Elements in Matrix


for (i = 0; i < rows; i++)
for (j = 0; j < columns; j++) {
printf("\nEnter the Element a[%d][%d] : ", i, j);
scanf("%d", &a[i][j]);
}

//Addition of all Diagonal Elements


sum = 0;
for (i = 0; i < rows; i++)
for (j = 0; j < columns; j++) {
// Condition for Lower Triangle
if (i > j) {
sum = sum + a[i][j];
}
}
//Print out the Result
printf("\nSum of Lower Triangle Elements : %d", sum);
return (0);
}

Calculating grades of N students from 3 tests

#include<stdio.h>
Void main()
{
Int I,j,k,n,m;
Int s[50][50],sum,avg,sub;
Char grade[50];
Printf(Enter The No.of Studens\n);
Scanf(%d,&n);

Printf(Enter The No.of subjects\n);


Scanf(%d,&sub);

For(i=0;i<n;i++)
{
Sum=0;
Printf(Enter subject marks of student %d:\n,i+1);

For(j=0;j<sub;j++)
{
Scanf(%d,&s[i][j]);
Sum=sum+ s[i][j];
}
Avg=sum/sub;
S[i][j]=avg;

If(avg >80)
Grade[i]=A;
Elseif(avg>60)
Grade[i]=B;
Elseif(avg>50)
Grade[i]=C;
Else
Grade[i]=U;

Printf(\n S.No Scores Average Grade);


Printf(\n-------------------------------------------------------------);
For(i=0;i<n;i++)
{
For(j=0;j<sub+1;j++)
{
Printf(%d\t%10d\t%6d,i,s[i][j],grade[i]);
}
}
Printf(\n-------------------------------------------------------------);
}

Exercise:
Find sum of row elements of a matrix
Find sum of column elements of a matrix
Transpose of a matrix

Three Dimensional Array

#include<stdio.h>
#include<conio.h>

void main()
{
int i, j, k, x=1;
int arr[3][3][3];
clrscr();

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
scanf("%d",&arr[i][j][k]);
}
}
}

printf(":::3D Array Elements:::\n\n");

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
arr[i][j][k] = x;
printf("%d\t",arr[i][j][k]);
x++;
}
printf("\n");
}
printf("\n");
}
getch();
}

Passing array to a Function

1 . Pass Entire array


Here entire array can be passed as a argument to function .
Function gets complete access to the original array .
While passing entire array Address of first element is passed to function ,
any changes made inside function , directly affects the Original value .
Function Passing method : Pass by Address

2 . Pass Array element by element


Here individual elements are passed to function as argument.
Duplicate carbon copy of Original variable is passed to function .
So any changes made inside function does not affects the original value.
Function doesnt get complete access to the original array element.
Function passing method is Pass by Value

C Program to Pass Array to Function Element by Element :


#include< stdio.h>
#include< conio.h>
//---------------------------------
void fun(int num)
{
printf("\nElement : %d",num);
}

void main()
{
int arr[5],i;
clrscr();
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);

printf("\nPassing array element by element.....");

for(i=0;i< 5;i++)
fun(arr[i]);

getch();
}

A program to pass an array containing age of person to a function. This function


should find average age and display the average age in main function.

#include <stdio.h>
float average(float a[]);
int main()
{
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
return 0;
}
float average(float a[]){
int i;
float avg, sum=0.0;
for(i=0;i<6;++i){
sum+=a[i];
}
avg =(sum/6);
return avg;
}

Example to pass two-dimensional arrays to function

#include
void Function(int c[2][2]);
int main()
{
int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
scanf("%d",&c[i][j]);
}
Function(c); /* passing multi-dimensional array to function */
return 0;
}

void Function(int c[2][2])


{
/* Instead to above line, void Function(int c[][2]){ is also valid */
int i,j;
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\n",c[i][j]);
}

Character Array and Strings


string is a sequence of characters that is treated as a single data item and terminated
by null character \0.

For example : The string "hello world" contains 12 characters


including '\0' character which is automatically added by the compiler at the end of
the string.

Declaring and Initializing a string variables

char name[10]="StudyTonight"; //valid character array initialization

char name[]={'L','e','s','s','o','n','s','\0'};
char str[4];
str="hell";

Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is that,
strings are of char type.

char s[5];

Initialization of strings
In C, string can be initialized in different number of ways.

char c[]="abcd";

OR,

char c[5]="abcd";
OR,

char c[]={'a','b','c','d','\0'};

OR;

char c[5]={'a','b','c','d','\0'};

Reading words from user.

char c[20];

scanf("%s",c);

String variable c can only take a word. It is because when white space is
encountered, the scanf()function terminates.

Write a C program to illustrate how to read string from terminal.


#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}
Output

Enter name: Dennis Ritchie

Your name is Dennis.

Here, program will ignore Ritchie because, scanf() function takes only string
before the white space.
Reading a line of text
C program to read line of text manually.
#include <stdio.h>
int main(){
char name[30],ch;
int i=0;
printf("Enter name: ");
while(ch!='\n') // terminates if user hit enter
{
ch=getchar();
name[i]=ch;
i++;
}
name[i]='\0'; // inserting null character at end
printf("Name: %s",name);
return 0;
}
This process to take string is tedious. There are predefined
functions gets() and puts in C language to read and display string
respectively.
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;
}

Reading String and Displaying

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
clrscr();
printf("Enter a string");
scanf(%[^\n],str); Edit set conversion
printf("%s",str);
getch();
}

char text[20];
gets(text);
printf("%s",text);

-getchar()
-putchar(ch)

-gets(str);
-puts(str);

ARITHMETIC OPERATIONS ON CHARACTERS

1. Char x=a;
Printf(%d,x);

2. X=y-1;
3. Char ch;
Ch>=A && ch<=z

4. Converting character digit into integer digit


Char cdigit[]=1999;
Int ndigit;
Ndigit=atoi(cdigit);

STRING FUNCTIONS
There are numerous functions defined in "string.h" header file. Few
commonly used string handling functions are discussed below:
Strings handling functions are defined under "string.h" header file, i.e, you
have to include the code below to run string handling functions.

strchr(mystr, 'f')

strrchr(mystr, 'f')

strstr(inputstr, 'Begi')

p2 = strdup(p1);

strnset(str,'#',4)
String Handling Functions
These functions are packaged in string.h library. Hence, you must include string.h
header file in your program to use these functions.

strcat(string1,string2) function
strcat("hello","world");
strcat() function will add the string "world" to "hello".

strlen(string) function
strlen() function will return the length of the string passed to it.
int j;
j=strlen("studytonight");
printf("%d",j);
output :
12

strcmp() function
strcmp(str1,str2) function will return the ASCII difference between first
unmatching character of two strings.
int j;
j=strcmp("study","tonight");
printf("%d",j);
output:
-1

Strcpy(string1,string2)

Strncpy(string1,string2,n)
Strncmp(string1,stirng2,n)
Strncat(string1,string2,n)
Strstr(string1,string2)
Source Code to Find Number of Vowels, Consonants, Digits and White Space
Character

#include<stdio.h>
int main(){
char line[150];
int i,v,c,ch,d,s,o;
o=v=c=ch=d=s=0;
printf("Enter a line of string:\n");
gets(line);
for(i=0;line[i]!='\0';++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' ||
line[i]=='A' || line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U')
++v;
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
++c;
else if(line[i]>='0'&&c<='9')
++d;
else if (line[i]==' ')
++s;
}
printf("Vowels: %d",v);
printf("\nConsonants: %d",c);
printf("\nDigits: %d",d);
printf("\nWhite spaces: %d",s);
return 0;
}

Program to perform String Functions

#include <stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
int length(char str[]);
void reverse(char str[]);
int palindrome(char str[]);
void copy(char str1[], char str2[]);
int compare(char str1[], char str2[]);
void concat(char str1[], char str2[]);
void search(char str1[], char str2[]);
void count(char str1[]);

void main() {
char a[100], b[100];
int result, option;
do {
printf("\n1.Length of a string");
printf("\n2.Reverse the Given String");
printf("\n3.Check for Palindrome");
printf("\n4.Copy");
printf("\n5.String Comparison");
printf("\n6.String Concatenation");
printf("\n7.String Searching");
printf("\n8.Counting of Words,Characters & Special Characters");
printf("\n9.Quit");
printf("\n\nEnter Your Choice:");
scanf("%d", &option);

flushall();
switch (option) {
case 1:
printf("\nEnter a String:");
gets(a);
result = length(a);
printf("\nLength of %s=%d", a, result);
printf("\nPress a Character");
getch();
break;

case 2:
printf("\nEnter a String:");
gets(a);
reverse(a);
printf("\nResult=%s", a);
printf("\nPress a Character");
getch();
break;

case 3:
printf("\n Enter a String:");
gets(a);
result = palindrome(a);
if (result == 0)
printf("\nNot a palindrome");
else
printf("\nA palindrome");
printf("\nPress a Character");
getch();
break;

case 4:
printf("\nEnter a String:");
gets(a);
copy(b, a);
printf("\nResult=%s", b);
printf("\nPress a Character");
getch();
break;

case 5:
printf("\nEnter 1st string:");
gets(a);
printf("\nEnter 2nd string:");
gets(b);
result = compare(a, b);
if (result == 0)
printf("\nboth are same");
else if (result > 0)
printf("\n1st>2nd");
else
printf("\n1st<2nd");
printf("\nPress a Character");
getch();
break;

case 6:
printf("\nEnter 1st string:");
gets(a);
printf("\nEnter 2nd string:");
gets(b);
concat(a, b);
printf("\nresult=%s", a);
printf("\nPress a Character");
getch();
break;

case 7:
printf("\nEnter 1st string:");
gets(a);
printf("\nEnter 2nd string:");
gets(b);
search(a, b);
printf("\nPress a Character");
getch();
break;

case 8:
printf("\nEnter a string:");
gets(a);
count(a);
printf("\nPress a Character");
getch();
break;

default:
printf("\nInvalid Choice:");
break;
}

} while (option != 9);


}
// Implementation of strlen() function
int length(char str[]) {
int i = 0;
while (str[i] != '\0')
i++;
return (i);
}

// Implementation of strrev() function

void reverse(char str[]) {


int i, j;
char temp;
i = j = 0;
while (str[j] != '\0')
j++;
j--;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}

// Implementation to check a string is palindrome or not function

int palindrome(char str[]) {


int i, j;
i = j = 0;
while (str[j] != '\0')
j++;
while (i < j) {
if (str[i] != str[j - 1])
return (0);
i++;
j--;
}
return (1);
}
// Implementation of strcpy() function

void copy(char str2[], char str1[]) {


int i = 0;
while (str1[i] != '\0') {
str2[i] = str1[i];
i++;
}
str2[i] = '\0';
}

// Implementation of strcmp() function

int compare(char str1[], char str2[]) {


int i;
i = 0;
while (str1[i] != '\0') {
if (str1[i] > str2[i])
return (1);
if (str1[i] < str2[i])
return (-1);
i++;
}
return (0);
}

// Implementation of strcat() function

void concat(char str1[], char str2[]) {


int i, j;
i = 0;
while (str1[i] != '\0')
i++;
for (j = 0; str2[j] != '\0'; i++, j++)
str1[i] = str2[j];
str1[i] = '\0';
}
// Implementation of strstr() function

void search(char str1[], char str2[]) {


int i, j, lena, lenb;
for (lena = 0; str1[lena] != '\0'; lena++);
for (lenb = 0; str2[lenb] != '\0'; lenb++);

for (i = 0; i <= lena - lenb + 1; i++)


{
for (j = 0; str1[i + j] == str2[j] && str2[j] != '\0'; j++);
if (str2[j] == '\0')
printf("\nString found at location : %d", i + 1);
}
}

// Implementation o count No.of digits and No.of letters in a string function

void count(char str[]) {


int words = 0, characters = 0, spchar = 0, i;
for (i = 0; str[i] != '\0'; i++) {
if (isalnum(str[i]) && (i == 0 || !isalnum(str[i - 1])))
words++;
characters++;
if (!isalnum(str[i]) && !isspace(str[i]))
spchar++;
}
printf("\nNo of characters = %d", characters);
printf("\nNo of special characters = %d", spchar);
printf("\nNo of words = %d", words);
}

Exercise:

1.Write a program to fins mean, variance and standard deviation of an array


elements
2. Dynamic memory allocation functions mallac(), calloc(), realloc(), free()

You might also like