Monthly Archives: August 2013


An C program to Multiply two matrices (matrix)

Let’s identify variables needed for this program.

In this program, we need to save matrices which consists Rows and Columns. To save this we need Two dimensional ARRAY.

Multi dimensional Array is a nothing different than any Array but the only difference is that it has more than one deminsion to it e.g. square has two dimension and cube has three dimension. The Dimension of array is decided by us in number of square brackets [] selected. If We select two dimension than we have to take two square brackets[][]. It has to be accessed with the help of index number ranging from 0 to n-1 and 0 to m-1. (e.g. num[n][m] will have num[0][0],num[0][1],num[2][2] so on.) 

First few variables will be the one which will save the values entered by the user and it will be array A[3][3] and B[3][3]. Here we are taking 3 x 3 matrices hence taking number 3 in both the square brackets. Next variable will be array C[3][3] for saving resultant value which will be displayed later. other variables will be I, J and K which will be for FOR Loop so in all Five variables selected.
The identified variables are A[3][3],B[3][3],C[3][3],I,J,K;

int A[3][3],B[3][3],C[3][3],I,J,K;

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

In this program there is a requirement of accessing the two dimension array A[0][0],A[..][..],..A[2][2]. Here we have the index values ranging from zero to two (i.e. n-1) for ROWS and index values ranging from zero to two (i.e. n-1) for COLUMNS . Best Loop for such kind of condition is FOR Loop the value of loop will start with 0 to 2. Now here we need nested loop one loop inside the other. So that we can access all the Nine elements with it. We will need four nested loop,that is  in all eight FOR loops. First two nested loops for scanning required array values of Two matrices. Next nested loop will be nested with three FOR loop for multiplication of matrices and save it in the third empty matrix. and fourth nested loop for printing resultant array values as output.

This let’s you understand nested loop

for(I=0;I<3;I++)
    {
        for(J=0;J<3;J++)
        {
            scanf("%d",&A[I][J]);
        }
    }

Multiplication of two matrices is a bit complex as we have to do dot product of first row with first column multiply and add there product all the elements of the first matrix with row and other matrix with column. The matrices can only be added if the column of first matrix is equal to row of the second. To known more please click here 

for(I=0;I<3;I++)
    {
        for(J=0;J<3;J++)
        {
            C[I][J]=0;
            for(K=0;K<3;K++)
            {
                C[I][J]=C[I][J]+A[I][K]*B[K][J];
            }
        }
    }

Finally print the Numbers of Two Dimension Resultant Array in the Matrix form by using Tab (\t) and New Line (\n) character in the nested Loop at the end of the program.

for(I=0;I<3;I++)
    {
        for(J=0;J<3;J++)
        {
            printf("%d\t",C[I][J]);
        }
        printf("\n");
    }

C program code :

  1. #include<stdio.h>
  2. void main()
  3. {
  4.     int A[3][3],B[3][3],C[3][3],I,J,K;
  5.     clrscr();
  6.     printf("ENTER 3X3 MATRIX A VALUES\n");
  7.     for(I=0;I<3;I++)
  8.     {
  9.         for(J=0;J<3;J++)
  10.         {
  11.             scanf("%d",&A[I][J]);
  12.         }
  13.     }
  14.     printf("ENTER 3X3 MATRIX B VALUES\n");
  15.     for(I=0;I<3;I++)
  16.     {
  17.         for(J=0;J<3;J++)
  18.         {
  19.             scanf("%d",&B[I][J]);
  20.         }
  21.     }
  22.     for(I=0;I<3;I++)
  23.     {
  24.         for(J=0;J<3;J++)
  25.         {
  26.             C[I][J]=0;
  27.             for(K=0;K<3;K++)
  28.             {
  29.                 C[I][J]=C[I][J]+A[I][K]*B[K][J];
  30.             }
  31.         }
  32.     }
  33.     printf("RESULT 3X3 MATRIX C VALUES ARE :\n");
  34.     for(I=0;I<3;I++)
  35.     {
  36.         for(J=0;J<3;J++)
  37.         {
  38.             printf("%d\t",C[I][J]);
  39.         }
  40.         printf("\n");
  41.     }
  42.     getch();
  43. }

Note:- whenever you have large number of inputs to be entered, we can use space instead of enter button all the time. You can see have its done in Output screen.

SCREEN SHOTS:-

C_program_Matrix_Multiplication

C_program_Matrix_Multiplication_Output

A C program to Add two matrices (matrix) or Subtract two matrices (matrix)

Let’s identify variables needed for this program.

In this program, we need to save matrices which consists Rows and Columns. To save this we need Two dimensional ARRAY.

Multi dimensional Array is a nothing different than any Array but the only difference is that it has more than one deminsion to it e.g. square has two dimension and cube has three dimension. The size of array is decided by us in number of square brackets [] depending upon the Dimension selected. If We select two dimension than we have to take two square brackets[][]. It has to be accessed with the help of index number ranging from 0 to n-1 and 0 to m-1. (e.g. num[0][0],num[0][1],num[2][2] so on.) 

First few variables will be the one which will save the values entered by the user and it will be array A[3][3] and B[3][3]. Here we are taking3x3 matrices hence taking number 3 in both the square brackets. Next variable will be array C[3][3] for saving resultant value which will be displayed later. other variables will be I and J which will be for FOR Loop so in all Four variables.
The identified variables are A[3][3],B[3][3],C[3][3],I,J;

