Thursday, October 31, 2013

%c format specifier limitation.


The limitation of %c format specification is that, it receives the white space characters also. The white space character includes tab, space, enter etc. This limitation of %c format specifier can be rectified by %1s format specifier. The %1s format specifier can be used to receive a non white space character.
Look at the following program:

#include <stdio.h>
#include <conio.h>
void main()
{
          char ch;
clrscr();
printf(“Enter any character:”);
scanf(“%c”,,&ch);
printf(“”\nInputted character is=%c”,ch);
getch();
}

Run the program and press Enter. You will get the following output.
Output:
#----------------------------------------------------------------#
Enter any character:<Enter>
inputted character is=
#----------------------------------------------------------------#

Fixing the limitation of %c format specification by using %1s format specifier.
#include <stdio.h>
#include <conio.h>
void main()
{
          char ch;
clrscr();
printf(“Enter any character:”);
scanf(“%1s”,,&ch);
printf(“”\nInputted character is=%c”,ch);
getch();
}

Now, run the program and press Enter or try pressing any other white space character. The program does nothing until you provide the character from the console.
#----------------------------------------------------------------#
Enter any character:<Enter>
<Enter>
<space><Enter>
y
inputted character is=y

#----------------------------------------------------------------#

Wednesday, October 30, 2013

1 Minute Drill...


♦ You can close individual window of TC editor by using ALT+F3 key combination.

♦ C is a case sensitive language. So, god, God, and GOD all are different.

♦ main() is one of the user defined function.

♦ Every C program contains at least one function which is main().

♦ Program execution always begins with main().

♦ C is free form language i.e. C has no specific rules for the position at which a statement should be written.

♦ By default every user defined function written an integer value to its caller function.

♦ The output directory is one where the compiler keeps all the executable files and object files of your C programs.

♦ Adding comments into a C program does not increase the size of the executable (.EXE) file.

♦ Comments cannot be nested.

♦ You can place comment anywhere in your program.

♦ scanf() function returns the number of input fields which are successfully scanned, converted and stored.

Tuesday, October 29, 2013

Exercises...


Que 1:Fill in the blanks.
    a)   C was developed in the year…………..
    b)   C was developed by ………………………….
    c)   C is …... sensitive language.
    d)   C is …… form language.
    e)   The executable file of Turbo C compiler is……………….
    f)    To close the current window the shortcut key is…………………
    g)   .h stands for ………….. file.
    h)   in printf() f stands for………….. output.

Que 2: State true or false.
    a)   A C program can have more than one main() function.
    b)   List of variables can be dropped from the scanf().
    c)   Output directory is the directory where compiler stores executable and object files corresponding to your programs.
    d)   printf() can be split over multiple lines.
    e)   Special keys like PgUp, PgDn, Home, End etc. have ASCII value 0.

Que 3:Find out the errors in the following programs, correct them and
           rewrite.
     1)
     #include <stdio.h>   
     #include <conio.h>  
     main()
     {
        clrscr();
        int i=20;
        printf(“The value of i=%d”,i);
        getch();       
     }

     2)
     #include <stdio.h>   
     #include <conio.h>  
     main()
     {
        int Int;
        int iNt;                  
        int =786;
        iNt=iNt;
        clrscr();
        printf(“The value of int=%d”,Int);
        printf(“The value of iNt=%d”,iNt);
        getch()         
     }
   
     3)
     #include <stdio.h>   
     #include <conio.h>  
     main()
     {
         int 55_rupee;
        55_rupee=55;
        printf(“The todays rate of dollar is %d rupees.”,55_rupee);
        getch();       

     }

Monday, October 28, 2013

Playing with variables, constants and keywords..


To write better programs, it is necessary to understand the basic building blocks of this beautiful language. This chapters mainly deals with variables, constants and keywords. So, get prepared for this wonderful journey.

What is Variable?
A variable is an entity whose value can be changed during program execution. A variable can hold only one value at a time i.e. when we assign new value to the variable, previous value gets lost.

The syntax for declaring variable is:
data type var1,var2,….varn;

Where,
data type may be any data type from the following:

int, float or char.
var1,var2,…varn are number of variable of identical data type.

E.g.      int age;                                                      
           float salary,da,hra;
           char code,gender;

