facebook like button

29 April, 2011

program 37: matrix multiplication

The need:
     This is a simple program to multiply 2 matrices.
The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int j,i,k,m1,n1,m2,n2;
    int A[20][25],B[20][25],mul[20][25];         //declaration of 2 dimensional array
    printf("This is a program to get multiplication of two matrices A nad B\n\n");
    printf("Enter the rows in mat A..\n");
    scanf("%d",&m1);
    printf("Enter the columns in mat A..\n");
    scanf("%d",&n1);
    printf("Now keep on entering matrix elements.\n\n");
    for (i=0;i<m1;i++)
    {
        for (j=0;j<n1;j++)
        {
            printf("A%d%d=",i+1,j+1);
            scanf("%d",&k);
            A[i][j]=k;
        }
    }
   
    printf("\nEnter the rows in mat B..\n");
    scanf("%d",&m2);
    if(n1!=m2)
    {
        printf("\n\nDimension error.\nCan not multiply\nexiting...\n");
        exit(0);
    }
    printf("Enter the columns in mat B..\n");
    scanf("%d",&n2);
    printf("Now keep on entering matrix elements.\n\n");
    for (i=0;i<m2;i++)
    {
        for (j=0;j<n2;j++)
        {
            printf("B%d%d=",i+1,j+1);
            scanf("%d",&k);
            B[i][j]=k;
        }
    }
   
    printf("\n\nMatrix A is\n\n");
    for (i=0;i<m1;i++)
    {
        for (j=0;j<n1;j++)
        {
            printf ("%d ",A[i][j]);
        }
    putchar('\n');
    }
   
    printf("\n\nMatrix B is\n\n");
    for (i=0;i<m2;i++)
    {
        for (j=0;j<n2;j++)
        {
            printf ("%d ",B[i][j]);
        }
    putchar('\n');
    }
   
   
   
    for (i=0;i<m1;i++)            //initialisation of mat mul
    {
        for (j=0;j<n2;j++)
        {
             mul[i][j]=0;
        }
    }
   
   
    for (i=0;i<m1;i++)            //multiplication part
    {
        for (j=0;j<n2;j++)
        {
            for (k=0;k<n1;k++)
            {
                mul[i][j]+=A[i][k]*B[k][j];
            }
        }
    }
   
   
    printf("\n\nThe multiplied matrix is\n\n");
    for (i=0;i<m1;i++)
    {
        for (j=0;j<n2;j++)
        {
            printf ("%d ",mul[i][j]);
        }
    putchar('\n');
    }
    getchar();
}
-------------------------------------------- 

The approach: 
This program shows how one can multiply 2 matrices. Run the program. This program asks you to enter the number of rows and columns of the matrix A, then matrix A and similarly matrix B. This also prints both the matrices for user. Then the program multiplies the 2 matrices and prints the output matrix. For multiplication of 2 matrices to be defined number of columns of first matrix should be equal to number of rows of second matrix. In the program does not find those to be equal, it terminates. The 'exit()' functions cause the program to terminate. Read remark for details. Multiplication procedure implemented here is the same as you people follow when you multiply 2 matrices. To know more about how a matrix is stored and printed .see program36.


Remarks:

1. You have noticed that I have written a 0 in parentheses of 'exit()' function. Actually any integer could be written there or even it could be left blank.
2. The number helps in determining the site of termination of the program at run time when there are multiple 'exit()' statements in it.

27 April, 2011

program 36: matrix as 2 dimesional array

The need:
     In most calculations we need matrices. So for a C program to do calculations on matrices it should store the matrix first. This program just takes a matrix as input, stores that and prints back for user.
