Thursday, February 21, 2019


Array and String
Array: The consecutive memory location separated with same data types is called array. An array can be defined as number of memory location, each of which can store the same data type and which can be references through the same variable name.
The array of character is called string where as an array of integer or floats are called simply an array.
Importance /Advantages of array:
1. It makes very easy and efficient to handle large number of similar values in a program.
2. It also makes the program very short and easy to develop.
3. Array elements are stored in subsequent memory locations.
4. Array name represents the address of the starting elements.

 Types of Array:
One-dimension Array:  The value on an array variable assigned in one row is called one dimension array.
            Syntax:
type  array_name[size];
or,
type array_name[]={number_of_variables}; 
For example:
            int arr [10];
            Float age[]={18,19,21,17,16,18,16,15};
Index
0
1
2
3
4
5
6
7
8
Value
18
19
21
17
16
16
18
16
15
Two-dimension Array: While one-dimension array allows data to be placed in an array one row at a time, two-dimension arrays are capable of storing data in rows and columns.
The two dimension array is also called matrix.
Syntax / declare:
type array_name [numrows] [numclos]; or
type array_name [] [colsize]={{first_row},{second_row},……{last row}};
Where, type is data type for the array, array_name is the variable name for the storing data in the array, numrows is the maximum number of rows for the array and numcols is the maximum number of column for the array.
Example:
int matrix[2][3];
char student[10][15];
Write a program to read elements of the two matrices of order 3 x 3 and perform the matrix addition.
#include<stdio.h>
#include<conio.h>
int main()
 {
int a[3][3], b[3][3],sum[3][3],i,j;
printf("\n Enter elements for matrix A\n");
for(i=0;i<3;i++)
    {
for(j=0;j<3;j++)
      {
scanf("%d",&a[i][j]);
      }
    }
printf("\n Enter the elements for matrix B\n");
for(i=0;i<3;i++)
    {
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
      }
    }
printf("\n The sum of two matrix is\n");
for(i=0;i<3;i++)
    {
for(j=0;j<3;j++)
      {
sum[i][j]=a[i][j]+b[i][j];

printf("%d\t",sum[i][j]);
      }
printf("\n");
    }
getch();
 }

Output:
 Enter elements for matrix A
1 2 3
5 6 9
7 8 9

 Enter the elements for matrix B
7 8 9
4 5 6
1 2 3

 The sum of two matrixes is
8       10      12
9       11      15
8       10      12

Q. Write a program to find addition of any two matrix os size 2*2 using array. [2074]
Q. Write a program to enter elements into 4*4 matrix and find the sum of the elements of matrix
Write a program which finds multiplication table of two matrices. [HSEB 2071]
#include<stdio.h>
#include<conio.h>
int main( )
 {
int a[3][3], b[3][3],m[3][3],i,j,s=0,c;
printf("\n Enter elements for matrix A\n");
for(i=0;i<3;i++)
    {
for(j=0;j<3;j++)
      {
scanf("%d",&a[i][j]);
      }
    }
printf("\n Enter the elements for matrix B\n");
for(i=0;i<3;i++)
    {
for(j=0;j<3;j++)
      {
scanf("%d",&b[i][j]);
      }
    }
for(i=0;i<3;i++)
    {
for(j=0;j<3;j++)
{
            s=0;
            for(c=0;c<3;c++)
            {
            s=s+a[i][c]*b[c][j];
                        }
m[i][j]=s;
                }
    }
printf("\n The multiplication of two matrix is\n");
for(i=0;i<3;i++)
    {
for(j=0;j<3;j++)
      {

printf("%d\t",m[i][j]);
      }
printf("\n"); 
    }
getch( );
 }

Write a C program to read age of 40 students and count the number of students of the age between 15 and 22.
#include<stdio.h>
#include<conio.h>
main()
  {
int age[40],i,c=0;
printf("\nEnter age of 40 students:"); //code to input to array
for(i=0;i<40;i++)
        {             
scanf("%d",&age[i]);
        }
for(i=0;i<40;i++)
    {
if (age[i]>15 && age[i]<22)
            c=c+1;
    }
printf("The number of students aged between 15 and 21 are %d", c);
getch( );
 }

Write a program to sort integer variables in descending order.
#include<stdio.h>
#include<conio.h>
void main()
  {
int n,i,j,num[10],temp;
printf("Enter how many numbers?");
scanf("%d",&n);
printf("\nEnter %d numbers",n);
for(i=0;i<n;i++)
scanf("%d",&num[i]);
for(i=0;i<n;i++)
     {
for(j=i+1;j<n;j++)
       {
            if(num[i]<num[j])
              {
            temp=num[i];
            num[i]=num[j];
            num[j]=temp;
              }
            }
      }
printf("\n The sorted numbers in descending order are\n");
for(i=0;i<n;i++)
printf("%d\t",num[i]);
getch();
 }