Here age is an integer variable which can hold integers only (whole numbers (positive or negative, but it does not contain any decimal point). Examples are: 

100,   0,       -707 etc.

salary, da and hra are float variables which holds floating point values (which must contain a decimal point). Examples are:
0.5,    -3.5,  .1       ,1 etc.

code and gender are character variables which can hold only one character at a time. The character must be entered in single quotation marks(‘ ’).
Examples are:
‘&’,     ‘+’,     ‘9’,     ‘R’ etc.

Consider the following program.
Program 1: Write a program (WAP) to receive the temperature in Fahrenheit degrees and convert it into degree centigrade.

#include <stdio.h>
#include <conio.h>
void main()
{
          float far_temp,deg_ce_temp;
          clrscr();
          printf(“Enter temperature in Fahrenheit degrees:”);
          scanf(“%f”,&far_temp);
          deg_ce_temp=5*(far_temp-32)/9;
          printf(“Temperature in degree centigrade is=%f”,deg_ce_temp);
          getch();
}

#----------------------------------------------------------------#
Enter temperature in Fahrenheit degrees:100
Temperature in degree centigrade is=37.777779
#----------------------------------------------------------------#

In the above program far_temp and deg_ce_temp are variables. A variable must be defined before using it in the program.

Note: The section where you declared your variables is known as type declaration section.

In our program, the line
float far_temp,deg_ce_temp;

is a type declaration section. Whatever numbers of variables you are going to use in your program must be declared in this section. this section may covers one or more lines depending on the nature of the program. The following chunk of code typial type declaration section.

E.g. char item[20];
       int partno;
       float cost;

Warning: After main() there must be type declaration section if you are using variables in your program. And then write other statements or functions. Otherwise the compiler flashes the following error message:
          “Declaration section is not allowed here.”

Save the above program as Error1.c and interchange the following two lines of the program.
float far_temp,deg_ce_temp;
        clrscr();
with
        clrscr();
float far_temp,deg_ce_temp;


Now, save the program. And try to compile it. Your compiling window will show 1 error in it. Press Enter and you get the above error message.

Sunday, October 27, 2013

Rules for naming variables


♦ Variable name is formed by using alphabets, digits and underscore characters.

♦ Variable name must begin with alphabet or underscore.

♦ The maximum number of characters used in forming a variable name is 32. Some compilers allow the variable name length to be more than 32 characters, however only first 32 characters are significant. i.e. the following two variable names are same.
E.g. TheSalary_Of_theEmployeePerMonth
       TheSalary_Of_theEmployeePerMonthisEqualto 
Because the compiler considers only first 32 characters.

♦ C is case sensitive language. For instance the variable names such as IQ,Iq,iq, and iQ are treated as different variable names.

♦ Keywords cannot be used as variable names.
E.g. int char; is wrong. As char is keyword.  

Note: It is not a good idea to begin variable name with an underscore character because compiler often starts special variable names and function names with underscore.

The following are some of the valid variable names:
MAXIMUM,   sum,  Salary_of_employee,       _DA,
Name007,    ClassMarks, age_18 etc.

The following are some of the invalid variable names:
Boy’s            : Illegal character “’”.
My salary      : Blank space is not allowed.
gross-salary  : Illegal character “-“.
2Brothers      : First character should be alphabet or underscore.
PriceIn$       :Illegal character “$”.

Note: Variables that are declared but not initialized will contain garbage value or unpredictable value.
                      
Look at the following program.

#include <stdio.h>
#include <conio.h>
void main()
{
          int smallb;
          clrscr();
          printf(“Hi ! I am smallb. Your local friend.”);
          printf(“\nValue assigned to me by Big B (compiler) is=%d”,smallb);
          getch();
}

#----------------------------------------------------------------#
Hi ! I am smallb. Your local friend.
Value assigned to me by Big B (compiler) is=-28715

#----------------------------------------------------------------#

Saturday, October 26, 2013

Variable initialization


By default every variable contains an unpredictable value called garbage value. Assigning initial value to the variable is known as variable initialization. A variable can also be initialized during its definition.
E.g.    1) int a,b;
              a=b=100;
Assign value 100 to both the variables a and b.
          2) float area;
              int z;      
              area=3.14159*4*4;
Assign 50.2654 to variable area.       
             z=area+100;
Assign 150 to z. Here z is an integer variable so it truncates the decimal part of the result.
          3) int i=0,j=1;
Assign 0 to variable I and 1 to variable j.

