facebook like button

28 May, 2011

program 49: scanning and accessing structure in C

The need: 
      This is a program to demonstrate the use of structure in C program. This shows how a struct keyword can be used to define a structure form a collection of several variables of different (or may be same) type and how individual members of any struct type variable can be accessed and modified.

The code: 
--------------------------------------------
#include<stdio.h>
#include<string.h>
struct student        //defining structure
{
  char name[20];
  int age,roll_no;
  char gender;
};

int main()
{
  struct student st;     //creation of new structure variable st which is like student in its structure
  char z;
  printf("Enter the student name=>\t");
  gets(st.name);
  printf("Enter the student roll number=>\t");
  scanf("%d",&st.roll_no);
  printf("Enter the student age=>\t");
  scanf("%d",&st.age);
  printf("Enter the student gender 'm' or 'f'=>\t");
  z=getchar();        //dummy char varible to swallow previous inputs
  st.gender=getchar();
  printf("\nYou entered\n");
  printf("roll_no\tname\tage\tgender\n");
  printf("%d\t%s\t%d\t%c\n",st.roll_no,st.name,st.age,st.gender);
  return 0;
}

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

The approach: 
First of all copy, paste, compile and run the program. This is a simple program just to show how we can access and scan individual components of a structure unlike previous program where all the values were directly assigned to structure component variables. This program is different from previous program in only one way that is scanning the component variables. Once the memory is allocated all component variables can be accessed by adding the structure variable name as prefix separated with a dot(.). Ex. 
st.name has been used to access name variable in the structure st.
After that these can be used normal variables.

program 48: building and accessing structure in C

The need: 
      This is a program to demonstrate the use of structure in C program. This shows how a struct keyword can be used to define a structure form a collection of several variables of different (or may be same) type and how individual members of any struct type variable can be accessed and modified.

The code: 
--------------------------------------------
#include<stdio.h>
#include<string.h>
struct student        //defining structure
{
  char name[20];
  int age,roll_no;
  char gender;
};

int main()
{
  struct student st;     //creation of new structure variable st which is like student in its structure
  strcpy(st.name,"RANU");
  st.roll_no=1;
  st.age=21;
  st.gender='m';
  printf("roll_no\tname\tage\tgender\n");
  printf("%d\t%s\t%d\t%c\n",st.roll_no,st.name,st.age,st.gender);
  return 0;
}

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

The approach: 
First of all copy, paste, compile and run the program. This is a simple program just to show how we can access individual components of a structure so here I have not taken any input form user. All the values are directly assigned to structure component variables. We can scan individual components this will be shown in next post. There are 2 steps in using structures. First is defining the structure. In this step no memory is allocated (Like in our case no memory is allocated to student. This is only an abstraction of the structure.). Once the structure is defined we can use that structure in creating new variables which are like student (in our case st is the a structure variable created with the help of previously defined structure student. In this case memory has been allocated to variable st). Let me recall you, "Unless memory is allocated a variable can not be used to store anything."

Remarks:
1. Structures can be used to define a new data-type. This will be shown in upcoming posts.
2. One other thing like structure is union. union is the data-structure I hardly use unless its specified to use.




24 May, 2011

struct: use of structures in C

All of us know that we have some built-in data types and functions in C. We also know that we can also have user defined functions in C. Now question comes: "Can we have our own data-types ??". Answer is YES you can. Before that you need to have knowledge of something called structures. Just for now think structures as a way to represent complex data-types that are combination of known(built-in) data-types. For example suppose in a program you need a single variable which would be containing name and age of a person. By using only built-in data-types it is not possible. Some of you may say that we can have a character string variable which can  contain name and age separated with a <space> but still it would give headache to access both of them independently and using age as integer. For this we can use a structure variable. This is done by using struct keyword. See the below example.

struct person
{
   char name[20];
   int age;
};
This is an example of defining a structure named person. Now we can use its reference to create more variables of complex data-types which are like person in their look. This is done by following statement:

struct person person1;

Above statement creates a variable person1.
This types of structures we will be using in the upcoming programs. Just wait and watch.

23 May, 2011

program 47: largest of three integers with user defined function

The need: 
      This is program is just to  find out largest of three numbers given by user and print their on the standard output using User defined function.