.  Write a program using C language to read the age of 100 persons and count the number of persons in the age group between 50 and 60. Use FOR and CONTINUE statement.
#include<stdio.h>
#include<conio.h>
void main()
  {
inti,c=0;
float a[100];
printf("\nEnter age of 100 persons");
for(i=0;i<100;i++)
scanf("%f",&a[i]);
for(i=0;i<100;i++)
    {
if (a[i]>50 && a[i]<60)
            c=c+1;
else
continue;
    }
printf("Total number of persons aged between 50 and 60 are %d",c);
getch();
 }
  
Write a program in C to store mark obtained by ‘n’ students and count the number of students who obtained mark greater than 70. Also count the number of students who are fail. (<35)
#include<stdio.h>
#include<conio.h>
void main()
 {
intn,i,c=0,cf=0;
float m[100];
printf("\nEnter how many students?");
scanf("%d",&n);
printf("\n Enter marks for %d students: ",n);
for(i=0;i<n;i++)
scanf("%f",&m[i]);
for(i=0;i<n;i++)
if(m[i]>70)
  c=c+1;
else if(m[i]<35)
cf=cf+1;
printf("\n Total no. of students scoring more than 70 are %d ",c);
printf("\nTotal no. of students who are fail are %d ",cf);
getch();
 }

Output:
Enter how many students?5
Enter marks for 5 students: 30 80 50 60 70
Total no. of students scoring more than 70 are 1
Total no. of students who are fail are 1

Q. Write a program to sort 10 integer numbers in ascending order.

Write a C program to input 'n' numbers and find the greatest and smallest number. [2061]
#include<stdio.h>
#include<conio.h>
main()
{
            int n,i,max,min, a[100];
            printf("How many number");
            scanf("%d",&n);
            for(i=0;i<n;i++)
            {
                        printf("Enter the number");
                        scanf("%d", &a[i]);
                        }
            max=a[0];
            min=a[0];
            for(i=0;i<n;i++)
            {
                        if(a[i]>max)
                        max=a[i];
                        else if(a[i]<min)
                        min=a[i];
                        else;
            }
printf("The greatest number is =%d",max);
printf("The smallest number is =%d",min);
getch( );
}
Output:
How many number 3
Enter the number 3 5 2
The greatest number is = 5
The smallest number is = 2

Write a program to store ten different constant variables in an array and print out the greatest number.
#include<stdio.h>
#include<conio.h>
 main()
  {
    int i,num[10],g;
    printf("\nEnter 10 numbers");
    for(i=0;i<10;i++)
     scanf("%d",&num[i]);
    g=num[0];
    for(i=1;i<10;i++)
     {
      if (num[i]>g)
       g=num[i];
     }
    printf("\nThe greatest number is %d",g);
    getch();
}

String Function: A string is a sequence of character. Thus character array is also known as string. Any sequence or set of character defined within a pair of double quotation symbol is a constant string. A string is always terminated by a null character i.e. \0.

Initialization of string
char name[] = “ANDREW”

String manipulation is the process of doing some meaningful operation on the string.
They are:
Reading string, displaying string.
Combining or concatenatingstrings.
Copying one string to another.
Comparing string
                          I.          strlen( ):This string function   returns an integer which denotes exact length of thestring . (Note excluding the terminating null character (\0).
 Syntax:
            strlen(string);

char course [] = “Computer Science”
The length for the string is 16.

                        II.          strcat ( ): This function concatenates two strings i.e. it appends one string at the end of another. This function accepts two strings and stores the contents of the second string at the end of the first string.
Syntax:
strcat(string1,string2);
char class []= “Class 12”
char subject[] =”Management”
strcat(subject,class);
The outputs will be ManagementClass 12.

                      III.          strncat( ):This function is used to concatenate n number of character from source string and merge after the destination string.

                      IV.          strcmp( ): This function compares two strings to find out whether they are same or different . This function is useful for constructing and searching strings. The output of the comparison is integer value either positive (+1), or negative ( -1), or equal to zero (0). The output of this function is zero if both strings are equal.

Syntax:
strcmp(string1,string2);

Example: Write a program to compare any two string by using string function in C
 #include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
            char string1[30], string2[30];
            printf("enter first string");
            gets(string1);
            printf("enter second string");
            gets(string2);
            if(strcmp(string1,string2)>0)
            printf("greater string %s",string1);
            else if(strcmp(string1,string2)==0)
            printf("both string are equal");
            else
            printf("greater string %s",string2);
            getch();
}


                        V.          strncmp ( ): This function is used to compare n number of character from both strings. The comparison is same as strcmp function.

                      VI.          strrev ( ): This function is used to reverse all character in a string except null character at the end of the string.The reverse of string “abc” is “ cba”.