Another way to declare variables
You can adopt this totally new way to declare variables you use in your programs. How? The following program demonstrates this.

#include <stdio.h>
#include <conio.h>

main(i,j,k)
{
   clrscr();
   i=2,j=5;
   k=i+j;
   printf(“The sum of %d+%d=%d”,i,j,k);    
   getch();
}

Output:
#-------------------------------------------------------------------------------#
The sum of 2+5=7
#-------------------------------------------------------------------------------#
Note that if you do not specify the data type of the variable declaring inside the parenthesis of main(), then the compiler by default treat them  as an integer variables. But, if you want to specify other type of variables, say float or char, then it is necessary to explicitly specify the data type.
Program 5:

/* Using float  variables. */
#include <stdio.h>
#include <conio.h>

main(float i,float j,float k)
{
   clrscr();
   i=2.5,j=5.9;
   k=i+j;
   printf(“The sum of %f+%f=%f”,i,j,k);      
   getch();
}

Output:
#-------------------------------------------------------------------------------#
The sum of 2.500000+5.900000=8.300000
#-------------------------------------------------------------------------------#
/* Using char variables. */
#include <stdio.h>
#include <conio.h>

main(char ch1,char ch2,unsigned char ch3)
{
   clrscr();
   ch1=’A’;
   ch2=’B’;
   ch3=ch1+ch2;
   printf(“The sum of %d+%d=%d”,ch1,ch2,ch3);
   getch();
}

Output:
#-------------------------------------------------------------------------------#
The sum of 65+66=131
#-------------------------------------------------------------------------------#
Remember that the ASCII value of A is 65 and the ASCII value of B is 66. So, in the above program we are performing operation on the ASCII values of the variables rather than two characters.

Arithmetic opearators
Arithmetic operators are used to build simple as well as complex expressions. C uses following arithmetic operators.
+       :Addition
-        :Subtraction
*        :Multiplication
/        :Division
%      :Modulus
We will explore these operators time by time later on.

 The assignment statement:
The main statement in C for carrying out computation and assigning values to the variables is the assignment statement. the general form of assignment statement is:
                             result=expression;
the expression is evaluated and then the value of the expression is assigned to the result. It is important to note that, the value assigned to the result must be the same as that of result. where result is any valid variable name. expression must be any valid C expression. The expression can be single variable, a single constant or involves variables and constants combined by the arithmetic operators.
For example, the following assignment statement:
          average=(a+b)/2;
assigns half the sum of a and b to the variable average. have a look at the another example:
          i=3;
Assign 3 to the variable i.
Perimeter=2.0*(length*breadth);
Assign the value of rightmost expression to the variable on the left hand side i.e. perimeter.
          i=j=k=l=500;

assign value 500 to all variables i.e. i, j, k, and l.

Friday, October 25, 2013

Unary operators


Binary operators are the operators which works on two operands at a time.
E.g. z=x+y;
Here, + is binary operator.
X and y are operands.
So, “+” operator works on two operands (Here x and y) at a time. Unlike binary operators, unary operator works on only one operand at a time.
Note that, unary operators have higher precedence than arithmetic operators. Another main difference between unary and binary operator is the associativity. The associativity of unary operator is from right to left, whereas the associativity of binary operator is from left to right. We will see the concept of associativity later on. In C you can use the following unary operators.
1) Unary minus (-): Unary minus change the sign of operand it preceding.
E.g. -786,    -temp,         5E-5  etc.
2)Unary not or Logical not or Negation: It is used to negates the condition. The following examples should better clarify this concept.
E.g. if(!TRUE) is same as
       if(FALSE)
Similarly,
       if(!FALSE) is same as
       if(TRUE)
Where TRUE is a symbolic constant having nonzero value (E.g. 100,-100, 1 etc.), and FALSE is a symbolic constant having value 0. Remember that, any nonzero value is treated as true value in C and 0 is treated as falsity.
Consider an example,
          !(ZZ>=5) is same as      
            ZZ<5
3)Increment and decrement operator (++ and --): Increment operator increment the value of the variable by 1, and the decrement operator decrease the value of the variable by 1.
E.g. i=5;
       i++;
Increments the value of I by 1. So, after evaluation of the statement i++, I contains a value of 6. instead of i++, you can write ++I also. But there is slight difference between the two. We will see it later on.
Similarly, we can decrement the value of the variable by 1 using:
E.g. i=5;
       i--;