The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int j,i,k,m,n;
    int mat[20][25];         //declaration of 2 dimensional array
    printf("Enter the rows..\n");
    scanf("%d",&m);
    printf("Enter the columns..\n");
    scanf("%d",&n);
    printf("Now keep on entering matrix elements.\n\n");
    for (i=0;i<m;i++)
    {
        for (j=0;j<n;j++)
        {
            printf("Enter element %d%d.\n",i+1,j+1);
            scanf("%d",&k);
            mat[i][j]=k;
        }
    }
    printf("\nThe matrix is\n\n");
    for (i=0;i<m;i++)
    {
        for (j=0;j<n;j++)
        {
            printf ("%d ",mat[i][j]);
        }
    putchar('\n');
    }
}
--------------------------------------------
The approach: 
This program shows how one can implements 2 dimensional integer array to store a matrix in a C program. Run the program. This program asks you to enter the number of rows and columns of the matrix a and then the matrix and prints that matrix for user. The program uses 2 for loops for taking input from user and 2 loops for printing the output. Here I have assumed that you are very much familiar to nested loops(loop within a loop).

Remarks:
1. In this program you have seen use of 2 dimensional integer array. In C we can have array of any dimension for any data-type but their use is not that common.

program 35: printing the positions of a matrix

The need:
     This program takes takes dimensions of a matrix as input and prints all the positions of that matrix. Here position means the row and column of an element.
The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int j,i,m,n;
    printf("Enter the number of rows..\n");
    scanf("%d",&m);
    printf("Enter the number of columns..\n");
    scanf("%d",&n);
    for (i=0;i<m;i++)
    {
        for (j=0;j<n;j++)
        {
            printf ("%d%d ",i+1,j+1);
        }
    printf("\n");
    }
} 
--------------------------------------------
The approach: 
This program illustrates how we can print in 2 dimensional space(like matrix here). Run the program. This program asks you to enter the number of rows and columns of the matrix and then prints index of each element of that matrix. I did not make this program at that time but I have put its here intentionally because in next post I am going to tell you how to store a matrix in a C program. I am going to introduce the concept of 2 dimensional arrays which can store a matrix.

program 34: printing a triangle of stars(*)

The need:
     This program takes a whole paragraph as input and calculates total number of characters, words and lines.
The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int j,i,k;
    printf("Enter the number of stars in the base..");
    scanf("%d",&k);
    for (i=1;i<=k;i++)
    {
      for (j=0;j<i;j++)
      {
         printf ("*  ");
      }
      printf("\n");
    }
}
--------------------------------------------
The approach: 
This program illustrates how we can print in 2 dimensional space(like matrix in next posts). Run the program. This program asks you to enter the number of stars in the base. Give an integer from 1 to 30(so that you can see the output clearly). You can give a bigger integer but the shape of triangle may not be clearly visible at that number. As you can see the output, the program create a right angle triangle of stars. This is done by two nested for loops here. Each run of inner for loop cause a single * to be printed on screen. Each run of outer loop has i number of runs of inner loop. So each run of outer loop prints i number of stars on the screen followed by a new line.

program 33: program to count lines and words

The need:
     This program takes a whole paragraph as input and calculates total number of characters, words and lines.

The code: 
--------------------------------------------
//A program to count lines
#include<stdio.h>
#include<string.h>
main( )
{
    char line[500],ctr;
    int i,c,end=0,characters=0,words=0,lines=0;
    printf("key in text =>   ");
    while(end==0)
    {
        c=0;
        while((ctr=getchar())!='\n')
        line[c++]=ctr;
        line[c]='\0';
        if(line[0]=='\0')
        break;
        else
        {
            words++;
            for(i=0;line[i]!='\0';i++)
            if(line[i]==' '|| line[i]=='\t')
            words++;
        }
        lines=lines+1;
        characters=characters+strlen(line);
    }
    printf("\n");
    printf("no lines=> %d\n",lines);
    printf("no of words=> %d\n",words);
    printf("no of characters=> %d\n",characters);
}
--------------------------------------------
 
The approach:
First of all run the program. This program takes input until you press enter 2 times continuously thus allowing you to enter more than one line (recall that in previous programs whenever you gave characters as input to your program and pressed ENTER key it stopped taking more characters). After taking input the program gives the output.