Syntax:
strrev(string);

                   VII.          strcpy ( ):This string function is used to copy one string to other. The source string is copied to destination string. The index size must hold the size of source string character length.
                        strcpy (destination_string, source string);
i.e. strcpy(s1,s2) means the content of s2 is copied to s1.
VIII.     strncpy ( ):This function is same as strcpy function except it copies n numbers of character from source to destination.
                 VIII.          strlwr(): This function is used to change character to lowercase.If the main string is in upper case it changed to lowercase.If the character already in lowercase then this function does not change the value
Syntax:
Strlwr(string)
Chat string1[ ] = “Computer”;
strlwr(string1);
The value of string1 is changes to ‘computer’.
XI. strupr(): This string function is used  to convertcharacters to uppercase. If the character of the string is in lowercase it changes to uppercase otherwise this function does nothing.
Syntax:
char string1 [ ] = “Computer”;
            strupr(string1);
The value of string changes to “COMPUTER”.
Write a program to read a line of text and convert it into uppercase.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char text[25];
printf("\nEnter any line of text in lowercase\n");
gets(text);
strupr(text);                    
printf("\n Enterd text converted into uppercase\n");
puts(text);
getch();
 }

                           I.          strcpy ( ):This string function is used to copy one string to other. The source string is copied to destination string. The index size must hold the size of source string character length.
                        strcpy (destination_string, source string);
i.e. strcpy(s1,s2) means the content of s2 is copied to s1.
VIII.     strncpy ( ):This function is same as strcpy function except it copies n numbers of character from source to destination.
Write a program to input n names and sort them in alphabetical order.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[50][20],temp[20];
inti,n,j;
printf("\nEnter how many names: ");
scanf("%d",&n);
printf("Enter %d names\n",n);
for(i=0;i<n;i++)
scanf("%s",name[i]);
for(i=0;i<n;i++)
 {
for(j=i+1;j<n;j++)
 {
if(strcmp(name[i],name[j])>0)
 {
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
 }
 }
 }
printf("\nThe sorted names are\n");
for(i=0;i<n;i++)
printf("\n%s",name[i]);
getch();
 }

Write a program to count the number of vowels and consonants in a given text.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
charstr[20];
int nv=0,nc=0,i;
printf("\nEnter any text");
gets(str);
strupr(str);
for(i=0;str[i]!='\0';i++)
{
if(str[i]=='A' || str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U')
nv++;
else if(str[i]>='A' &&str[i]<='Z')
nc++;
}
printf("\n No. of Vowels = %d ",nv);
printf("\n No. of Consonants = %d ",nc);
getch();
}
Enter any text:santosh
No. of Vowels =2
No. of Consonants =5

Write a program to input a string and count the number of consonants  containing in the string.

#include <stdio.h>
#include<conio.h>
int main()
{
    char line[150];
    int i, vowels, consonants ;

    vowels =  consonants = 0;

    printf("Enter a line of string: ");
    scanf("%[^\n]", 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')
        {
            vowels ++;
        }
        else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
        {
            consonants ++;
        }
               
    }
    printf("\nConsonants: %d",consonants);
   
    getch();

}


Write a program to store ten different constant variables in an array and print out the greatest number.
#include<stdio.h>
#include<conio.h>
 main()
  {
    int i,num[10],g;
    printf("\nEnter 10 numbers");
    for(i=0;i<10;i++)
     scanf("%d",&num[i]);
    g=num[0];
    for(i=1;i<10;i++)
     {
      if (num[i]>g)
       g=num[i];
     }
    printf("\nThe greatest number is %d",g);
    getch();
}
Write a program to enter a string and check whether the entered string is palindrome or not. (Example, ada, madam)
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
            char str[10],str1[10];
            int cmp;
            printf("enter a string\n");
            scanf("%s",str);
            strcpy(str1,str);
            strrev(str1);
            cmp=strcmp(str,str1);
            if(cmp==0)
            printf("string is palindrome");
            else
            printf("string is not palindrome");
            getch();
}

Output:
Enter a string
madam
String is palindrome
 Write a program to input a message from keyboard and display the menu.
a.       Print the message length in terms of characters.
b.      Print the message in reverse order.
      c.       Print the message in capital letters.