The code: 
--------------------------------------------
#include<stdio.h>
int largest(int a,int b,int c);       //declaration of function
int main()
{
int i,j,k,l;
    printf("The program to give largest of 3 numbers.\n");
   printf("Enter three integers\n");
   scanf("%d %d %d",&i,&j,&k);
    l=largest(i,j,k);
   printf("The largest integer of the above given is %d\n\n",l);
return 0;
}
int largest(int a,int b,int c)       //definition of function
{
  int temp;
temp=(a>b)?a:b;
  temp=(c>temp)?c:temp;
  return temp;
}
--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. After that try to understand the code and also try to compare with code of program10 of this blog.

Remarks:
There are 2 noticeable points. 
1. The output of both the programs is same.
2. The only difference is in the code (that is in this I have used UDF.)

program 46: addition with user defined function

The need: 
      This is program is just to add two given numbers and print their on the standard output using User defined function.

The code: 
--------------------------------------------
#include<stdio.h>
int getsum(int a,int b);       //declaration of function
int main()
{
    int i,j,k;
    printf("The program to add two numbers.\n");
    printf("Enter first number.\n");
    scanf("%d",&i);
    printf("Enter second number.\n");
    scanf("%d",&j);
    k=getsum(i,j);
    printf("Sum = %d\n",k);
}
int getsum(int a,int b)       //definition of function
{
  int temp;
  temp=a+b;
  return temp;
}
--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. After that try to understand the code and also try to compare with code of program3 of this blog. In this program I have used a user UDF getsum() which takes 2 integers as arguments, adds them and stores in a temporary variable temp and returns the value of temp (that is the sum). This much is clearly visible in the definition of the UDF getsum(). You know that everything should be declared before it is used. In the same way a UDF is declared before it is called. Thats why it has been declared above main().

Remarks:
There are 2 noticeable points. 
1. The output of both the programs is same.
2. The only difference is in the code (that is in this I have used UDF.)

program 45: printing hello world with user defined function

The need: 
      This is program is just to print "Hello World !" on the standard output using User defined function.

The code: 
--------------------------------------------
#include<stdio.h>
void print_hello(void);       //declaration of function
int main()
{
  print_hello();
  return 0;
}
void print_hello(void)       //definition of function
{
  printf("Hello World!\n");
} 
--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. After that try to understand the code and also try to compare with code of program1 of this blog.

Remarks:
There are 2 noticeable points. 
1. The output of both the programs is same.
2. The only difference is in the code (that is in this I have used UDF.)

07 May, 2011

User Defined Functions (UDF) in C

Till now you people have seen many programs in this blog. There are many functions used in those programs like printf(), scanf(), putchar() etc... All these functions perform some job in the program. All these functions are provided to you by C language (we call them built-in C functions). By combination of these functions we make our program to do something useful for us. There may be situations when you have very big program where you need to use a same sequence of code (written by combining built-in functions) many times in that program (Lets say its a 10 line sequence of code and you have to write it 5 different places in the program.) In that situation perhaps you can think, "How nice it would be if there existed a direct function to replace this sequence???"
Your this thinking is correct. Here in C we have something called USER DEFINED FUNCTIONS (UDF). These are the functions those are not built-n in C but are the combination of other built-in or user defined functions. For people who are hearing the term UDF first time I would like to say that
just for now think UDF as a replacement of that sequence of code described above. Though these are more than that. You people will come to know more as you go through next posts and practice more.
    It took me a lot of time to decided whether to put UDF first or structures. Finally I decided to put UDFs first. This will be only the introduction. After that we'll go to structures and pointers and again go into details of UDFs. For those who are hearing these terms first time I would like to say: "Don't worry. Everything will be explained in the easiest way possible."  Now I'll be putting some programs on UDF (some are same programs which I have posted before). You are advised to see and compare codes of both the programs.

program 44: The pot riddle

The need:
     The purpose of writing this program was to solve a mathematical riddle which once somebody asked me when I was in 9th class. At that time it took a long time of mine to solve it. Once when I was practicing C I thought that I could write a program that could solve it for me so I wrote this program.The riddle is:
    There are three types of pots available in the market. The costs are as under:
1. one item of Type1 costs 5 bucks.
2. one item of Type2 costs 1 buck.
3. twenty items of Type3 cost 1 buck.
If someone wants to purchase 100 items for 100 bucks what selection of pots should he make?

The code: 
--------------------------------------------
//The pot riddle
#include<stdio.h>
main()
{
    float i,j,k;
    for(i=1;i<=100;i++)
    for(j=1;j<=100;j++)
    for(k=1;k<=100;k++)
    if((i+j+k==100)&&(5*i+j+.05*k==100))
    {
       printf("number of type1 pots =>\t%.0f\n",i);
       printf("number of type2 pots =>\t%.0f\n",j);
       printf("number of type3 pots =>\t%.0f\n",k);
       //break;
    }
}
-------------------------------------------- 

