0% found this document useful (0 votes)
2 views

Module2 Cp Final

Uploaded by

nabeelkm2000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module2 Cp Final

Uploaded by

nabeelkm2000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Arrays and strings

Arrays Declaration and Initialization, 1-Dimensional Array, 2-Dimensional ArraString processing:


In built String handling functions (strlen, strcpy, strcat and strcmp, puts, gets), Linear search
program, bubble sort program, simple programs covering arrays and strings

Array

• An array is a collection of variables of homogeneous (same) type.

• An array in C is a collection of items stored at contiguous memory locations and elements


can be accessed randomly using indices of an array.
• They are used to store similar type of elements as in the data type must be the same for all
elements
• . They can be used to store collection of primitive data types such as int, float, double, char,
etc of any particular type.
• Array can be integer array, floating point array, character array etc.
• Individual data item in array is called array element.
• Each array element is referred to by specifying the array name followed by one or more
subscripts.

Why do we need arrays?

We can use normal variables (v1, v2, v3) when we have a small number of objects, but if
we want to store a large number of instances, it becomes difficult to manage them with normal
variables. The idea of an array is to represent many instances in one variable.

1
Different ways of declaring an Array

1. Array declaration by specifying size

Eg:intA[10];

2. Array declaration by initializing elements

Eg: int A[]={10, 20, 30, 40 }

3. Array declaration by specifying size and initializing elements


Eg:int A[6]={10, 20, 30, 40 }

Array name must be accompanied by a size specification (i.e., the number of elements).
• One-dimensional array has only one pair of square brackets. The size is specified by a positive
integer expression(or constant), enclosed in square brackets.
• One-dimensional ARRAY DECLARATION is represented as
data- type array[ size] ;
eg: int a[10];

Array initialization/definition
Arrays can be initialized by assigning some initial values if desired. The initial values must appear
in the order in which they will be assigned to the individual array elements. Values should be
enclosed in braces and separated by commas.
The general form is
data- type array[ size] = { value1, value2, . . . , valuen} ;
Eg: int A[]={10, 20, 30, 40 }

Initialization of 1 D array
Array can be initialized at either two of the following stages:
• At compile time
• At run time
1. Compile time initialization
Syntax:
datatype arrayname[size]={list of values};
eg:
int number[3]={1,2,3};

2
• Size may be omitted. In such cases compiler allocates enough spaces for all initialized
elements.
Eg: int number[]={1,2,3};
• Characters may be initialized in a similar manner.
Char name[]={‘a’,’n’,’u’,’\0’};
• If we have more initializers than declared size, the compiler will produce an error.
int number[3]={1,2,3,4}; this will not work.it is illegal in C.

2. Run time Initialization


• We can use scanf( to initialize an array.
int number[3],i;
for(i=0;i<3;i++)
scanf(“%d”,&number[i]);

Advantages of an Array:
1. Random access of elements using array index.
2. Use of less line of code
3. Easy acces to all the elements.
4. Traversal through the array becomes easy using a single loop.
Disadvantages of an Array:
• It allows us to enter only fixed number of elements into it.

• We cannot alter the size of the array once array is declared. Hence if we need to insert more
number of records than declared then it is not possible. We should know array size at the
compile time itself.

• Inserting and deleting the records from the array would be costly since we add/delete the
elements from the array, we need to manage memory space too.

• It does not verify the indexes while compiling the array. In case there is any indexes pointed
which is more than the dimension specified, then we will get run time errors rather than
identifying them at compile time.

3
1) Write a program to read and display an array of size n.

#include<stdio.h>
void main()
{
int n,a[20],i;
printf("Enter the size of Array");
scanf("%d",&n);
printf("Enter the numbers");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
2) Writea program to read and display an array of size n in reverse order.

#include<stdio.h>
void main()
{
int n,a[20],i;
printf("Enter the size of Array");
scanf("%d",&n);
printf("Enter the numbers");
for(i=0;i<n;i++)

{
scanf("%d",&a[i]);
}
for(i=n-1;i>=n;i--)
{
printf("%d\t",a[i]);
}
}

4
3) Write a program to find sum and average of an array content of size n.

#include<stdio.h>
void main()
{
int n,a[20],i, sum;
float avg;
printf("Enter the size of Array");
scanf("%d",&n);
printf("Enter the numbers");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
sum=0;
for(i=0;i<n;i++)
{
sum = sum + i;
}
avg = (float)sum/n;
printf("Sum=%d",sum);
printf("Average=%f",avg);
}