10 April, 2011

program 32: binary conversion

The need:
     This program converts a given decimal integer to equivalent binary number.

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int i=0,j,k,l,m;
    char str1[50],str2[50];
    printf("Enter a decimal integer => ");
    scanf("%d",&k);
    m=k;                   //storing k for further use
    while(k>0){            //while loop for storing remainder
       if(k%2==0)          //of each division by 2 in a string
       str1[i]='0';        //variable str1
       else
       str1[i]='1';
       k/=2;
       i++;
    }
    str1[i]='\0';
    l=i;
    j=i-1;
    for(i=0;j>=0;i++,j--)
      str2[j]= str1[i];
    printf("The binary equivalent of %d is => ",m);
    for(j=0;j<l;j++)
    putchar(str2[j]);
    getchar();
}
--------------------------------------------
 
The approach:
    You people are supposed to know what binary numbers are and how we can convert a decimal number to corresponding binary number on paper. That same division method is used in this program. First a number is scanned in variable k. During run of the program value of k will be changed so I have backed-up the value of k in another variable m. After while loop variable str1 will be containing all the remainders. But binary equivalent is reverse of remainders. In previous program I demonstrated how to reverse a string without using another string variable but here I am using another string variable str2 to get the reversed string in it.

program 31: reversing a string


The need:
     This program in some places we need to reverse the given string like in next post (binary conversion). This program asks the user for a string, reverses that and prints back.

The code: 
--------------------------------------------
#include<stdio.h>
#include<string.h>
main()
{
    int i=0,length;
    char c,str[50];
    printf("Enter a string => ");
    gets(str);
    length=strlen(str);
    for(i=0;i<length/2;i++)
    {
      c=str[i];
      str[i]= str[length-1-i];
      str[length-1-i]=c;
    }
    printf("\nreversed string is => ");
    puts(str);
    getchar();
}
--------------------------------------------
 
The approach:     
    There are many ways to reverse a string. Here I have exchanged last character with first, second with second last and so on up to middle of string.

program 30: finding whether a word is palindrome or not

The need:
     In previous posts you have seen that we can have for loop in another for loop. This is true for all the loops and conditional statements also. This is a program for palindrome checking. This program takes some a word as input check whether its a palindrome or not and prints corresponding message for user.

The code: 
--------------------------------------------
#include<stdio.h>
#include<string.h>
main()
{
    int i,j=0,k;
    char a[20];
    printf("Enter a word to check whether its a palindrome.\n");
    scanf("%s",a);
    k=strlen(a);
    for (i=0;i<k/2;i++)
    {
        if(a[i]==a[k-i-1])
        ;                  //empty statement.
        else
         {
          j++;
          break;
         }
    }
    if(j>0)
    printf("The word is not palindrome .\n");
    else
    printf("The word is palindrome .\n");
    getch();
}
-----------------------------------------
 
The approach:     
    Palindrome is the word whose reverse is the same word. So simplest approach is to match first letter to the last, second to second last and so on up to middle. If all are matched, the word is a palindrome else not. The program implements this with the help of single for loop used here.
Here j is an integer variable initialized to 0. Observe if any mismatch is found j is increased. So if at the end of for loop is j is greater than 0, the word is not a palindrome else the word is a palindrome.
    Two more things I wanted to show here. One is that we can have an empty statement. An empty statement is having nothing in it. It is used after if when we want program not to do anything if the condition is satisfied. The second is the 'break' statement. 'break' statement is always used inside a loop. This breaks the loop iterations. So it is used with a condition and breaks the loop flow. Like in our program if is has found a mismatch, there is no need to check further so to save our time it need not run the loop for more number of times. Hence the 'break' statement breaks the loop as soon as the first mismatch is found.

06 April, 2011

program 29: sorting in increasing order (selection sort)