The approach: 
The approach used here is a layman's approach. This program starts checking for every possible combination of pots whether the given condition is satisfied or not. This is done with the help of 3 nested loops. The 3 variables i,j,k represent the numbers of type1, type2 and type3 pots respectively. Whenever the the condition is met, the corresponding values of i,j,k get printed on the screen.


Remarks:
There are 2 noticeable points. 
1. The break; statement which has been commented here. If it was not commented, the program would find a solution and exit. The purpose of commenting is to check for more than one solution if existed.
2.  "%.0f"  is used for printing float values instead of "%f". For that, let me tell you, when you print a float number by using "%f", the output number has 6 digits after the decimal point. Here I wanted to tell that we can control the number of places after the decimal point in the output.
if I write  "%.nf" then then the output has n digits after decimal.( replace n with any non negative integer like here I have used 0 because I did not want answer in decimal.)

05 May, 2011

program 43: ABCD triangle


The need:
     This program draws a triangle of ABCD on the output screen. This program was written to show that we can increment the characters like numbers.

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    char z;
    int j,i,k;
    printf("Enter the number of rows..(1 to 26)\t");
    scanf("%d",&k);
    if(k<1||k>26)
    {
        printf("\nThe number entered was not in range of 1 to 26\n");
        printf("exiting...\n");
        exit(0);
    }
    printf("\n\n");
    for (i=1;i<=k;i++)
    {
        z = 'A';
        for (j=0;j<i;j++)
        {    
            printf ("%c  ",z);
            z++;
        }
    printf("\n\n");
    }
}
-------------------------------------------- 

The approach: 
This program is very much similar to that star triangle program(program34 of this blog) with only addition of a character variable z which is getting printed each time in place of star(*). z is also incremented each time thus printing different values in each print in row. When a new row starts z is again initialized with character literal 'A' and the loop repeats.

03 May, 2011

program 42: Pascal's triangle

The need:
     This program draws a pascal triangle upto certain numbers of rows. Pascal triangle is an arrangement of binomial coefficients for each row.

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int i,j,k[50],l[50][50],m;
    printf("Enter the number of rows.");
    scanf("%d",&m);
    for(i=1;i<=m;i++)
    {
        for(j=0;j<(m-i);j++)
        printf("   ");
        for(j=0;j<i;j++)
        {
            k[0]=1;
            if(j==i-1)
            k[j]=1;
            l[i][j]=k[j];
            k[j+1]=l[i-1][j]+l[i-1][j+1];
            printf("%5d ",k[j]);
        }
        printf("\n");
    }
}
-------------------------------------------- 

The approach: 
If you have already visited the wiki link given above in this post,you have come to know the logic that each number in the triangle is the sum of the two directly above it. This is the approach used here. To store the rows, a double array of integers has been used and the current row(the row that is being printed) is evaluated and temporarily stored in array k which is also added to double array 'l' each time for next row calculation.


Remarks:

1. We can avoid using two dimensional array in place of that we can use a one dimensional array. Here I used 2 dimensional because at that time I made this program in this way. One advantage of using 2 dimensional array is that now we have the whole pascal stored in that.

program 41: Multiple Diamonds of $

The need:
     This is a simple program to print multiple diamonds of '$'. This program was is an extension of previous program.

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int j,i,k,l,m,n;
    char c;
    do
    {
           printf("Enter the number of dollars in the base..");
        scanf("%d",&k);
        printf("\nEnter the number of diamonds you want ..");
        scanf("%d",&n);
        printf("\n\n");
        for (i=1;i<=k;i++)
        {
            for(m=1;m<=n;m++)
            {
                for(l=0;l<(k-i);l++)
                printf(" ");
                for (j=0;j<i;j++)
                printf ("$ ");
                for(l=0;l<(k-i);l++)
                printf(" ");
            }
            printf("\n");
        }
        for (i=1;i<=k;i++)
         {
            for(m=1;m<=n;m++)
            {
                printf(" ");
                for(l=1;l<i;l++)
                printf(" ");
                for (j=1;j<=k-i;j++)
                printf ("$ ");
                for(l=0;l<i;l++)
                printf(" ");
            }
            printf("\n");
          }
        printf("\nEnter y to try more...press any other key exit...\t");
        c=getchar();
        c=getchar();
        putchar('\n');
    }
    while(c=='y');
}
-------------------------------------------- 