4) Write a program to read and display even numbers in an array of size n.

#include<stdio.h>
void main()
{
int n,a[20],i;
printf("Enter the size of Array");
scanf("%d",&n);
printf("Enter the numbers");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
if(A[i]%2==0)
{printf("%d\t",a[i]);
}}}
5
5) Write a program to read and display prime numbers in an array of size n.

#include<stdio.h>
void main()
{
int n,a[20],i,flag,j;
printf("Enter the size of Array");
scanf("%d",&n);
printf("Enter the numbers");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{flag=0;
for(j=2;j<=a[i]/2;j++)
{
if(a[i]%j==0)
{
flag=1; break;
}}
if(flag==0)
{
printf("%d\t",a[i]);
}
}
}

Or using sqrt()
#include <stdio.h>
#include <math.h>

int main() {
int n, a[20], i, flag, j;

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


scanf("%d", &n);

printf("Enter the numbers: ");


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

printf("Prime numbers in the array: ");


for (i = 0; i < n; i++) {
if (a[i] < 2) // Exclude numbers < 2 (not prime)
continue;

flag = 1; // Assume prime

for (j = 2; j <= sqrt(a[i]); j++) { // Optimize loop using sqrt


if (a[i] % j == 0) {
flag = 0; // Not prime
break;
}
}

if (flag) {
printf("%d\t", a[i]);
}
}

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

6) Write a program to perform linear search in an array of size n. (Linear Search)

#include<stdio.h>

void main()

int a[50],n,i,key,flag=0;

printf("Enter the size of the array\n");

scanf("%d",&n);

printf("Enter the elements\n");

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

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

7
}

printf("Enter the value to be searched\n");

scanf("%d",&key);

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

if(a[i]==key)

printf("The searched element is in the %d th position",i);

flag++;

if(flag==0)

printf("Element not found\n");

7) Write a program to perform bubble sort in an array of size n.

#include<stdio.h>

void main()

int a[50],n,i,j,temp;

printf("Enter the size of the array\n");

scanf("%d",&n);

printf("Enter the elements\n");

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

scanf("%d",&a[i]);
8
}

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("The sorted array is");

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

printf("%d\n",a[i]);

8) Write a program to find largest element in an array of size n.

#include<stdio.h>

void main()

int a[50],i,n,largest;
9
printf("Enter the size of array\n");

scanf("%d",&n);

printf("Enter the element\n");

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

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

largest=a[0];

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

if(a[i]>largest)

largest=a[i];

printf("Largest value=%d\n",largest);

9) Write a C program to find the occurrence of an element in an array.

#include <stdio.h>

void main()

int Size, i, num, occr = 0;

printf("Please Enter the Array size = ");

scanf("%d", &Size);

10
int arr[Size];

printf("Enter the Array %d elements : ", Size);

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

{scanf("%d", &arr[i]);

printf("Please Enter the Array Item to Know = ");

scanf("%d", &num);

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

{if (arr[i] == num)

occr++;

printf("%d Occurred %d Times.\n", num, occr);

TWO DIMENSIONAL ARRAYS


• One-dimensional array can be thought of as a list of values,
• Thus, a two-dimensional array will require two pairs of square brackets. Elements are stored
by rows, so the right most subscript, or column, varies as elements are accessed in storage
order.

Two-dimensional arrays are declared as follows:


type array_name [row_size] [column_size];

11
eg: int s[2][3];

Initializing two_dimensional arrays


The initialization is done row by row.
For ex: int s[2][3]={{0,0,0},{1,1,1}};
Initializes first row to zero and the second row to one. The initialization is done row by row.
1) Write a C program to add two matrix.
#include <stdio.h>
void main() {
int m, n, i, j;
printf("Enter the number of rows and columns of the matrices: ");
scanf("%d%d", &m, &n);
int a[m][n], b[m][n], c[m][n];
printf("Enter the elements of first matrix : \n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter the elements of second matrix : \n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &b[i][j]);
}
}
for (i = 0; i < m; i++)
{
12
for (j = 0; j < n; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
printf("The sum of the two matrices is: \n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%d\t ", c[i][j]);
}
printf("\n");
}
}
2) Write a C program to multiply two matrix.