int A[3][3],B[3][3],C[3][3],I,J;

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

In this program there is a requirement of accessing the two deminsion array A[0][0],A[..][..],..A[2][2]. Here we have the index values ranging from zero to two (i.e. n-1) for ROWS and index values ranging from zero to two (i.e. n-1) for COLUMNS . Best Loop for such kind of condition is FOR Loop the value of loop will start with 0 to 2. Now here we need nested loop one loop inside the other. So that we can access all the Nine elements with it. We will need four nested loop in all eight FOR loops, First two nested loops for scanning required array values of Two matrices. Next nested loop for addition of matrices and save it in the third empty matrix. and fourth nested loop for printing resultant array values as output.

This let’s you understand nested loop

for(I=0;I<3;I++)
    {
        for(J=0;J<3;J++)
        {
            scanf("%d",&A[I][J]);
        }
    }

Subtracting two matrices is simple as we have to subtract all the elements of the first matrix with same row and column to the other matrix. The matrices can only be subtracted if the row and column is same. To known more please click here 

for(I=0;I<3;I++)
    {
        for(J=0;J<3;J++)
        {
            C[I][J]=A[I][J]+B[I][J];
        }
    }

For substraction of two matrices we need to change only the PLUS sign to MINUS sign and Done program changes from Addition of two matrices to Substraction of two matrices.

for(I=0;I<3;I++)
    {
        for(J=0;J<3;J++)
        {
            C[I][J]=A[I][J]-B[I][J];
        }
    }

Finally print the Numbers of Two Dimension Resultant Array in the Matrix form by using Tab and New Line character in the nested Loop at the end of the program.

for(I=0;I<3;I++)
    {
        for(J=0;J<3;J++)
        {
            printf("%d\t",C[I][J]);
        }
        printf("\n");
    }

C program code :

  1. #include<stdio.h>
  2. void main()
  3. {
  4.     int A[3][3],B[3][3],C[3][3],I,J;
  5.     clrscr();
  6.     printf("ENTER 3X3 MATRIX A VALUES\n");
  7.     for(I=0;I<3;I++)
  8.     {
  9.         for(J=0;J<3;J++)
  10.         {
  11.             scanf("%d",&A[I][J]);
  12.         }
  13.     }
  14.     printf("ENTER 3X3 MATRIX B VALUES\n");
  15.     for(I=0;I<3;I++)
  16.     {
  17.         for(J=0;J<3;J++)
  18.         {
  19.             scanf("%d",&B[I][J]);
  20.         }
  21.     }
  22.     for(I=0;I<3;I++)
  23.     {
  24.         for(J=0;J<3;J++)
  25.         {
  26.             C[I][J]=A[I][J]+B[I][J];
  27.         }
  28.     }
  29.     printf("RESULT 3X3 MATRIX C VALUES ARE :\n");
  30.     for(I=0;I<3;I++)
  31.     {
  32.         for(J=0;J<3;J++)
  33.         {
  34.             printf("%d\t",C[I][J]);
  35.         }
  36.         printf("\n");
  37.     }
  38.     getch();
  39. }

Note:- whenever you have large number of inputs to be entered, we can use space instead of enter button all the time. You can see have its done in Output screen.

SCREEN SHOTS:-

C_program_Matrix_Addition

C_program_Matrix_Addition_Output

An interactive C program that will take as input a set of 20 integers and store them in an array and using a temporary array of equal length, reverse the order of the integers & display the values.

Let’s identify variables needed for this program.

In this program, we need several variables to store and compare the values to find the largest and the smallest out of them. Its not recommended to take number of variables declared of the same data type with different names and remembering it. It becomes worst when the variable numbers goes on increasing to large number. Hence we have a savior called ARRAY.

Array is a nothing different than any variable but the only difference is that it allows us to use more than one variables with a single name to it. The size of array is decided by us. We can take 2 to n numbers according to our requirement. It has to be accessed with the help of index number ranging from 0 to n-1. (e.g. num[0],num[1],num[2],num[3]) 

First variable will be the one which will save the values entered by the user and it will be array NUM[20]. Here we are taking twenty different values hence taking number 20. Second variable will be array TEMP[20] for saving temporary reversed values which will be displayed later. other variables will be I which will be for FOR Loop and J will help us in the reversing logic index so in all Four variables.
The identified variables are NUM[20],TEMP[20],I,J.

int NUM[20],TEMP[20],I,J;

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

In this program there is a requirement of accessing the array NUM[0],NUM[1]….NUM[9]. Here we have the index values ranging from zero to the given number minus one (i.e. n-1) . Best Loop for such kind of condition is FOR Loop the value of loop will start with 0 to 19. We will need four FOR loops, First one for scanning required array values. Second one for reversing all the numbers found in original array. and third & fourth ones for printing original array values and reversed array values.

In this program, The main thing to do is reverse the array elements and save in another array. As we know, the array index of NUM[20] starts with 0 – 19 and same with TEMP[20] that is 0 – 19, so if we see it in reverse order it will be 19 – 0 main logic of the program is that initialize the variable with 19 and decrement J by J– with the loop which executing for 20 times. No need to worry about when to stop.

J=19;
    for(I=0;I<20;I++)
    {
        TEMP[J]=NUM[I];
        J--;
    }

Finally print the Numbers of Original Array and Reverse Array at the end of the program.

