Thursday, November 14, 2013

Learn By Doing !

B 4 U Begin…

Five cats are sitting on a wall. Three of them decided to jump down, now how many cats are sitting on the fence? You may answer two. But the answer is incorrect. Because as it is stated in a question, three cats are only decided to jump down. They did not jump.




Moral: Mere decision making is not enough. The action must follow. Here is a book in the form of blog that will put your decision into the action. Have a smooth journey and excel in C language.


Best of luck…
Happy Learning !


Wednesday, November 13, 2013

C introduction at a glance...

     
      A bunch of pages explaining history, superfluous long hall of text explaining various aspect of language.  These are the few features of the good books available in the market. “Learn by doing”, is the main approach of this book. So, I don’t want to waste my time on explaining the thing like history and evaluation of the language etc. However, as a background, I will provide some information on these aspects.

C introduction at a glance...

      ► C is a general purpose programming language.
            
      ► C was first developed in 1972.
            
      ► C was developed at AT&T’s Bell labs.
            
      ► C was developed by Dennis Ritchie.
            
      ► C was derived from the language “B” which was also developed at Bell Laboratories.
           
      ► C is free form language.
             
      ► C is case sensitive language.

Tuesday, November 12, 2013

Starting turbo C/C++


Opening Turbo C/C++ Editor: If your computer has Windows, you can adopt the following methods to open your Turbo C IDE (Integrated Development Environment.  An IDE normally consists of a source code editor, build automation tools and a debugger.). Actual it is not Turbo C IDE; it is Turbo C++ IDE Version 3.0. But using this editor we can create C++ as well as C programs. If you want to create C programs then simply save your file with extension .C  (E.g. Myfile.c) and for C++ programs save your file with extension .cpp (E.g. Myfile.cpp).

Using windows XP

Step 1: Click on the start button.

Step 2: Click on All programs and then click on Accessories menu and then select Command Prompt. Your screen will look like as follows (yours may be different).

C:\Documents and Settings\Krish>

Where Krish is the user name of my computer. You will see another user name defined by you in your system. At the command prompt type CD\ and press Enter Key. And follow the procedure below:

Common procedure :
If TC is the directory where your TC compiler is placed, then type the following commands at the C prompt.

C:\>CD TC <Enter>
C:\TC>TC <Enter>

If your TC compiler is located at another directory, then specify that directory name.
E.g. C:\>CD  <DirName> <Enter>
C:\DirName>TC <Enter>

If your TC compiler is located at another drive and directory, then after C:\> appears do the following:
C:\>DRIVELETTER : <Enter>
E.g. C:\>D: <Enter>
D:\> CD  <DirName> <Enter>
D:\DirName>TC <Enter>


Your Screen will look like as follows:


Note: We write TC at the command prompt because when we write TC at the command prompt, it means we are going to run one of the following files:

TC.COM
TC.EXE
TC.BAT

So, we can only execute these three executable files using command prompt. Files having the extension .COM, .EXE and .BAT. You can specify the full filename like TC.EXE at the command prompt, but there is no need to write this. As in Turbo C directory there is only one executable file having primary name TC (i.e. TC.EXE). 

So when we need to write full file name at the command prompt?
Consider that these all three files (i.e. TC.COM, TC.EXE and TC.BAT ) are available in the same directory, then it is mandatory to specify the full name of the file (e.g. TC.EXE) at the command prompt to start Turbo C. What will happen when we simply write TC and the command prompt ? 

In such case the OS will execute TC.COM file. As their order of execution is as follows:

.COM                    First priority
.EXE                     Second priority and
.BAT                     Third priority

Remember that our Turbo C compiler executable file is TC.EXE.

Using DOSBox to run TC on Windows 7 and Windows 8