#include<stdio.h>
void main()
{
int a[50][50],b[50][50],r1,r2,c1,c2,i,j,k,product[50][50];
printf("Enter the order of matrix 1\n");
scanf("%d%d",&r1,&c1);
printf("Enter the order of matrix 2\n");
scanf("%d%d",&r2,&c2);
if(r1==c2)
{
printf("Enter the 1st matrix\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the 2nd matrix\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
13
scanf("%d",&b[i][j]);
}
}
for(i=0;i<r1;i++)
{
product[i][j]=0;
for(j=0;j<c2;j++)
{
for(k=0;k<r1;k++)
{
product[i][j]=product[i][j]+(a[i][k]*b[k][j]);
}
}
}
printf("The product of the matrix is\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",product[i][j]);
}
printf("\n");
}
}
else
{
printf("Multiplication is not possible");
}
}

3) Write a C program to find transpose of a matrix.


#include<stdio.h>
void main()
{
int a[50][50],i,j,m,n;
printf("Enter the order of matrix\n");
scanf("%d%d",&m,&n);
printf("Enter matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n Transpose of the matrix is \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
14
printf("%d",a[j][i]);
}
printf("\n");
}
}

4. Write a C program to find sum of diagonal elements of a matrix.

#include <stdio.h>
void main ()
{
int array[10][10];
int i, j, m, n, a = 0, sum = 0;
printf("Enetr the order of the matix \n");
scanf("%d %d", &m, &n);
if (m == n )
{
printf("Enter the elemets of the matrix\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &array[i][j]);
}
}
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
sum = sum + array[i][i];
}}

printf("\nThe sum of the main diagonal elements is = %d\n", sum);

15
}
else
printf("The given order is not square matrix\n");
}

MULTIDIMENSIONAL ARRAYS
Multidimensional arrays are defined in much the same manner as one except that a separate pair of
square bracket is required for each subscript. The general form of a multi-dimensional array is
type array_name [s1][s2][s3].....[sn]; where Si is the size of the ith dimension.
For ex:
int table[3][5][2]; /* is a three-dimensional array can be represented as a series of two- dimensional
arrays*/
String
• Strings are defined as an array of characters.
• The difference between a character array and a string is the string is terminated with a special
character ‘\0’.

Declaration of strings:
basic syntax for declaring a string.
char stringname[size];
eg: char str[20];
there is an extra terminating character which is the Null character (‘\0’) used to indicate termination
of string which differs strings from normal character arrays.
Size= maximum no.of characters+1.

Initializing a String:
A string can be initialized in different ways.
16
1. char str[] = "Programming";
2. char str[50] = "Programming";
3. char str[] = {'P','r','o','g','r','a','m','m','i','n','g','\0'};
4. char str[12] = {'P','r','o','g','r','a','m','m','i','n','g','\0'};

Read a character from User


1) scanf()
It is used to read the input (character, string, numeric data) from the standard input (keyboard).
It is used to read the input until it encounters a whitespace, newline or End Of File (EOF).
#include <stdio.h>
void main()
{
char str[20];
printf("Enter the String\n");
scanf("%s", str);
printf("String is: %s\n", str);
}
Output
Enter the String : Hello World
String is: Hello

Issue with scanf: There is a whitespace after Hello. So it read the input till Hello and store it in str.

Solution: use % [^\n] instead of %s.


#include <stdio.h>
void main()
{
char str[20];

17
printf("enter the string\n");
scanf("%[^\n]", str);
printf("String: %s\n", str);
}

2) Gets
It is used to read input from the standard input (keyboard).It is used to read the input until it
encounters newline or End Of File (EOF).
#include <stdio.h>
void main()
{
char str[20];
printf("Enter the String\n");
gets( str);
printf("String: %s\n", str);
}
Output
Enter the String: Hello World
String: Hello World
Issue: it reads string from standard input and prints the entered string, but it suffers from Buffer
Overflow as gets() doesn’t do any array bound testing. gets() keeps on reading until it sees a
newline character.

Display String value


printf puts

18
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
char str[20]; char str[20];
printf("Enter the String\n");
printf("Enter the String\n"); gets( str);
gets( str); puts(str);
printf("%s\n", str); }
}
Output
Output Enter the String: Hello world
Enter the String: Hello world Hello world
Hello world

1. strlen
strlen returns the length of the string stored in array.
#include<stdio.h>

19
#include<string.h>
void main()
{
char str[]="Hello World";
int len=strlen(str);
printf("length=%d",len);
}
OUTPUT
length=11.

2. strcat
It concatenates two strings and returns the concatenated string.
Syntax: strcat(string1,string2)
– concatenate string1 with string2.
#include <stdio.h>
#include <string.h>
void main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("After concatenation: %s", s1);
}
Output:
After concatenation: HelloWorld