C program code :

  1. #include<stdio.h>
  2. void main()
  3. {
  4. int NUM[20],TEMP[20],I,J;
  5. clrscr();
  6. printf("ENTER TWENTY NUMBERS TO BE REVERSED\n");
  7. for(I=0;I<20;I++)
  8. {
  9. scanf("%d",&NUM[I]);
  10. }
  11. J=19;
  12. for(I=0;I<20;I++)
  13. {
  14. TEMP[J]=NUM[I];
  15. J--;
  16. }
  17. printf("\nORIGINAL NUMBERS ARE :- \n");
  18. for(I=0;I<20;I++)
  19. {
  20. printf(" %d\t",NUM[I]);
  21. }
  22. printf("\nREVERSE NUMBERS ARE :- \n");
  23. for(I=0;I<20;I++)
  24. {
  25. printf("\t %d",TEMP[I]);
  26. }
  27. getch();
  28. }

Note:- whenever you have large number of inputs to be entered, we can use space instead of enter button all the time. You can see have its done in Output screen.

SCREEN SHOTS:-

C_program_Array_Reverse

C_program_Array_Reverse_Output

A C program that will take as input a set of integers and find and display the largest and the smallest values within the input data values

Let’s identify variables needed for this program.

In this program, we need several variables to store and compare the values to find the largest and the smallest out of them. Its not recommended to take number of variables declared of the same data type with different names and remembering it. It becomes worst when the variable numbers goes on increasing to large number. Hence we have a savior called ARRAY.

Array is a nothing different than any variable but the only difference is that it allows us to use more than one variables with a single name to it. The size of array is decided by us. We can take 2 to n numbers according to our requirement. It has to be accessed with the help of index number ranging from 0 to n-1. (e.g. num[0],num[1],num[2],num[3]) 

First variable will be the one which will save the values entered by the user and it will be NUM[10]. Here we are taking ten different values hence taking number 10. Second variable will be I which will be for FOR Loop. other variables will be holding largest and smallest numbers and it will be LARGE and SMALL so in all Four variables.
The identified variables are NUM,I,LARGE,SMALL.

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

In this program there is a requirement of accessing the array NUM[0],NUM[1]….NUM[9]. Here we have the index values ranging from zero to the given number minus one (i.e. n-1) . Best Loop for such kind of condition is FOR Loop the value of loop will start with 0 to 9. We will need two FOR loops, First one for scanning required array values and Second one for comparing all the other numbers to find largest and smallest out of them.

The variable for largest and smallest are already taken. But the problem is both are having no values inside it to compare so the logic is assign the first value to both LARGE and SMALL. So that we have the first value to compare and replace it with the other larger or smaller value with LARGE and SMALL respectively. Comparison is done with the help of IF condition below. FOR Loop the value of loop will start with 1 to 9. We will need this because First value is already assigned now we need to compare all the other numbers except the first to find largest and smallest out of them.

if(LARGE<NUM[I])
         LARGE=NUM[I];
 if(SMALL>NUM[I])
          SMALL=NUM[I];

Finally print the Numbers as Largest and Smallest at the end of the program.

C program code :

  1. #include<stdio.h>
  2. void main()
  3. {
  4. int NUM[10],I,LARGE,SMALL;
  5. clrscr();
  6. printf("ENTER TEN NUMBERS TO COMPARE\n");
  7. for(I=0;I<10;I++)
  8. {
  9. printf("\nENTER NUMBER : ");
  10. scanf("%d",&NUM[I]);
  11. }
  12. LARGE=SMALL=NUM[0];
  13. for(I=1;I<10;I++)
  14. {
  15. if(LARGE<NUM[I])
  16. LARGE=NUM[I];
  17. if(SMALL>NUM[I])
  18. SMALL=NUM[I];
  19. }
  20. printf("\nTHE LARGER NUMBER IS %d", LARGE);
  21. printf("\nThe SMALLER NUMBER IS %d", SMALL);
  22. getch();
  23. }

SCREEN SHOTS:-

C_program_Large_Small

C_program_Large_Small_Output

A C program that uses macros, MIN & MAX, to find and return, respectively the minimum & maximum of two values

Macro are the small code which is substituted wherever the macro is refered. macros can be used in two ways :

First way as a replacement to the code which is long in length or repeated all the time.  e.g. #define CUBE(X) (X*X*X)

Second way as a small function in which we can pass arguments and return results. In this method, we have to use Ternary operator. e.g. #define ABSOLUTE(NUM)  ((NUM) < 0) ? -(NUM) : (NUM)

Ternary operator is a conditional operator (?:) which is related to the if-else structure.
syntax looks like this :
(condition)? (expression1): (expression2);

First part is a conditional expression. Second part represents the value to be evaluated if condition is true. Third part is represents the value to be evaluated if condition is false.

Let’s write Macro for Minimum (MIN) and maximum (MAX).

#define MIN(X,Y) (X<Y ? X:Y)
#define MAX(X,Y) (X>Y ? X:Y)

Here we are passing two arguments to Macro (i.e. X & Y) and checking condition if X is less than Y and if the condition is True than the X variable is returned (This placed can be written by any Expression to be evaluated or a simple variable also.)  and if the condition is False than the Y variable is returned.

Now, let’s find varibles needed

Since we are going to use the above macro as a function call, hence we will need two variables i.e. FIRST and SECOND.

Data type will be int (integer) data type as numbers will be entered by user and check the min value and the max value.

Enter message for user to enter values, scan the values and save it in respective variables. Call the macro similar to function call and the value will be returned to the calling position. print the values done.

C program code:

