Tuesday, November 5, 2013

Oening an existing program


Opening your existing program is fairly easy task. To open an existing program do one of the following:

Click on the File menu and then choose Open option Or press ALT+F to evoke file menu and the press O to invoke the file open dialog box.
OR
Press F3 function key.


“Open a file” dialog box appears. Press TAB to move to files listed. Select your file using arrow keys and press Enter. Your file is on the screen.

Monday, November 4, 2013

Comment philosophy...


We had seen earlier that, comments are the statements ignored by the C compiler. Now, we are going to learn more about comments. The following program illustrates the usefulness of comments.

Program 7:
/* The message program */
/* Created by :Mysterio Date: 20 November 2013 */
#include <stdio.h>
#include <conio.h>
void main()
{
          /* Clear the screen.*/
clrscr();
/* Display the message on the screen. */
printf(“\n Fear less, Hope more;\
           \n Whine less, Breathe more;\
           \n Talk less, Say more;\
           \n Hate less, Love more;
           \n And all good things are yours.”);
/*Pause the program output.*/
getch(); /*End of the program. */
}

We know that, all the statements enclosed in between /* and */ are comments. Comments are useful to make our program more readable and easy to understand. Remember that comments are for programmer and not for compiler. Adding comments into the program does not increase the size of executable file. In the above program, we split the printf() over the multiple lines by appending “\” at the end of each line. It tells the compiler that what is on the next line is the continuation of the previous line. The printf() function  can be used to print the strings in various ways. Our forthcoming topic “Printing strings in various way…” will explain this concept.

Warning: You cannot nest comments i.e. one comments inside another.

So, the following comment is invalid.
/*Program to find IQ /*Created by Genius */ Date :21 Nov 2013. */

Tip: We are using Turbo C++ compiler to write our C programs. So, we can also write single line comment as follows. But it is not valid in pure Turbo C compiler.

//Hey! I am C++ style comment.

Note: You can place comments anywhere in your program.
The following program illustrates this.

Program 8:         
#include <stdio.h>
#include <conio.h>
void main(/* Program execution begins here. */)
{
     clrscr(/* use me to clear the screen. */);
     printf(“\n I %c C! And you?”,3);
    getch(/* use me to pause program display.*/);
}

Warning: Don’t write comment in angle bracket after #include statement.
E.g.
#include <stdio.h /*Standard I/O header file. */> because, if you do so, the compiler assumes it as a file name and the error will occur.

You may be curious about the second pritf() statement. The %c format specifier is used to print the character corresponding to ASCII value on the right side. The ASCII value of “©” character is 3, so it will print the “©” character and so the output of second printf() will be:

I © C! And you?

Sunday, November 3, 2013

Printing string in various ways using printf()


You can use printf() function to print the string in your program as follows:
Program 9:

#include <stdio.h>
#include <conio.h>
void main(/* Program execution begins here. */)
{
     clrscr();
     printf(“\nNever give up on anybody.”);
     printf(“\n%s”,”Never give up on anybody.”);
     printf(“\nNever” “ give” “  up” ”  on” “  anybody.”);
     printf(“\nNever\
    give\
    up\
    on \
    anybody.”);
    getch();

}

Output:

The extra spaces on the last printf() can be adjusted by using the escape sequences “\b”. So, the improved version of the printf() would be:

printf(“\nNever\
    \b\b give\
    \b\b up\
    \b\b on \
    \b\b anybody.”);

Saturday, November 2, 2013

getch() philosophy ...


Up till now we have used getch() several times to pause program output. But, by using getch() we can perform other important tasks also. getch() gets a character from the keyboard but it does not echo (display) that character on the screen.
Type the following code:
Program 10:
#include <stdio.h>
#include <conio.h>
void main()
{
     int gender; /* An integer variable. */
    clrscr();
    printf(“\nEnter Gender (1-Male, 2-Female):”);
    gender=getch();
    printf(“\nYour entered gender is =%d:”,gender);
    getch();
}

Output:
#----------------------------------------------------------------#
Enter Gender (1-Male, 2-Female):
Your entered gender is=49 (if you entered 1)

