Module2 Cp Final
Module2 Cp Final
Array
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
Eg:intA[10];
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.
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);
}
#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;
if (flag) {
printf("%d\t", a[i]);
}
}
printf("\n");
return 0;
}
#include<stdio.h>
void main()
int a[50],n,i,key,flag=0;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
7
}
scanf("%d",&key);
for(i=0;i<n;i++)
if(a[i]==key)
flag++;
if(flag==0)
#include<stdio.h>
void main()
int a[50],n,i,j,temp;
scanf("%d",&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;
for(i=0;i<n;i++)
printf("%d\n",a[i]);
#include<stdio.h>
void main()
int a[50],i,n,largest;
9
printf("Enter the size of array\n");
scanf("%d",&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);
#include <stdio.h>
void main()
scanf("%d", &Size);
10
int arr[Size];
{scanf("%d", &arr[i]);
scanf("%d", &num);
occr++;
11
eg: int s[2][3];
#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");
}
}
#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];
}}
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'};
Issue with scanf: There is a whitespace after Hello. So it read the input till Hello and store it in str.
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.
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);
}
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");
}
}
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.
The keyword ‘enum’ is used to declare new enumeration types in C and C++.
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
#include<stdio.h>
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>
int main() {
printf("%d", n);
return 0;
}
27