The need:
     In previous posts you have seen that character arrays exist. This program was built to show that we can have arrays of integers also. This program takes some integers as input stores them in an array, sorts them in increasing order and prints back for the user.

The code: 
--------------------------------------------
#define MAX 20
#include<stdio.h>
int main()
{
    int i,j,k,n,a[MAX];
    printf("How many numbers do you want to sort?\n");
    scanf("%d",&n);
    printf("Now keep on giving %d numbers.\n",n);
    /*  taking numbers one by one*/
    for(i=0;i<n;i++)
    {
      scanf("%d",&a[i]);   
    }

    printf("\nYou have given\n");
    for(i=0;i<n;i++)
    {
      printf("%d  ",a[i]);
    /* for printing given array*/
    }
    /*below is code for sorting */
    for(i=0;i<n;i++)
    {
        for(j=i;j<n;j++)
           {
           if(a[i]>a[j])
           {
            k=a[i];
            a[i]=a[j];
            a[j]=k;
           }
         }
    }

    /*above is code for sorting */


    printf("\n\nSorted in increasing order\n");
    for(i=0;i<n;i++)
    {
      printf("%d  ",a[i]);
    /* for printing sorted array*/
    }
    getch();
    return 0;
}

-----------------------------------------
 
The approach:     
    The simplest idea to sort an array in increasing order is given by following steps:
1. Find out smallest number of the array.
2. Exchange this smallest number with first element number in the array.
3. Now skip position 1 and take rest of array as array.
4. repeat from step1.

    This program implements exact this approach. I think taking input, storing in array and printing array is trivial for you at this point of time. Now comes sorting which is explained in next paragraph.
    Here 2 for() loops one inside the other are used to get our task done. Here for for() loops I have used 2 variables 'i' and 'j'. The loop with variable is in side of loop so I'll be calling that the inner loop and the other the outer loop. Now see that inner loop runs completely in each run of outer loop. Throughout single run of outer loop value of 'i' does not change.

Remarks:
1. In this program you have seen use of integer array. In general in C we can have array for any data-type.
2. There are other methods also for sorting.
3. Here in the end of program I have used a getch() statement. This halts the program screen to until you press ENTER key. This is not necessary in "C-free" and "Unix built-in compiler" because C-free has built-in facility to halt the program screen until you press any key. but in dev-C++ and turbo-C++ this getch()is necessary to halt the program screen otherwise these compilers close the screen as the program finishes final output whether user is able to see the output in that short time of spell or not.

program 28: getting ASCII code of any character

The need:
  This program was made to get ASCII code for any given character. 

The code: 
--------------------------------------------
#include<stdio.h>
#include<math.h>
int main()
{
    char i;
    printf("Enter the character to get its ASCII code.\n");
    scanf("%c",&i);
    printf("\nASCII code of `%c` is %d\n\n",i,i);
    printf("\n");
    return 0;
}
-----------------------------------------

The approach:     
     Probably you are aware of the fact that in computer's language everything is combination of 0 and 1. You know that integers can be converted into binary numbers and stored in computer. But question comes how characters are converted and stored? Answer is: there is a standard encoding scheme called ASCII which assigns an integer to each character and then the character is converted into 0 and 1's and stored in memory of computer. Worth notice point is this: each character is stored as integer in memory it is the printing style which differentiate between character and integer. So to print ASCII code of any character just print the same variable which is storing that character with %d which has been done here.

Remarks:
    One more point I wanted to show that if we include header file which is not at all required then there is no harm provided your compiler has that header file. Note that I have included math.h header file in this program while there is no function in the program that requires that header file.

program 27: comparison of two strings

The need:
     In previous post we came to know about index and accessing of elements of a string (basically an array of characters.) In the remark of previous post I told that there is a header file which deals with strings. In this program I am introducing that header file "<string.h>" to you. This program takes 2 strings as input, prints their lengths and tells whether they are equal or not.