#include<stdio.h>
 
#define MIN(X,Y)(X<Y ? X:Y)
#define MAX(X,Y)(X>Y ? X:Y)
 
void main()
{
    int FIRST,SECOND;
    clrscr();
    printf("ENTER NUMBERS TO COMPARE\n");
    printf("\nFIRST NUMBER : ");
    scanf("%d", &FIRST);
    printf("\nSECOND NUMBER : ");
    scanf("%d", &SECOND);
    printf("\nTHE LARGER NUMBER IS %d", MAX(FIRST,SECOND));
    printf("\nThe SMALLER NUMBER IS %d", MIN(FIRST,SECOND));
    getch();
}

Screen Shots:-

C_program_Ternary_Min_Max

C_program_Ternary_Min_Max_Output

A C program to write a function that calculates the compounded interest amount for a given initial amount, interest rate & no. of years. The interest is compounded annually. The return value will be the interest amount

First thing to know before writing this program is the Simple interest Formula.

COMPOUND INTEREST = (P *(1+R) N)

  • P = PRINCIPAL AMOUNT.
  • N = NUMBER OF YEARS (TIME).
  • R = RATE OF INTEREST.

Here the problem is the rate of interest should be in the form of 0.10 instead of 10%.

Now, find out the variables needed for calculating Compound interest.

CI = (P *(1+R) N)

By looking at the formula, we have CI, P,  N, R. (i.e. Four Variables)

Now decide the data type.

int, float, and double are the choices for the variable to be used, since we are using only fraction number and not the whole number due to the complexity of the formula(i.e. rate of interest should be in the form of 0.10 instead of 10%). Hence we will omit int. Select float and double as our data type.

Two variables which will hold bigger values compared to other are SI and P. hence we will use double data type with qualifier for SI and P. For the other two N and R float data type will be sufficient.

float N,R;
double CI,P;

data type and variables selection done.

Interactive means the program will not have any hardcoded values assigned to variables but user has to provide them.

To get values from the user screen we have a function called scanf() which will help us to scan values entered by the user by keyboard and visible on the screen.

We cannot expect that user should enter values in the sequence blindly without knowing what to enter. For that purpose we should guide the user to enter expected values by displaying message.

(E.g. ENTER THE PRINCIPAL AMOUNT: ) than scan the value entered for principal in P. and so on.

CI = (P *(1+R) N);

This formula has a raise to N this can be achieved by using a inbuilt function called pow() function which is there in another header file called math.h So we have to INCLUDE math.h in our program.

e.g.  XY can be written as pow(X,Y) and So.

This COMPOUND interest formula cannot be written on a single line statement. So we write it in two statements as:

 

CI=pow(1+R,N);
 
CI=P*CI;
 
printf("THE CALCULATED SIMPLE INTEREST IS RUPEES : %.2f",CI);

 

Here we are using %.2f instead of %f so that the Amount is Printed to Two Decimal Digits.

Note:- Remember whenever you are scanning or printing the values of double be careful to  write %lf instead of just %f. Because %lf is used for double data type and %f is used for float data type.

C program code

#include<stdio.h>
#include<math.h>
void main()
{
float N,R;
double CI=0,P;
clrscr();
printf("ENTER THE PRINCIPAL AMOUNT : ");
scanf("%f",&P);
printf("ENTER THE NUMBER OF YEAR(S) : ");
scanf("%f",&N);
printf("ENTER THE RATE OF INTEREST(%) : ");
scanf("%f",&R);
R=R/100;
CI=pow(1+R,N);
CI=P*CI;
printf("THE CALCULATED SIMPLE INTEREST IS RUPEES : %.2f",CI);
getch();
}

Use the following function definition: float comp_int_calc(floatint_amt, float rate, int years); Write a program that will accept the initial amount, interest rate & the no. of years and call the function with these values to find out the interest amount and display the returned value

Now the thing we have to do is split the above program in to two parts

One part will be the MAIN function part and the other part will be the COMP_INT_CALC function part