The approach: 
This program creates multiple diamonds on the output screen. First it asks the user to input the number of stars in the base and the number of diamonds and then gives the output and asks the user whether he wants the program to stop or wants to draw one more diamonds. To understand functionality read program40.

01 May, 2011

program 40: Diamond of $

The need:
     This is a simple program to print diamond of '$'. This program was is an extension of previous program - printing an equilateral triangle of star.

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int j,i,k,l;
    char c;
    do
    {
        printf("Enter the number of stars in the base..");
        scanf("%d",&k);
        for (i=1;i<=k;i++)
        {
            for(l=0;l<(k-i);l++)
                printf(" ");
            for (j=0;j<i;j++)
                printf ("$ ");
            printf("\n");
        }
        for (i=1;i<=k;i++)
        {
            for(l=0;l<i;l++)
                printf(" ");
            for (j=1;j<=k-i;j++)
                printf ("$ ");
            printf("\n");
        }
        printf("\nEnter y to try more...press any other key exit...\t");
        c=getchar();
        c=getchar();
    }
    while(c=='y');
} 
-------------------------------------------- 

The approach: 
This program creates a diamond on the output screen. First it asks the user to input the number of stars in the base and gives the output and then asks the user whether he wants the program to stop or wants to draw one more diamond. To understand functionality read program39. You might want to take a look on the next program of this blog which is further extension of this program. Have a look that is cool.

program 39: Equilateral star triangle

The need:
     This is a simple program to print equilateral triangle of symbol '$'. This program was written to learn managing the output on the screen. After doing its job this program asks the user whether to end or try with other value. Moreover this program was prerequisite for the next program of this blog which is also very good program (a recommended program for you to have a look).

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int j,i,k,l;
    char c;
    do
    {
        printf("Enter the number of stars in the base..");
        scanf("%d",&k);
        for (i=1;i<=k;i++)
        {
            for(l=0;l<(k-i);l++)
                printf(" ");
            for (j=0;j<i;j++)
                printf ("$ ");
            printf("\n");
        }
        printf("\nEnter y to try more...press any other key exit...\t");
    c=getchar();
    c=getchar();
    }
    while(c=='y');
}
 -------------------------------------------- 

The approach: 
This program creates an equilateral triangle on the output screen. First it asks the user to input the number of stars in the base and gives the output and then asks the user whether he wants the program to stop or wants to draw one more triangle. This is done using a do while loop which checks the value of character variable c. c is taken as input at the end of program. Notable point here is that I have written getchar() twice in the program still its only taking only one character at the end. WHY??? Read remarks for this.


Remarks:

1. You can try removing one getchar() statement. what happens???

2. Now try printing the value of variable c after each getchar() statement. what did you see???

3. You see the first value of c is '\n'(new line character). Observe the change in line in the output.(How come??? read all remarks.)

4. Second value of c is the value given by you.

5. I have already told you in previous posts that characters can be anything (digit, alphabet, space, tab, new line etc.) Now note that when you entered number of stars in the base, you must have pressed ENTER key after that. The number had been stored in variable k. Where did the ENTER key(new line) go?? Ans. : That remains in the memory and as soon as new character is required by the program this ENTER is assigned as required character. This is why I have used getchar() twice. Read paragraph 3 of approach in program25 of this blog for more details.

6. One could have used built-in function fflush(stdin); for the same purpose.

program 38: Fibonacci series

The need:
     This is a simple program to print Fibonacci series upto certain number of terms. This program was given to me a assingment in lab.
The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int i=0,j=1,k=1,m=1,n;
    printf("Enter the number of terms.");
    scanf("%d",&n);
    printf("\nterm no. \tvalue\n");
    printf("%d\t\t%d\n",m,k);
        for(m=1;m<n;)
        {
            k=i+j;
            printf("%d\t\t%d\n",++m,k);
            i=j;
            j=k;
        }
    printf("\n\n");
}
-------------------------------------------- 

The approach: 
This program creates a Fibonacci series upto the terms given by the user. The logic is simple. Just go with the definition of Fibonacci that any term is the sum of its two preceding terms. Here k always hold current term and i and j hold previous 2 terms(except for first 2 terms case).

Remarks:
1. In this program if you enter a large number of terms, the program fails to give correct output after certain number of terms. This is because of size limit on integers in C.