The code: 
--------------------------------------------
#define MAX_LENGTH 50
#include<stdio.h>
#include<string.h>
int main()
{
    int i,l1,l2;              // declaration of 3 integers
    char str1[MAX_LENGTH],
str2[MAX_LENGTH];     //declaration of two character strings str1 and str2
    printf("Enter string1\n");
    gets(str1);            // getting string and storing in str1

    printf("Enter string2\n");
    gets(str2);            // getting string and storing in str2

    l1=strlen(str1);       // getting length of str1 into l1
    l2=strlen(str2);       // getting length of str2 into l2
    i=strcmp(str1,str2);   // strcmp compares strings str1 & str2
    printf("length of string %s is %d\n",str1,l1);
    printf("length of string %s is %d\n",str2,l2);
    if(i==0)
    printf("given strings are same.\n");
    else
    printf("given strings are not same.\n");
    return 0;
}

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

The approach:
     First of all run the program. Read the following explanation and try to understand the code. I hope you remember the use of #define directive(program9).
   This program takes two strings as input. This is well understood by you. Then I have used built-in function strlen() to get the length of str1 and then str2. strlen() function calculates the length of string given to it as argument and returns it to the variable left of '=' sign. So we have length of str1 and str2 in 'l1' and 'l2' respectively. Then function strcmp() is used which takes 2 strings as arguments(here str1 and str2). This returns 0 if the given strings(strings given to it as arguments) are equal else returns non-zero value. So by checking the value of I we can say whether the given strings are same or not and print the corresponding statement. This is done using if...else... statement.


Remark:
    Here in this program I have calculated the lengths of given strings directly by using built-in function strlen(). To compare strcmp has been used. But these are not only functions in <string.h>. Some most commonly used are:
strlen
strcmp
strcpy
strcat
strstr
strncmp
strncpy
strncat
For complete reference of <string.h> visit the following links:
 

program 26: calculating the length of a string

The need:
     In previous post we came to know that there exists a data-type to handle words and characters. This program takes a string as input and shows position of each character in that string and also counts the number of characters in the string(length of string). Here in this program we come to know a new term 'array-index' or simply 'index'.

The code: 
--------------------------------------------
#define MAX_LENGTH 50
#include<stdio.h>
int main()
{
    int i=0,length;              // declaration of single integer
    char str[MAX_LENGTH];     //declaration of a character string str
    printf("Enter a string\n");
    gets(str);            // getting string and storing in str
    while(str[i]!='\0')
    {
     printf("the index of character %c is %d\n",str[i],i);
     i++;
    }
    length=i;
    printf("\nThe length of given string is %d\n",length);
    return 0;
}

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

The approach:
     First of all run the program. Read the following explanation and try to understand the code. I hope you remember the use of #define directive(program9).
In C strings are stored as ordered set of characters. So we can say that this particular character is at that number position. Yes. In C we have this built-in facility. So each character can be accessed by its location in that set. This location(position number) is called 'index' of that character in the string. These index start from 0 and continue in increasing sequence. We can access the character at index 'i' by writing str[i] where given string is stored in variable str. One question can arise like, "Up to where the index continue?" The answer is till "the last character of the string". Now second question comes, "How does program comes to know the end of that string?". The answer is in next paragraph.
    When you have to recognize the end of some-thing, you try to find some mark or symbol that signifies its end. This symbol can not occur in the middle of the given thing. e.g. you can tell the end of a sentence by seeing a full-stop after it. So the idea is, there must be something which does not occur in any of the given string so that the program can tell the end of that string. Yes. We have a special character called NULL which is represented as NULL or '\0'. Note here '\0' is a single character literal. This '\0' is placed after the string ends at the time of scanning. Here I also want to tell you that a single character literal is written enclosed in single quotes. e.g. a character literal 'd'. Multi-character literals are written enclosed in double quotes. e.g. a string literal 'ranu'.

   In this program there is a while loop which accesses each character of string str by is index, compare it with NULL and terminates when it is found to be NULL('\0') character. In each run of loop corresponding character gets printed with its index and the index variable is incremented so that in next run next character can be printed. Note that here 'i' is used as index of str in each run of loop. Its obvious that at the end of loop variable 'i' will be having the value of the length of string which is assigned to variable length and printed in next line.