d.     Copy the message from one location of screen to another location..
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
charmsg[100],msg1[100];
inti,ch,len,j;
printf("\n Enter a message:");
gets(msg);
printf("\n 1. Print the message length in terms of characters");
printf("\n 2. Print the message in reverse order");
printf("\n 3. Print the message in capital letters");
printf("\n 4. Copy the message from one location to another");
printf("\n Enter your choice (1-4)");
scanf("%d",&ch);
switch(ch)
{
case 1:
len=0;
while(msg[len]!='\0')
len++;
printf("\n The string %s has %d characters\n",msg,len);
break;
case 2:
len=strlen(msg);
 j=0;
for(i=len-1;i>=0;i--)
msg1[j++]=msg[i];
msg[j]='\0';
strcpy(msg,msg1);
printf("\n The reversed string is %s",msg);
break;
case 3:
for(i=0;msg[i]!='\0';i++)
 {
if(msg[i]>='a' &&msg[i]<='z')
msg[i]=msg[i]-32;
 }
printf("\n The message in uppercase %s",msg);
break;
case 4:
for(i=0;msg[i]!='\0';i++)
msg1[i]=msg[i];
msg1[i]='\0';
printf("The copied string is %s ",msg1);
break;
default:
printf("\n Invalid choice");
 }
getch();
 }

Difference between array and structure with suitable example
Array
Structure
 An array is a collection of similar type's data.
A structure is a collection of different types of variable under a single name.
The memory taken by an array depends on data type of the array and its size.
The memory taken by a structure variable depends on its members and their individual types.
Array is not user-defined data type.
Structure is user-defined data type. We can define variable of particular structure type.
Syntax:
datatype array_name[size];
Syntax:
struct structure_name
{
type1 member1;
type2 member2;
};
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
            char name[20];
            int age;
            printf("Enter Name:");
            gets(name);
            printf("Enter Age:");
            scanf("%d",&age);
            printf("Name:%s",name);
            printf("\tAge %d",age);
            getch( );
}
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
            struct student
            {
                        char name[20];
                        int age;
            } std;
            printf("Enter Name:");
            scanf("%s",std.name);
            printf("Enter Age:");
            scanf("%d",&std.age);
            printf("Name:%s",std.name);
            printf("\tAge %d",std.age);
            getch( );
}

Write an algorithm and C program to read salaries of 200 employees and count the number of employees getting salary between 5000-10,000.

Write a program to read salaries of 300 employees and count the number of employees getting salary from 10,000 to 15,000.



Write a C program to input 'n' numbers and find the greatest and smallest number. [2061]
#include<stdio.h>
#include<conio.h>
main()
{
            int n,i,max,min, a[100];
            printf("How many number");
            scanf("%d",&n);
            for(i=0;i<n;i++)
            {
                        printf("Enter the number");
                        scanf("%d", &a[i]);
                        }
            max=a[0];
            min=a[0];
            for(i=0;i<n;i++)
            {
                        if(a[i]>max)
                        max=a[i];
                        else if(a[i]<min)
                        min=a[i];
                        else;
            }
printf("The greatest number is =%d",max);
printf("The smallest number is =%d",min);
getch( );
}
Output:
How many number 3
Enter the number 3 5 2
The greatest number is = 5
The smallest number is = 2

Write a program to store ten different constant variables in an array and print out the greatest number.
#include<stdio.h>
#include<conio.h>
 main()
  {
    int i,num[10],g;
    printf("\nEnter 10 numbers");
    for(i=0;i<10;i++)
     scanf("%d",&num[i]);
    g=num[0];
    for(i=1;i<10;i++)
     {
      if (num[i]>g)
       g=num[i];
     }
    printf("\nThe greatest number is %d",g);
    getch();
}
Write a program to enter a string and check whether the entered string is palindrome or not. (Example, ada, madam)

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
            char str[10],str1[10];
            int cmp;
            printf("enter a string\n");
            scanf("%s",str);
            strcpy(str1,str);
            strrev(str1);
            cmp=strcmp(str,str1);
            if(cmp==0)
            printf("string is palindrome");
            else
            printf("string is not palindrome");
            getch();
}

Output:
Enter a string
madam
String is palindrome


Q. Write a program to sort ten integer number in ascending order. #include<stdio.h>
#include<conio.h>
 main()
{
int i,j,temp,a[10];
printf("Enter 10 integer numbers:");
for(i=0;i<10;i++)
{
           
scanf("%d",&a[i]);
}
for (i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(a[i]>a[j])
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
printf("The 10 numbers sorted in ascending order are:");

for(i=0;i<10;i++)
{
           
printf("%d\t",a[i]);
}