Dear friends,


        Most of the users face difficulty while running Turbo C in Windows 7. As you know, Turbo C is not compatible with Windows 7 and Windows 8. To run Turbo C on Windows 7 and Windows 8 you need a special emulator software DOSBox.  You can download DOSBox from various web sites. But, before proceeding just check it out whether you are using 32-bit Operating System or 64-bit Operating System. As there are different versions of the DOSBox are available for 32 bit OS and 64 bit OS. To do so, Click on Start ->Control Panel and click on System.

DOSBox is mainly used to run dos games and old applications. Download DOSBox 0.74 and install it. DOSBox shortcut appears on your desktop. Right click on it and from the popup menu select Properties.


Properties window appears.

Click on Open File location button. 

Above window appears on the screen. From the window open DOSBox 0.74 Options batch file. The contents of the batch file will appears on the screen.


Note that the default setting of fullscreen and fulldouble option is false. Change both settings to True. Now go to the [autoexec] section of the file and add the five lines as shown below.
Save the file. Enjoy ! Now double click on the DOSBox icon on your desktop and your Turbo C is start automatically.

Now do two more settings. Why ? Don't ask! Just do it. Start DOSBox and quit from the Turbo C. Now our screen looks like as follows (yours may be different.).



Press CTRL+F1. Mapper screen appears. 



Click on ShutDown option from the table and the click on Del option. Now click on Mapper option (just below the ShutDown option) and then click on Del option. Now click on Exit to exit from the mapper. This mapper setting is mandatory as the shortcut key to run program in TC is CTRL+F9 and to exit mapper the same key is used. So, when we press CTRL+F9 in TC to run your program you will automatically exit from the DOSBox. 

Now, why we delete Mapper option. Note that the shortcut key to open mapper is CTRL+F1 and the same key CTRL+F1 in Turbo C is used to take topic help. Understand ?



Monday, November 11, 2013

Creating your first C program...

Closing unwanted windows: After opening Turbo C editor, if you observe that there are several unwanted programs opened on your screen, then first of all, close them using following techniques.
Press ALT+W to invoke the Windows menu and then choose Close all option or press hotkey e (The red color letter “e” in the close all menu option.) This procedure will close all open windows on the screen.
OR
You can close individual window by using Alt+F3 shortcut key combination.

Creating new program file:
If you are using mouse (generally, in windows environment) the click on the File menu and click on New option.

If you are keyboard lover then press ALT+F to popup the file menu and then choose New. A new program window will appear on the screen. Type the following code.

Program #1
#include <stdio.h>
main()
{
                printf(“One who makes no mistakes never makes anything.” );
}

Warning: C is a case sensitive language, therefore it is necessary to write programs in lowercase letters. Whereas strings, symbolic constants, variables can be written in both uppercase and lowercase letters or the combination of both.
So type the code exactly as written above. Note that the only text i.e. string “One who makes…” written in double quotation marks can be typed as you like.

Saving the program file: 
To save the program file, you can use one of the following methods:

Method 1: Press ALT+F to popup the file menu and then choose Save option. Specify the filename, say “Prog1.c” after removing the default file name and press Enter.

Method 2: Press F2 function key to open save dialog box. Remove the default filename using backspace key and then write a new name (E.g. Prog1.c).
Note that the filename should not be exceeding than 8 characters and all DOS filename rules are applicable.

Compiling the program
Before running a program directly, it is good idea to compile it first. To compile the program use ALT+F9 function key or press ALT+C to popup Compile menu. Choose Compile option. Checkout the errors if any. If there are errors in your program, don’t worry! Make sure that you have typed the exact code as shown above. Also make sure that you have written the whole program in lowercase letters (excluding text in “” marks.). After removing all errors, save the program again by pressing F2. Your program is error free now! Get ready to run your program!

Executing the program
Using CTRL+F9 you can execute your program. Or use ALT+R to evoke Run Menu. From the Run menu, select Run option. No output? And you are back in editor window?
What’s going wrong? Relax!! nothing’s gone wrong. Then what happens?
Actually your program displays the output and suddenly come back to TC editor. This happens in a flash, so you are not able to see the output. Press ALT+F5 to display output screen. Congratulations!! you have created your first C program and successfully execute it.