Remark:
    Here in this program I have calculated the length of given string by using a loop to count till the end of string. I further programs you'll see that we have direct function to calculate the length of a string. In fact we have a whole header file to do some things with strings.

02 April, 2011

program 25: characters and strings

The need:
     In all my previous posts I have told you about some data-types in C(int, float, double etc.) but all these are data-types for numbers. We know that numbers are not the only thing which we use in our daily life. Words and letters also equally important. Don't you think that a program should have data-type for those? Yes there is a data-type char for these words and letters. Here char stands for "character". For now just remember that in C we use term "character" for letters(alphabet), single digit or any other symbol on keyboard. This program shows how we scan characters and strings of characters (words and phrases in normal English).This program only takes the input and prints back.

The code: 
--------------------------------------------
#include<stdio.h>
int main()
{
    char j,k;              // declaration of single character
    char s[15],t[40];     //declaration of character strings
    printf("Enter any character\n");
    k=getchar();
    printf("You entered\t %c \n",k);
    printf("This character was stored in variable k\n\n");
    printf("Enter your first name...\n");
    scanf("%s",s);         // scanning s as string
    printf("Your first name is:\t %s\n",s);
    j=getchar();
    if(j=='\n')
    printf("j is ENTER\n\n");
    else
    printf("j is %c\n",j);
    printf("Enter your full name\n");
    gets(t);            // getting t as string
    printf("\nYour full name is %s\n\n",t);
    printf("Still the value stored in variable k is\t");
    putchar(k);
    printf("\n\n");
    return 0;
}
-----------------------------------------

The approach:
     First of all run the program, then try to understand the code. Read the explanation below thoroughly. In case of any doubt you can ask me on may email or just comment on this post because this is an important program to learn strings.


     In first line of main() char is used to declare 2 character variables j and k. This means these variables can store the one character each. In the second line char is used to declare strings variables. The numbers in square brackets indicate the maximum length of the string( maximum possible number of characters in that string). The function getchar() reads single character from keyboard and assign that character to the variable written on left side of it. In next line printf is used to print value of character variable k. Here %c is signifies that the value to be printed is a character(like %d signifies an integer). 


 In 8th line of main() scanf() is used to read a string of characters and assign that string to string variable s. For giving a string as input you have to hit ENTER key after that. If you want program to give desired result, don't give your first name with a space because scanf() stops reading a string whenever it encounters a space. Observe there is no & operator before s in this scanf statement. When we scan strings, we don't use & operator. Then next line printf() prints the first name. After that there is a getchar() function which assigns any character taken from keyboard to j. You are thinking that the program should ask you as I told before for but if you run the program, it doesn't demand a character as input. The reason for that is simple. Recall you just hit the ENTER key after your first name. This ENTER key is also a character. Your first name goes into s. Where does the ENTER key goes. It is not lost. This is used by the getchar() and assigned to j as a character literal(a character is also a literal).


    You can see that to verify this I have put an if else statement in this program. If j is ENTER or '\n', program will print "j is ENTER" otherwise character value of j will be printed whatever it is. Now the program again asks you for your full name. To read this I have used gets() function here. The gets function allows the spaces to be taken as a part of the given string. It scans anything in between until it finds the ENTER key. So here you can give your full name with spaces in between. The whole name is assigned to string variable t. This full name gets printed in the next printf() line. Recall that the variables store the value permanently until it is changed. To demonstrate another function putchar() to print a single character, I have again printed the value of k.

Remark:
     All of beginners are advised to practice 2 or 3 more programs of your own.