Enter Gender (1-Male, 2-Female):
Your entered gender is=50 (if you entered 2)
#----------------------------------------------------------------#

Strange output..!! From where this 49 and 50 comes? Definitely This question is  arises in your mind. Correct! Read the following paragraph carefully.

When you press a key from the keyboard, the keyboard circuit transmits a sequence of one or more 8-bit numbers to the computer. This sequence of 8-bits is called “scan code” and it uniquely identifies the key you pressed. Each key available on the keyboard has a unique scan code. The ROMBIOS routines translate scan code into two byte sequence. The first byte contains the ASCII code of the key you hit, and the second byte contains the scan code of the key you hit. If the key you hit is a special key, such as function key or arrow key, then first byte contains a value 0 (zero), whereas the second byte contains the scan code of the key.

Now, look at the following example.

#include <stdio.h>
#include <conio.h>
void main()
{
     int key;
    clrscr();
    printf(“\nPress any key…”);
    key=getch();
    printf(“\nASCII code of the key you pressed is=%d”,key);
    getch();
}

Run the program and press z. And observe the output.
#----------------------------------------------------------------#
Press any key…
ASCII code of the key you pressed is=122
#----------------------------------------------------------------#

Run the program several times by pressing function keys, arrow keys or numeric keypad keys and every time you will get this same output.

Press any key…
ASCII code of the key you pressed is=0

Now, we are going to write a program which handles both i.e. ASCII values as well as scan code.

#include <stdio.h>
#include <conio.h>
void main()
{
     int ascii,scan;
     clrscr();
     printf(“\nPress any key…”);
     ascii=getch(); /* Receive the first byte. */
     if(ascii==0) /* If special key is hit the first byte contains 0. */
    {
       scan=getch();
       printf(“\nScan code of the key you pressed is=%d”,scan);
    }
    printf(“\nASCII code of the key you pressed is=%d”,ascii);
    getch();
}

Run the program by pressing arrow keys and function keys. Program shows both ASCII and scan code of the keys. If you press F1 then program will display the following output.
Output:
#----------------------------------------------------------------#
Press any key…
Scan code of the key you pressed is=59
ASCII code of the key you pressed is=0

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

Friday, November 1, 2013

Checking successfully scanned input items.


When you entered data using keyboard then always remember that the data items must corresponds to the arguments in scanf() function in number, type and in order. Violation of this rule may cause unexpected results.
You can use the scanf() function to return the number of input fields successfully scanned, converted and stored.
Look at the following program to make this fact clearer.
Program 13:

#include <stdio.h>
#include <conio.h>
void main()
{
          int age,nof;/* Number of fields. */
char gender;
clrscr();
printf(“Enter gender and age:”);
nof=scanf(“%c%d”,&gender,&age);
if(nof==2)
{
          printf(“\nCorrect input!”);
printf(“\nGender=%c\nAge=%d”,gender,age);
printf(“\nNumber of input field scanned=%d”,nof);
}
else
{
printf(“\nWrong input!”);
         printf(“\nGender=%c\nAge=%d”,gender,age);
printf(“\nNumber of input field scanned=%d”,nof);
}
getch();
}
Run the program. Input the value of sex=12 and age=25. Observe the output.
Output:
#----------------------------------------------------------------#
Enter gender and age:12 25
Correct input!
Gender=1
Age=2
Number of input field scanned=2
#----------------------------------------------------------------#
Oops! You might be surprised that our input data is valid. How? When you enter 12 for gender then compiler assigns 1 to the variable gender (remember that in character variable we can store only one character either it is alphabet, number or special character). The unread data from the inputted number 12 i.e. 2 in this case is assigned to the variable age. So the next data input that is 25 remains unread. If our program contains another scanf(), then this unread data is used by the compile for the next scan data. So, be cautious about such errors.
Now, run the program with the following
Enter gender and age:m m
Wrong input!
Gender=m
Age=-28727
Number of input field scanned=1


This time the compiler reports invalidity of input. Observe that, the value of variable is a garbage value and it may be different when you run this program.

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

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