Understanding the program
Now, watch carefully at our source code line by line.
Line 1:   #include <stdio.h>
Line 2:   main()
Line 3:   {
Line 4:        printf(“One who makes no mistakes never makes anything.” );
Line 5:   }

Output:
#------------------------------------------------------------------------------#
One who makes no mistakes never makes anything.
#------------------------------------------------------------------------------#
Line 1: #include option is used to include the file in our C program. In the above program we can include “stdio.h”, which is header file inbuilt with Turbo C compiler and contains the definitions of several standard library functions including printf(). Note that “f” in printf() stands for formatted output. So, it is necessary to include each and every file containing function definition of respective function in the program.

Line 2-3: Indicates beginning of every C program. main() is a special function. Remember that, execution of your program always starts with main() function.

Line 4: It uses standard library function printf(). To display the message on the screen. You can write this message in uppercase, lowercase or combination of both. You can also include numbers and special characters in the message.

Line 4: Indicates the end of C program.

So, it is obvious that, C program is a collection of several functions. In our program, we use printf() function to print the message on the screen. main() is also one of the user defined function. Now, look at the following program:

Program #2
main()
{
}

What? Neither #include statement, nor any functions, even there is no any statement in main() ! Surprising…! But it is absolutely valid. You can also write the above same code in a single line. Like this.
main(){}
Remember that C is free form language i.e. C has no specific rules for the position at which a statement is to be written. Save the program, compile and run it. Obviously it will not produce any output, nor it will give any errors.

So, now you can put your name in “Limca Book of World Records” ! How? Because you have just written the World’s smallest C program.

Sunday, November 10, 2013

Improving the program. Taking topic help.

Improving the program

Now, we are going to add two new functions and few more to the program number 1.

Program 3:
Line 1:   /* The message program.
Line 2:     Written by: Me  Date:20 Nov 2013 */
Line 3:   #include <stdio.h>
Line 4:   #include <conio.h>
Line 5:   main()
Line 6:   {
Line 7:       clrscr();
Line 8:       printf(“One who makes no mistakes never makes anything.” );
Line 9:      getch();
Line 10: }

The first two lines in our program are comments. It starts with a combination of /*, and ends with */. In C “/*” is called opening comment mark and “*/” is called closing comment mark.

In line 7, we use clrscr() function. It is standard library function and used to clear the output screen.

In line 9, we use another standard library function getch(). It is used to pause the program output until user hit any key from the keyboard. The definition of these functions defined in the file “conio.h”. So, it becomes necessary to include it at the beginning of the program.

Line 10 indicates the end of the program.

How do we come to know that which function belongs to which header file (.h file)? It’s pretty simple. Just follow the procedure given below:


To know the prototype of the function, move the cursor of the first letter of the function (e.g. to know the prototype of the function getch() move the cursor to the first letter (i.e. “g”) and press Ctrl+F1. A help window appears. 


Note the name of header file and include it at the top of your program.



Saturday, November 9, 2013

Be cautious about getch()

        Always press Enter key to come back to your editor window after viewing the program output. Why?
Because,
If you press Up Arrow key to come out from output window to editor window, and if you run the program which takes an input from the keyboard, then the H character appears next to the input prompt.
If you press Right Arrow key to come out from output window to editor window, and if you run the program which takes an input from the keyboard, then the M character appears next to the input prompt.
If you press Down Arrow key to come out from output window to editor window, and if you run the program which takes an input from the keyboard, then the P character appears next to the input prompt.
If you press Left Arrow key to come out from output window to editor window, and if you run the program which takes an input from the keyboard, then the K character appears next to the input prompt.
And the different characters will go on appearing, if you press any special key from the keyboard to come out to editor window.
The following program will show you what I want to say.
#include <stdio.h>
#include <conio.h>
main()
{
     int number;
     clrscr();
     printf(“Enter a number:”);
    scanf(“%d”,&number);
   getch();
}

The above program takes an integer number from the user and then does nothing.
Run the program. Input any number at input prompt like this:
Output:
#-----------------------------------------------------------------------------------------#
Enter any number: 12 <Enter>

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

Now instead pressing Enter again press Up Arrow key. Now run the program again. Your input prompt is now as shown below:

#-----------------------------------------------------------------------------------------#
Enter any number: H
#-----------------------------------------------------------------------------------------#

I think, you got my point now.
In the above program we used scanf() function and type declaration section. We will see detailed about scanf() in the next section.

For a time being, remember that, if you press a special key from the keyboard while using getch(), it will return 0 and program will continue. But, this 0 will be stored in a buffer and will be returned from the next call to getch(). Thus the getch() will not work. The following program clarifies this concept.

#include <stdio.h>
#include <conio.h>
main()
{
      float radius,area;
      clrscr();
      printf(“Money is not everything.”);
      getch(); /* Press any special key here say F1 at the output prompt and notice that the second getch()        
                          will not work.*/  
      printf(“\nThere is Master Card and Visa.”);
      getch();
}
Run the above program and press any special key, say F1. When the message “Money is not everything.” is displayed and you will observe that the second getch() will not work (i.e. our program output does not pause after the message “There is Master card and Visa.”). We can rectify this limitation using the program below.

#include <stdio.h>
#include <conio.h>
main()
{
      float radius,area;
      clrscr();
      printf(“Money is not everything.”);
      if(getch()==0)
          getch();
      printf(“\nThere is Master Card and Visa.”);
      if(getch()==0)
          getch();
}

Now, if the user presses any special key, then the if statement becomes true and the value returned by getch() (i.e. 0) is passes to the extra getch() and so the program works normally. If the input key is not a special key, then the if statement becomes false and the program behaves like simple program. Note that the statement if(getch()==0) pauses the program and also check whether the value returned by the getch() is 0 (zero) or not.

Friday, November 8, 2013

Using printf() and scanf() functions

printf() function
printf() function is used to display formatted output on the screen. The general form of printf() function is as follows:

printf(<Control string>,var1,var2,…varn) ;
Where, control string may contain the format specifiers, strings or combination of both. For now, the format specifiers may be
%d    : for integers.
%f     : for floats.
%c     : for characters.
%s     : for strings.

var1,var2,…varn are variables of type ints, floats, chars or strings (we will study the primary data types and their usages in the chapter “Data types” later on ).
String is a group of characters included in “” (double quotation marks). The characters may uppercase and lowercase letters, numbers and special characters. Examples of strings are:

“Hello everybody…”
“1 gallon=4.53 liters.” etc.

Points to be noted about printf()
In control string there can be only string without any format specifiers.
E.g. printf(“Enter your height:”);

List of variables (i.e. var1,var2,..varn) can be dropped from printf().
E.g. printf(“Bhayyaji smile !!”);

No special symbol before variable name is required unlike “&” symbol in scanf() function.

scanf() function
scanf() function is used to receive the values from the keyboard. By using scanf(), we can create an interactive programs. The general form of scanf() function is as follows:
          scanf(<control string>,&var1,&var2,…&varn);
Where, format string may be either:

%d    : for integers.
%f     : for floats.
%c     : for characters.
%s     : for strings.

and var1,var2,…varn are variables of type ints, floats, chars or strings.

Points to be noted about scanf()
In scanf() we cannot include string into format string.
So,
scanf(“Enter age %d”,&age);
is illegal. The correct form would be
scanf(“%d”,&age);

List of variables (i.e. var1,var2,…varn) cannot be dropped from scanf().
E.g. scanf(“%d%f%c”); is invalid statement.
The correct form would be:
scanf(“%d%f%c”,&age,&salary,&code);

“&” symbol is required before variable name. Note that for character array or string, it is not necessary. So, it is up to you to add it or not.

E.g. scanf(“%f”,&radius); Note the “&” symbol before variable name.

scanf(“%s”,empname);

Here empname is string so no “&” symbol is required before variable name.

Thursday, November 7, 2013

Removing warning from the program

Now, type the following code:

#include <stdio.h>
#include <conio.h>
main()
{
     clrscr(); 
     printf(“\nBe careful about reading health books,”);
     printf(“\nyou might die of a misprint.”);
     getch();
}
Save the program. Compile it and observe the compiling dialog box, it display 1 warning. Press Enter and observe the message window located at the bottom of the window. This window appears time by time when you make mistake your program or after compiling, you may press Enter to see the warning message)