3. strcpy
It copies the string str2 into string str1, including the end character (terminator char ‘\0’).
Syntax:
strcpy(string1,string2)
20
copy the content of string2 to string1

#include <stdio.h>
#include <string.h>
void main()
{
char s1[30];
char s2[30] = "Hello World";
strcpy(s1,s2);
printf("String s1: %s", s1);
}
Output:
String s1 is: Hello World

4. strcmp
It compares the two strings and returns an integer value. If both the strings are same (equal) then this
function would return 0 otherwise it may return a negative or positive value based on the comparison.
Syntax:
strcmp(string1,string2) -- Compares the content of string1 and string2
• If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value.
• If string1 > string2 then it would return positive value.
• If string1 == string2 then you would get 0(zero) when you use this function for compare
strings.

#include <stdio.h>
#include <string.h>
void main()
{
char s1[20] = "Hello";
char s2[20] = "World";
21
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
}
Output:
string 1 and 2 are different
1. Write a program to find length of string without using library functions.
#include <stdio.h>
void main()
{
char str[100];
int i,length=0;
printf("Enter a string: \n");
scanf("%s",str);
for(i=0; str[i]!='\0'; i++)
{
length++;
}
printf("\nLength of input string: %d",length);
}
2. Write a program to reverse a string without using library functions.
#include<stdio.h>
void main()
{
char str[50],rev[50];
int len,i,j;
22
printf("Enter the string\n");
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
{
len++;
}
for(i=len-1,j=0;i>=0;j++,i--)
{
rev[j]=str[i];
}
rev[j]='\0';
printf("%s\n",rev);
}

3. Write a program to concatenate two strings without using library functions.


#include<stdio.h>
#include<string.h>
void main()
{
char a[50],b[50],c[50];
int l1=0,l2=0,i,j;
printf("Enter the string\n");
scanf("%s",a);
printf("Enter the string\n");
scanf("%s",b);
for(i=0; a[i]!='\0'; i++)
{
l1++;
}
for(i=0; b[i]!='\0'; i++)
{
l2++;
23
}

for(i=0;i<l1;i++)
{
c[i]=a[i];
}
for(i=l1,j=0;j<l2;i++,j++)
{
c[i]=b[j];
}
c[i]='\0';
printf("%s\n",c);
}
4.Write a program to check whether a string is palindrome or not.
#include<stdio.h>
void main()
{
char str[50],rev[50];
int len=0,i,j,flag=0;
printf("Enter the string\n");
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
{
len++;
}
for(i=len-1,j=0;i>=0;j++,i--)
{
rev[j]=str[i];
}
rev[j]='\0';
for(i=0;str[i]!='\0';i++)
{
if(str[i]!=rev[i])
{
flag=1;
break;
}
}
if(flag==0)
{
printf("The string is Palindrome\n");
24
}
else
{
printf("The string is not Palindrome\n");
}
}

5.Write a C program to print number of vowels and consonants in a string.


#include <stdio.h>
#include<string.h>
void main(){
char str[100];
int i, vowels, consonants;
i = vowels = consonants = 0;
printf("Enter any String");
gets(str);
while (str[i] != '\0'){
if(str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U'||str[i] == 'a' || str[i] == 'e' ||
str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ){
vowels++;
}
else
consonants++;
i++;
}
printf("vowels in this String = %d", vowels);
printf("consonants in this String = %d", consonants);
}

25
Enumeration (or enum) in C
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to
integral constants, the names make a program easy to read and maintain.

enum State {Working = 1, Failed = 0};

The keyword ‘enum’ is used to declare new enumeration types in C and C++.

enum week{Mon, Tue, Wed};


enum week day;

1. Write a program to illustrate enum datatypes

enum week{Mon, Tue, Wed}day;


#include<stdio.h>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}

2. Write a C program to display month numbers

#include<stdio.h>

enum year{Jan, Feb, Mar, Apr, May, Jun, Jul,


Aug, Sep, Oct, Nov, Dec};

int main() 26
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);

return 0;
}
C typedef

The typedef is a keyword that is used to provide existing data types with a new name. The C
typedef keyword is used to redefine the name of already existing data types. When names of
datatypes become difficult to use in programs, typedef is used with user-defined datatypes,
which behave similarly to defining an alias for commands.

#include <stdio.h>

typedef int Integer;

int main() {

// n is of type int, but we are using


// alias Integer
Integer n = 10;

printf("%d", n);
return 0;
}

27

You might also like