Decrement the value of I by 1. So, after evaluation of this statement i contain a value of 4. Here also you can write --i instead of i--.
4)Address of operator (&): The address of operator is used to find the address of the variable it precedes.
E.g. printf(“The address of the variable x=%u”,&x);
Note: You can use %p or %u format specifier for printing the addresses of the variables.
Consider the following example,
Program 6:
#include <stdio.h>
#include <conio.h>
void main()
{
     int x;
     clrscr();
     printf(“\nThe address of the variable x is=%u”,&x);     
     printf(“\nThe address of the variable x is=%p”,&x);
     getch();
}
Run the program, you will get the following output (in your case it may be different, because the compiler maqy select any available address as well.)
Output:
#-------------------------------------------------------------------------------#
The address of the variable x is=65524
The address of the variable x is=FFF4
#-------------------------------------------------------------------------------#        

What? Two different outputs for same variable? Absolutely nooooo. Every variable can have only one unique address assigned by the compiler at run time. Then what is the mystery behind this output? Actually, the address we have printed using %p format specifier is hexadecimal equivalent of its address 65524.So, both 65524 and FFF4 represents same location in the memory. Now, it is totally up to you to decide whether you want to print your variable addresses using decimal notation or hexadecimal notation. Try using %x or %X format specifier to print the address of the variable x. You will get the same output as produced by %p but %X will print the output in upper case letter whereas %x will print the output in lowercase letters.
4) sizeof(): sizeof() operator returns the size of its operands in bytes.
E.g. sizeof(x) ;
Gives the number of bytes allocated to the data type of x. Consider the following example.
Program 6:
#include <stdio.h>
#include <conio.h>
void main()
{
     char a;
     int b;
     float c;   
     clrscr();
     printf(“\nThe number of bytes reserved for character is=%d”,sizeof(a));
     printf(“\nThe number of bytes reserved for integer is=%d”,sizeof(b));
     printf(“\nThe number of bytes reserved for float is=%d”,sizeof(c));
     getch();
}

Run the program and you will get following output.

#-------------------------------------------------------------------------------#
The number of bytes reserved for character is=1
The number of bytes reserved for integer is=2
The number of bytes reserved for float is=4
#-------------------------------------------------------------------------------#        

In above program we use %d to print the size of the variables as the sizeof() returns the size of operands in an integer format.
Now, try to run the following code.
Program 6:
#include <stdio.h>
#include <conio.h>
void main()
{
     clrscr();
     printf(“\nThe number of bytes reserved for float is=%d”,sizeof(3.14));
     getch();
}
Run it, and observe the unexpected output.
#-------------------------------------------------------------------------------#
The number of bytes reserved for float is=8
#-------------------------------------------------------------------------------#        

In the previous program the size reported by the compiler for float is 4 bytes and now it report 8 bytes! How?

Note: A floating point number is specified by the float keyword in the C language. Floating point numbers can be suffixed with the letter f or F to specify float explicitly. A floating point number without suffix is double by default.

Therefore the correct version of the above program is:

#include <stdio.h>
#include <conio.h>
void main()
{
     clrscr();
     printf(“\nThe number of bytes reserved for float is=%d”,sizeof(3.14F));
     getch();
}
Run it, and you will get the expected output.
#-------------------------------------------------------------------------------#
The number of bytes reserved for float is=4
#-------------------------------------------------------------------------------#        

Note: if sizeof() is being applied to the type then parenthesis () are required, otherwise they are optional.
So, the following code is valid one.
Program 9:
#include <stdio.h>
#include <conio.h>
void main()
{
     clrscr();
     printf(“\n%d”,sizeof 3);
     getch();
}
But, this is invalid.

#include <stdio.h>
#include <conio.h>
void main()
{
     clrscr();
     printf(“\n%d”,sizeof int);
     getch();
}

Now, consider the another example using sizeof which will produce the unexpected output.

#include <stdio.h>
#include <conio.h>
void main()
{
     clrscr();
     printf(“\n%d”,sizeof (‘a’));
     getch();
}

Run the program now.
Output:
#-------------------------------------------------------------------------------#
  2
#-------------------------------------------------------------------------------#        
Remember that the character constants in C are of type int, so sizeof(‘a’) is equal to sizeof(int).
6) Cast unary operator: This operator is used to change the type of the variable, constant or expression explicitly.
E.g. (int)3.14159;

Change the value of operand to 3.