Warning PROG6.C 9: Function should return a value.

What does this warning indicates? And how we can get rid of this warning? Cool…

Removing warning from the program
In C by default every user defined function returns an integer value to its caller function. Remember main() is also one of the user defined function and so it also return some value to its caller (i.e. Operating System). And this is the main reason for this warning.
     1)   Adding void keyword before main().
     2)   Adding return statement at the end of program.

Now we are going to write modified version of the above program.

/* Removing warniong from the program. Method #1 */
#include <stdio.h>
#include <conio.h>
void main()
{
     clrscr(); 
     printf(“\nBe careful about reading health books,”);
     printf(“\nyou might die of a misprint.”);
     getch();
}

The keyword void before main() indicates that the function main() is not going to return any value to its caller (i.e. OS).

/* Removing warniong from the program. Method #2 */
#include <stdio.h>
#include <conio.h>
main()
{
     clrscr(); 
     printf(“\nBe careful about reading health books,”);
     printf(“\nyou might die of a misprint.”);
     getch();
    return(0);

}

The keyword return is used to terminate the function and return a value to its caller. The return statement may OR may not include an expression.

The general form of return statement is:
return(expression);
Some valid return statement examples are:
return;
return(0);
return 0;

Note: A nonzero value returned by the return statement tells the OS that an error has occurred.

Wednesday, November 6, 2013

Distribute your Program...

Creating executable (.Exe) file for your source code

If you want to distribute your program to dear and near ones then instead of providing source code (the actual C program) first create the executable file for your source code. To create  .Exe file for your source code follow the steps given below:

Step 1: Save the program file by pressing F2 key.

Step 2: Click on the Compile menu by using mouse and the select Make option from the popup menu or press ALT+C to invoke compile menu and the press M hot key. After linking compiler create .EXE file for your source code to your specified output directory.
OR
Press F9 function key.
Tip: If you do not know your output directory, then do not worry. To see your output directory, click on Options menu, and from the option menu click on Directories…. From the Directories dialog box, note your output directory.
If you want to specify other directory as output directory say MyOutput then add C:\TC\MyOutput in the output directory line (Remember that MyOutput directory must exist within TC directory) and click on OK. To save your settings, click on Options menu again and choose Save. From the save options dialog box, make sure that an Environment must be checked and then click on OK.
Quit TC by pressing ALT+X. Your screen may look like this:
C:\TC>
Type the command
C:\TC>CD MyOutput <ENTER>
C:\TC\MyOutput>
Now, type the name of your executable file i.e. your program name and press Enter.
C:\TC\MyOutput>Prog6 <ENTER>
Watch your program output. Now, at the command prompt type DIR/P and press Enter.
The files as well as directories will be displayed on the screen. Notice the .Obj file (Prog6.obj) will also present there.
From where the .obj file comes?

When you compile a program by using compiler, it creates .obj file. This file contains machine language code corresponding to your source code. But you cannot execute .obj files directly. Note that the linker links the .obj file, the standard library files and then produce .EXE file.