Here, since the definition of function is already given (i.e.float comp_int_calc(floatint_amt, float rate, int years) we need to change the variables from the old data types to the new defined data types in the function. And also declare the prototype of the function used there itself. (Note: declaration of the function can be done with variable name or only with data type excluding varaible names)

float R,P,CI;
int N;
float comp_int_calc(float,float,int);

Now, in main function only the calculation code will go to the function body part and else every thing will be the same.

void main()
{
float R,P,CI;
int N;
float comp_int_calc(float,float,int);
clrscr();
printf("ENTER THE PRINCIPAL AMOUNT : ");
scanf("%f",&P);
printf("ENTER THE NUMBER OF YEAR(S) : ");
scanf("%d",&N);
printf("ENTER THE RATE OF INTEREST(%) : ");
scanf("%f",&R);
R=R/100;
CI=comp_int_calc(P,R,N);
printf("THE CALCULATED SIMPLE INTEREST IS RUPEES : %.2f",CI);
getch();
}

Note:- Becareful while passing the parameters or arguments to the function keep the sequence same or there will be error in the program.

float comp_int_calc(float AMT,float RATE,int YEARS)

CI=comp_int_calc(P,R,N);

In the function, we can keep the same name of the varaibles we are passing or use the new names altogether. The scope of main function variables are limited to main function itself. The variables with the same name in the outer function will have scope inside the function only.

After changing the names to variable according to the defination of the function, we have function to be as below:

float comp_int_calc(float AMT,float RATE,int YEARS)
{
float COMP_INT=0;
COMP_INT=pow(1+RATE,YEARS);
COMP_INT=AMT*COMP_INT;
return COMP_INT;
}

The complete program will be as below:

C program code

  1. #include<stdio.h>
  2. #include<math.h>
  3. void main()
  4. {
  5. float R,P,CI;
  6. int N;
  7. float comp_int_calc(float,float,int);
  8. clrscr();
  9. printf("ENTER THE PRINCIPAL AMOUNT : ");
  10. scanf("%f",&P);
  11. printf("ENTER THE NUMBER OF YEAR(S) : ");
  12. scanf("%d",&N);
  13. printf("ENTER THE RATE OF INTEREST(%) : ");
  14. scanf("%f",&R);
  15. R=R/100;
  16. CI=comp_int_calc(P,R,N);
  17. printf("THE CALCULATED SIMPLE INTEREST IS RUPEES : %.2f",CI);
  18. getch();
  19. }
  20.  
  21. float comp_int_calc(float AMT,float RATE,int YEARS)
  22. {
  23. float COMP_INT=0;
  24. COMP_INT=pow(1+RATE,YEARS);
  25. COMP_INT=AMT*COMP_INT;
  26. return COMP_INT;
  27. }

SCREEN SHOTS:-

C_program_Compound_Interest_Function

C_program_Compound_Interest_Function_Output

Break up the program that you wrote to solve above problem into two separate source files. The main function should be in one file & the calculation function must be in another file. And modify the program so that the interest rate is a symbolic constant and is no longer input from the keyboard. And put all the C preprocessor directives into a separate header file that is included in the two program source files.

#include is an instruction used to read the functions written in header files which are also called library files.

#include can be used with < > or ” “  e.g. #include<compound.h> or #include”compound.h” both are used depending upon the file located. If the included file is located in the library files or the same location where the other header files than we have to use <>   e.g. #include<compound.h> and If the included file is located in the same folder where the calling program is present than we have to use ” ”   e.g. #include”compound.h”.

Now, cut the function part and save it in another name the file compound.h

File :- compound.h

float comp_int_calc(float AMT,float RATE,int YEARS)
{
float COMP_INT=0;
COMP_INT=pow(1+RATE,YEARS);
COMP_INT=AMT*COMP_INT;
return COMP_INT;
}

Now, the changes needed are only including a file by #include”compound.h” and there is no need of declaration of function, so delete that function declaration or comment that line by just adding \\ infront of the line which is to be commented. If you need to comment several lines then you can use /*on the first line and */ on the last line to be commented.

Note:- comment has no effect inside the code. It’s basically used for for giving  information to the user thought comments.

C program code

  1. #include<stdio.h>
  2. #include<math.h>
  3. #include"compound.h"
  4. void main()
  5. {
  6. float R,P,CI;
  7. int N;
  8. //float comp_int_calc(float,float,int);
  9. clrscr();
  10. printf("ENTER THE PRINCIPAL AMOUNT : ");
  11. scanf("%f",&P);
  12. printf("ENTER THE NUMBER OF YEAR(S) : ");
  13. scanf("%d",&N);
  14. printf("ENTER THE RATE OF INTEREST(%) : ");
  15. scanf("%f",&R);
  16. R=R/100;
  17. CI=comp_int_calc(P,R,N);
  18. printf("THE CALCULATED SIMPLE INTEREST IS RUPEES : %.2f",CI);
  19. getch();
  20. }

SCREEN SHOTS:-

C_program_Compound_Interest_Header

C_program_Compound_Interest_Header_File

C_program_Compound_Interest_Function_Output

A C program to write a function invert(x, p, n) that returns x with the n bits that begin at position p inverted. You can assume that x, p & n are integer variables and that the function will return an integer

As an example, if x = 181 in decimal which is 10110101 in binary, and p = 4 and n = 2, then the function will return 10101101 or 173 in decimal. The underlined bits are the changed bits. Note that bit positions are counted from the right to the left and that the counts start with a 0 (zero). Therefore, position 4 is the 5th bit from the right values.

Explanation of FUNCTION:

A function is a block of code that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required.

Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by itself. Instead its requests other program like entities – called functions in C – to get its tasks done. A function is a self contained block of statements that perform a coherent task of same kind.

The name of the function is unique in a C Program and is Global. It means that a function can be accessed from any location within a C Program. We pass information to the function called arguments specified when the function is called. And the function either returns some value to the point it was called from or returns nothing.

We can divide a long C program into small blocks which can perform a certain task. A function is a self contained block of statements that perform a coherent task of same kind.

 

First thing to know before writing this program is conversion of decimal to binary and  conversion of binary to decimal since mainly what is to be done is convert decimal to binary and vice versa and change the inner value and invert the inner digits of binary form of integer.

For more details on conversion of binary to decimal click this link http://www.wikihow.com/Convert-from-Decimal-to-Binary

For more details on conversion of decimal to binary click this link http://www.wikihow.com/Convert-from-Binary-to-Decimal

 

For writing a function and using it in the C program, we should declare the function in the MAIN function. Declaration has to done in the area before the code starts, same area where we declare data variables.

int invert(int,int,int);

Function returns value and the ones which does not return any value is called and declared as void. This function which we are writing returns the changed (inverted) value in decimal form as output. The values inside the round brackets are called Arguments. All the Arguments and return type are integer type. A function can return only one value so we have to take only one data type in which its value is expected.

 

Let’s identify variables needed for this program.
First variables will be the one which will save the value entered by the user and it will be X, P and N.  Other variable will be RESULT which will be for holding the resultant values returned by the FUNCTION. The identified variables are X, P, N and RESULT.

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

Main program needs only declaration of variables and function prototype. Also messages for user and scanning values  X, P, N and RESULT is used to display the resultant values returned by the FUNCTION.

#include<stdio.h>
void main()
{
     int X,P,N,RESULT;
     int invert(int,int,int);
     clrscr();
     printf("ENTER ANY INTEGER TO INVERT (X) : \n");
     scanf("%d",&X);
     printf("ENTER THE START POSITION TO INVERT (P) :\n");
     scanf("%d",&P);
     printf("ENTER THE LENGTH TO INVERT (N) :\n");
     scanf("%d",&N);
     printf("CONVERTED BINARY VALUE OF %d IS \t",X);
     RESULT=invert(X,P,N);
     printf("\nINVERTED INTEGER IN DECIMAL FORM IS \t%d",RESULT);
     getch();
}

Let’s identify variables needed for function which is part of program outside main function.
Variables which are passed in the function may not be declared again which are X, P and N.  Now the variables Y which will hold the resultant value to be returned by the FUNCTION. Variable BIN[15] will be holding the binary form of the integer entered by the user and should fit inside it sufficiently,  we take an array of integer of length 15 to hold 15 digits of binary number , since there no other data type to hold binary values. Variable LEN is to find the length of the binary digits inside the array. Variable I which will be for FOR Loop. Variable LIMIT will be helping us to check the value of P and N added together should not exceed length of binary form integer. The identified variables are I, Y, LIMIT, LEN and BIN[15].

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

int I,Y,LIMIT,LEN,BIN[15];

 

Explaination of WHILE LOOP:

while (condition){}

We can check condition in while loop. Condition will always give you the result to be True or False. LOOP continues till the condition is True and Stops when condition is False. If condition is not going to be false by itself, you need increment or decrement so that the value which is set has to change and make the Condition False sometime to be terminated.

Code for converting decimal to binary

Here initialize length to zero. X is the integer entered by the user it should be a positive integer and for converting decimal to binary the remainder is saved inside array (BIN []) at LEN position which is initially zero and increases till the integer is positive. Now the value of X integer should be saved by the Quotient of the integer divided by two.

LEN=0;
     while(X>0)
     {
                BIN[LEN]=X%2;
                X=X/2;
                LEN++;
     };

Code for printing binary form of integer

Since the array formed is in the reverse form of binary equivalent the printing of array values is done in the reverse form. Variable LEN gives us the length and array is always starting with 0 to len-1, hence the first value to print is on position BIN[LEN-1] and last value is on position BIN[0]. To have a reverse movement we need decrement, so we have I—(I minus minus i.e. i=i-1). Now print the value which in an array at position I (i.e. BIN[I]).

for(I=LEN-1;I>-1;I--)
     {
                printf("%d ",BIN[I]);
     }

In this program there is a risk of generating an ERROR or exception. Here we have to Check the values given in P and N variables, which should be smaller numbers. P should be less than LEN length (i.e. P<LEN) and N should also be less than LEN length (i.e. N<LEN). Hence if condition checking LIMIT less than LEN. And LIMIT holding addition of P and N (i.e. LIMIT =P+N). and if condition is false printing appropriate message to the user.

if(LIMIT < LEN)
{
\\Code to convert
}
else
{
printf("YOU HAVE ENTERED LARGE VALUE FOR P AND N");
}

Code for inverting the binary values from given position P and to the N number of values to be changed.

Variable P gives us the position from where the values are to be inverted and the value of I will be initialized to P-1, since array is always starting with 0 to len-1 and till P+N-1 (i.e. 4th position will be Bin[3]). Now were ever we find ONE replace it by ZERO and vice versa. And save the inverted value in array at position I (i.e. BIN[I]).

for(I=P-1;I<P+N-1;I++)
{
if(BIN[I]==0)
BIN[I]=1;
else
BIN[I]=0;
}

After this print inverted binary value and there is \t used in printf function which is a TAB character the other which we now is \n which is NEW LINE character.

Code for converting binary to decimal

Here FOR loop starts with LEN-1 is zero. Y is the integer to hold new decimal integer after inverting given integer and for converting binary to decimal the remainder is added to Y from array position (BIN [I]) which is initially zero or one and multiplied to TWO. Now the decimal equivalent value of binary inverted  integer saved in Y variable and returned back from where it is called.

for(I=LEN-1;I>=0;I--)
     {
            Y=Y*2+BIN[I];
     }
return Y;

Note:- Remember whenever you are calling a function which is returning a value it should always be assigned to a variable of same data type or called inside the printf function as variable.

C program code :

  1. #include<stdio.h>
  2. void main()
  3. {
  4. int X,P,N,RESULT;
  5. int invert(int,int,int);
  6. clrscr();
  7. printf("ENTER ANY INTEGER TO INVERT (X) : \n");
  8. scanf("%d",&X);
  9. printf("ENTER THE START POSITION TO INVERT (P) :\n");
  10. scanf("%d",&P);
  11. printf("ENTER THE LENGTH TO INVERT (N) :\n");
  12. scanf("%d",&N);
  13. printf("CONVERTED BINARY VALUE OF %d IS \t",X);
  14. RESULT=invert(X,P,N);
  15. printf("\nINVERTED INTEGER IN DECIMAL FORM IS \t%d",RESULT);
  16. getch();
  17. }
  18.  
  19. int invert(int X,int P,int N)
  20. {
  21. int I,Y,LIMIT,LEN,BIN[15];
  22. LEN=0;
  23. while(X>0)
  24. {
  25. BIN[LEN]=X%2;
  26. X=X/2;
  27. LEN++;
  28. };
  29.  
  30. for(I=LEN-1;I>-1;I--)
  31. {
  32. printf("%d ",BIN[I]);
  33. }
  34. printf("\n");
  35. LIMIT=P+N;
  36. if(LIMIT < LEN)
  37. {
  38. for(I=P-1;I<P+N-1;I++)
  39. {
  40. if(BIN[I]==0)
  41. BIN[I]=1;
  42. else
  43. BIN[I]=0;
  44. }
  45. }
  46. else
  47. {
  48. printf("YOU HAVE ENTERED LARGE VALUE FOR P AND N");
  49. }
  50.  
  51. printf("INVERTED INTEGER IN BINARY FORM IS \t");
  52. for(I=LEN-1;I>-1;I--)
  53. {
  54. printf("%d ",BIN[I]);
  55. }
  56. Y=0;
  57. for(I=LEN-1;I>=0;I--)
  58. {
  59. Y=Y*2+BIN[I];
  60. }
  61. return Y;
  62. }

Screen Shots :-

C_program_Invert_Function

C_program_Invert_Function_Output

An interactive C program to find the roots of a Quadratic equation

First thing to know before writing this program is the Quadratic Equation Formula.

Quadratic_Eqn

Here the problem is the this whole Quadratic Equation can not be written on single line.

Now, find out the variables needed for calculating Roots of Quadratic Equation.

X1 = (-B-Square Root(b 2 – 4AC))/2A    AND   X2 = (-B+Square Root(b 2 – 4AC))/2A

By looking at the formula, we have A,B,C,R1,R2, we need two more for splitting the Equation into parts, So we need PART,EQN. (i.e. in all SEVEN Variables)

Now decide the data type.

int, float, and double are the choices for the variable to be used, since we are using only fraction number and not the whole number due to the complexity of the Quadratic Equation. Hence we will omit int. Select float as our data type.

float A,B,C,R1,R2,PART,EQN;

data type and variables selection done.

Interactive means the program will not have any hardcoded values assigned to variables but user has to provide them.

To get values from the user screen we have a function called scanf() which will help us to scan values entered by the user by keyboard and visible on the screen.

We cannot expect that user should enter values in the sequence blindly without knowing what to enter. For that purpose we should guide the user to enter expected values by displaying message.

(E.g. ENTER THE VALUE OF A : ) than scan the value entered for A, B and C.

X1 = (-B-Square Root(b 2 – 4AC))/2A    AND   X2 = (-B+Square Root(b 2 – 4AC))/2A

This formula has a Raise to 2 this can be achieved by using a inbuilt function called pow() function which is there in another header file called math.h So we have to INCLUDE math.h in our program.

e.g.  XY can be written as pow(X,Y) and So.

This Quadratic Equation formula cannot be written on a single line statement. So we write it in several statements as:

Here the problem is that how to calculate Square Root, This can be achieved by using a inbuilt function called sqrt() function which is there in math.h, Now problem with sqrt() function is we cannot pass negative value to it otherwise it gives an exception(ERROR). This problem can be solved by using a inbuilt function called abs() function which is a absolute function which passes only Absolute (Positive) value to the sqrt() function. If the value which is passed is negative value then it’s Absolute (Positive) value has to be assigned a negative value after the result is obtained.

EQN=pow(B,2)-(4*A*C);
if(EQN<0)
{
    PART=sqrt(abs(EQN));
    PART=-PART;
}
else
{
   PART=sqrt(EQN);
}
R1=(-B+PART)/(2*A);
R2=(-B-PART)/(2*A);

 

Here we are using %.2f instead of %f so that the value is Printed to Two Decimal Digits.

Note:- Remember whenever you are using sqrt() function be careful to  pass positive value or if you are not sure than pass the value by Absolute function inside instead of passing a negative value unknowingly.

C program code:

  1. #include<stdio.h>
  2. #include<math.h>
  3. void main()
  4. {
  5. float A,B,C,R1,R2,PART,EQN;
  6. clrscr();
  7. printf("ENTER THE VALUE OF A : ");
  8. scanf("%f",&A);
  9. printf("ENTER THE VALUE OF B : ");
  10. scanf("%f",&B);
  11. printf("ENTER THE VALUE OF C : ");
  12. scanf("%f",&C);
  13. EQN=pow(B,2)-(4*A*C);
  14. if(EQN<0)
  15. {
  16. PART=sqrt(abs(EQN));
  17. PART=-PART;
  18. }
  19. else
  20. {
  21. PART=sqrt(EQN);
  22. }
  23. R1=(-B+PART)/(2*A);
  24. R2=(-B-PART)/(2*A);
  25. printf("THE CALCULATED ROOTS ARE : %.2f AND %.2f",R1,R2);
  26. getch();
  27. }

Screen Shots:-

C_program_Quadratic

C_program_Quadratic_Output

An interactive C program to check whether given two numbers are amicable numbers or not

Amicable numbers are two numbers so related that the sum of the proper divisors of the one is equal to the other, unity being considered as a proper divisor but not the number itself.

Let’s identify variables needed for this program.
First two variables will be the one which will save the values entered by the user and it will be NUM1, NUM2. Other two variables will be i,j which will be for FOR Loops. Last variable will be holding sum of  all the divisors of two numbers and it will be SUM1 and SUM2  so in all SIX variables.
The identified variables are NUM1,NUM2, i,j,SUM1,SUM2.

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

In this program there is a requirement of generating the divisors. Here we have to Check the values from 1 to the given number. It indicates LOOP is to be taken. Best Loop for such kind of condition is FOR Loop.
Loop selected is FOR Loop.

Now give the user a message to enter a value and scan the input from the user and save it in NUM1 and NUM2 variables.
for(i=0;i<NUM;i++) this FOR loop will give you DIVIDE ERROR. So be careful while initializing i=1 instead of i=0.
For Loop will start with 1 to NUM-1.To identify whether the number is divisor or not. We have to divide that number by given number(NUM1 and NUM2). If the remainder is zero than number entered is an divisor and if the remainder is not zero than number is not a divisor. This can be achieved by % (modulus) operator which is giving us the remainder.

The condition will be NUM1%i and NUM2%j in FOR Loops. If the remainder will be zero, INSTEAD of printing the number divisible as output values in this program, we will sum the divisors generated and save it in SUM1 and SUM2 by equation SUM1=SUM1+i and SUM2=SUM2+j.

If the total sum of divisor of a given number is equal to the given number itself than check this condition by NUM1==SUM2 && NUM2==SUM1 and if its equal than print the message TWO NUMBERS ARE AMICABLE NUMBERS else print message  TWO NUMBERS ARE NOT AMICABLE NUMBERS.

  1. #include<stdio.h>
  2. void main()
  3. {
  4. int NUM1,NUM2,i,j,SUM1=0,SUM2=0;
  5. printf("\nENTER TWO INTERGER TO CHECK IF THEY ARE AMICABLE NUMBERS :\n");
  6. scanf("%d",&NUM1);
  7. scanf("%d",&NUM2);
  8. for(i=1;i<NUM1;i++)
  9. {
  10. if(NUM1%i==0)
  11. {
  12. SUM1=SUM1+i;
  13. }
  14. }
  15. for(j=1;j<NUM2;j++)
  16. {
  17. if(NUM2%j==0)
  18. {
  19. SUM2=SUM2+j;
  20. }
  21. }
  22. if(NUM1==SUM2 && NUM2==SUM1)
  23. {
  24. printf("\n%d AND %d ARE AMICABLE NUMBERS",NUM1,NUM2);
  25. }
  26. else
  27. {
  28. printf("\n%d AND %d ARE NOT AMICABLE NUMBERS",NUM1,NUM2);
  29. }
  30. getch();
  31. }

SCREEN SHOTS:-

C_program_Amicable

C_program_Amicable_Output

An interactive C program to check whether a given number is a perfect number or not

A positive number is called Perfect Number if it is equal to the sum of all of its positive divisors,  excluding number itself.

Let’s identify variables needed for this program.
First variable will be the one which will save the value entered by the user and it will be NUM. Second variable will be i which will be for FOR Loop. Last variable will be holding sum of  all the divisors and it will be SUM so in all three variables.
The identified variables are NUM, i,SUM.

Now, Selection of data type is int data type due to the values expected are decimals and they will be holding smaller values so int data type is sufficient.

In this program there is a requirement of generating the divisors. Here we have to Check the values from 1 to the given number. It indicates LOOP is to be taken. Best Loop for such kind of condition is FOR Loop.
Loop selected is FOR Loop.

Now give the user a message to enter a value and scan the input from the user and save it in NUM variable.
for(i=1;i<NUM;i++) this FOR loop will give you DIVIDE ERROR. So be careful while initializing i=1 instead of i=0.
For Loop will start with 1 to NUM-1.To identify whether the number is divisor or not. We have to divide that number by given number(NUM). If the remainder is zero than number entered is an divisor and if the remainder is not zero than number is not a divisor. This can be achieved by % (modulus) operator which is giving us the remainder.

The condition will be NUM%i in FOR Loop. If the remainder will be zero, INSTEAD of printing the number divisible as output values in this program, we will sum the divisors generated and save it in SUM by equation SUM=SUM+i.

If the total sum of divisor of a given number is equal to the given number itself than check this condition by SUM==NUM and if its equal than print the message NUMBER IS A PERFECT NUMBER else print message  NUMBER IS NOT A PERFECT NUMBER.

C program code :

  1. #include<stdio.h>
  2. void main()
  3. {
  4. int NUM,i,SUM=0;
  5. printf("\nENTER ANY INTERGER AND FIND IS IT PERFECT NUMBER : ");
  6. scanf("%d",&NUM);
  7. for(i=1;i<NUM;i++)
  8. {
  9. if(NUM%i==0)
  10. {
  11. SUM=SUM+i;
  12. }
  13. }
  14. if(SUM==NUM)
  15. {
  16. printf("\n%d IS A PERFECT NUMBER",NUM);
  17. printf(" SINCE SUM OF DIVISORS IS %d \n",SUM);
  18. }
  19. else
  20. {
  21. printf("\n%d IS NOT A PERFECT NUMBER",NUM);
  22. printf(" SINCE SUM OF DIVISORS IS %d \n",SUM);
  23. }
  24. getch();
  25. }

SCREEN SHOTS:-

C_program_Perfect_No

C_program_Perfect_No_Output