Learn how to write the Turbo C program step-by-step | Lesson -1

BASIC OF C PROGRAMMING

In this lesson we are going to discuss the following topics:

  • HISTORY OF C
  • FEATURES OF C
  • APPLICATION OF C
  • GENERAL RULES FOR WRITING A C PROGRAM
  • STRUCTURE OF A C PROGRAM
  • WRITING, COMPILING AND RUNNING A C PROGRAM
  • CHARACTERISTICS OF A WELL-WRITTEN PROGRAM
  • THE C CHARACTER SET
  • IDENTIFIERS
  • KEYWORDS
  • DATA TYPES
  • CONSTANTS
  • VARIABLES
  • ARRAYS
  • DECLARATIONS
  • EXPRESSIONS
  • STATEMENTS

Short History about the basic of Turbo C Language

C was originally introduce in 1970's by Dennis Richie at Bell Laboratories,  Inc. ( now known as AT & T Bell Laboratories), on a DEC PDP-11 machine. It was created when Ken Thompson and Dennis Ritchie were developing the UNIX Operating System.

Learn the basic of turbo C
Learn C Program
C was largely confined to use within Bell Laboratories until 1978, when Brian Kernighan and Ritchie published a definitive description of the language.

In mid 1980's, the popularity of C had become widespread. Numerous C compilers and interpreters had been written for computers of all sizes and many commercial application programs had been developed. Many commercial software that were written in other languages were rewritten in C in order to take advantage of its efficiency and its portability

Features

  • C has the ability to write very concise source programs. Mainly because it has a large number of operators, a small set of instructions, and extensive library functions.
  • C is a general purpose, structured programming language.
  • C compilers are commonly available for all types of computer, having different platforms, different micro-processors, and different operating systems.
  • C resembles other high-level structured programming languages and contains certain additional features, that allow it to be used at a lower level , thus bridging the gap between machine language and the conventional high-level languages.
  • For your kind information, C can be used for system programming e.g. an operating  system and can be also used for application programming  such as  an Accounting Package.
  • C programs are highly portable, most of the C programs can be processed on many different computers with little or no alteration.

C Applications

C is used for writing following things:

  • Operating System 
  • Utilities & Tools         
  • Application software
  • GUI
  • CAD & CAM
  • Compilers
  • Assemblers
  • Editors
  • Word Processors
  • Spread Sheets
  • Database Managers
  • Rational  Database Management System (RDBMS)
  • Robotics, Artificial Intelligence (AI) etc..
  • ​Rules for writing a C Program
 

General rules for writing a C Program     

  • C is case-sensitive. So the word ELSE, Else, and else are treated differently.
  • All C keywords have to be used in lowercase only. 
  • Each block of instruction is embedded in curly braces '{' and '}', which are equivalent to begin and stop.
  • C is a free style language. so program statements can start at any column, blank lines and spaces may be inserted as appropriate in a program.
  • C statement is terminated by a semicolon. so a single statement can extend to many lines or multiple statements separated by semicolons can be written in a single line.
 

​C Program Structure

The following is the general form of a program in C.                                                                  

global declarations

preprocessor commands

main()

function argument declarations

{       local variables

         statement sequence



  }



​         function1(argument list)

       function argument declarations

{       local variables

         statement sequence

        -

        -

  }

       functionN(argument list)

       function argument declarations

{       local variables

         statement sequence

        -

        -

  }



  • C program, as shown above, consists of one or more functions which specify the actual computing operations to be performed. These may be library functions which are ready to use or may be user-defined.
  • Library functions will be used in the initial sessions, later on, we will see how to work with user defined functions.
  • The best way to learn C programming is by writing programs. 
 

Have a look here is an example :


#include<stdio.h>

main(){printf("Hello, everyone.");}

​              or

#include<stdio.h>

/*This is My First C Program */

main()

{

printf("Hello, everyone.");



}



#include

  • This is a pre-processor command.
  • This statement tells this pre-processor to include the information contained in the file stdio.h (Standard input output header) before it is passed for compilation.
  • The file contains a routine to perform the basic input and output.

Comments

  • Any set of characters between /* and */ is known as a comment statement.
  • They are ignored by compiler and have no effect on the size or speed of the final program.
  • A comment can be placed anywhere except inside a variable name, a constant, or a keyword.
  • Comments are helpful in identifying the program's principal features or in explaining the underlying logic of various program features.

Semicolon

  • Each expression statement must end with a semicolon.

​Braces

  • The opening brace {after main() indicates the beginning of the block of statements and the closing brace} indicates its end.
  • Each compound statement is enclosed within a pair of braces i.e, {and}.
  • The braces may contain combinations of elementary statements and other compound statements.
  • Thus, compound statements may be nested, one within another.

main()

  • main() is a special function name
  • Every C program must have a main() somewhere in the program.
  • This function will be executed first when the program is run.
  • The empty parentheses ( and ) following the name of the function indicate that this function does not  include any arguments​


​printf()

  • printf() is a library function which prints the string of characters that make up its argument on the terminal or any other destination.
  • The printf() function is used to print out a message, either on screen or paper.
  • The function called printf() is called or invoked in this program. (from stdio.h file)
  • The function has a character string as its argument.
  • This string is the sentence contained within the parentheses following the word printf. The contents of this string, are printed out.
  • A character string in C is a series of characters written within double quotation marks "  "
  • These punctuation marks are not actually part of the literal, but serve to delimit it.
  • It you need to indicate double quotes as part of a literal, you must precede it with a backslash, '\'. This symbol tells the compiler that the quotation marks are part of the string.


For Example:

printf("He said, \"Hello\"");

​C Program Writing, Compiling and Running​

  • TURBO C has an in-built editor, compiler, debugger which can be easily used by pull down menus. It also supports mouse.
  • Write a C program using an Text-Editor. For Example Edlin, DOS, ed  & vi in UNIX, notepad in Windows.
  • File name must have an extension of .C
  • The program written by the user is also known as source program.
  • Executable code or an .EXE file is the output of a compiler. 
  •  The compiler's job is to take the source code and translate it into instructions that the computer can understand and execute.

​​Working with TURBO C

​Step: 1

C:\TC> TC

​Step: 2

The user will get a screen like this: 

Turbo C language
Turbo C
  • The Top-Line is known as Menu-Bar which can be either invoked by pressing the Function Key F10, or pressing any underlined character of the command with ALT Key, i.e ALT+F will invoke the File Menu.
  • The Second-Line shows the path the file name, default filename is NONAME00.CPP
  • The Double-Line windows or the Editor Work-Space can be zoomed by pressing the Function Key F5.
  • The Double-Line border is a window, where 1 is written at the Top-Right corner, indicating the number of windows open.
  • The Double-Line border is a window also has Scroll-Boxes at the Right & Bottom corners of the windows, which can be scrolled with the help of a mouse.
  • The number (1:1) at the bottom of the Doube-Lined wondow is displaying the locating of the cursor in the editor, the first 1 indicates the Line-Number and the second 1 indicates the Column-Number.
  • The Bottom-Line of the screen is again displaying a list of some frequently used commands which can be invoked by pressing a Hot-Key. E.g.- The Function Key F2 Saves the currently opened file.

Step: 3

Press F3 - To Load a File.
Type File Name e.g. INTRO.C
Type the program.

The user will get a screen like this: 

Basic of C language
INTRO.C

  • The Function Key F6 allows switching between all open windows.
  • Press F1 for Help on Editor, Cursor Movement, Block Commands, C Commands, etc..
  • You can also take Help of a command, by placing the cursor on the command and Pressing CTRL+F1 
 
Step : 4

 Press ALT F9 - For compiling the program

The lines compiled is 315, though our program contains just 6 lines. A pre-defined function printf() is used in our program to display a string of text on the standard output, which has it's routine written in the header file <stdio.h>

Step : 5
 
Press F9 - For Linking
 
Step : 6
 
CTRL F9 - To Run the program
 
Step : 7
 
ALT F5 - To see the result on the user screen
 
Step : 8
 
F2 - To Save the file
 
Step : 9  

ALT  X -  To Quit Turbo C


The source code passes through a number of intermediate stages before an executable file is created. The stages are :
 
Editor -  Creates  -   A Source Code
C Preprocessor - Creates  -   Expanded C source code
Compiler - Creates  -   An  Object file
Linker -   Links & Creates  -   Object File & Library file Executable file
                               
 

Flowchart:

Flowchart (Basic of C)
Flowchart the basic of C language
  

Characteristics of a Well-Written Program

Integrity - It refers to the accuracy of the calculations. 

Clarity - It refers to the overall readability of the program, with particular emphasis on its underlying logic.
 
Simplicity - It may be desirable to sacrifice a certain amount of computational efficiency in order to maintain a relatively simple, straightforward program structure.
 
Efficiency - It refers to the execution speed and efficient memory utilization.
 
Modularity - Programs can be broken down into a series of identifiable sub-tasks.
 
Generality - A program should be as general as possible.
 

The C Character Set

A C Program consists of the following character set:
 
Upper Alphabet :      A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Lower Alphabet :      a b c d e f g h i j k l m n o p q r s t u v w x y z
The Digits :                0 1 2 3 4 5 6 7 8 9 
Special Character :   ~ ` ! # % ^ & * ( ) _ - + = | \ { } [ ] : ;  " ' < > , . ? /
  • These characters from basic program elements (e.g constants, variable, operators, expressions)
  • Program statements in C can use all printable ASCII characters.
  • Many compilers also allow certain other characters, such as @ and $    

Identifiers

  • Identifiers are names given  to various program elements, such as variables, functions and array.
  • Identifiers consists of letters  (A to Z), digits (0 to 9) & an underscore ( _ )
  • First character must be a letter
  • Both upper-case and lower-case letters are permitted, however they are not interchangeable (i.e., an uppercase letter is not equivalent to the corresponding lowercase letter).
  • An Underscore ( _ ) character is considered to be a letter, and is often used in the middle of an identifier, it may also be used as the first character of an identifier.
  • Must contain at least 1 character of the alphabet
  • Identifiers cannot be identical to any of the C keyword or the standard function names provided in the libraries.
  • Only the first 32 characters are significant
  • Identifier should contain enough characters so that it is meaningful.

Valid Identifiers :

                             a12          total_94

    price_per_unit   counter     DATA

    _interrupt          area           PT10

InValid Identifiers :

1st          -    The first character must be a letter 

part-no   -    The character  ( -) not allowed

room temperature   -    Space not allowed

98753    -   Should have atleast one alphabet

"c"         -   The character ( " ) not allowed

 

Keywords 

  • There are certain reserved words called keywords, that have standard, redefined meanings in C.
  •  These keywords can be used only for their intended purpose, so a programmer cannot use them to name variables, functions or constants.

  • C keywords are in lowercase only

  • The standard keywords are:

    asm               

    auto

    break

    case

    char

    const

    continue

     

    default

    do

    double

    else

    enum

    extern

    far

     

    float

    for

    huge

    if

    int

    long

    near

     

    pascal

    register

    return

    short

    signed

    sizeof

    static

     

    struct

    switch

    typedef

    union

    unsigned

    void

    volatile

    while

     
  • Some C compilers may recognize other keywords, the user may refer a manual to obtain a complete list of keywords for his or her particular compile. 

 Data Types

  • A program can be written to perform various task, during the course of execution, programs may require certain data on which the program operates on .
  • Data includes numbers and characters.
  • Some data are predetermined before a program is used and their value does not changes during the execution of the program - these are constants.
  • Before we use Constants and Variables we should be aware of Data-Types.
  • C supports everal different types of data, each of which may be represented differently within the computer's memory.
  •  The basic Data-Types are listed below:

Data-Type

 Description

int

integer

char

Single character

float

Floating-point number containing a decimal point or an exponent

double

Double-precision floating-point number        

   

       

 

Constants

C has 4 basic types of constants:
  1. Integer constants
  2. Floating-point constants
  3. Character constants
  4. String constants 
Rules for integer and floating-point constants:
  • Commas and blank space cannot be included within the constant
  • The constant can be preceded by a minus (-) sign if desired
  • The value of a constant cannot exceed specified minimum and maximum range

Integer Qualifiers

Bytes

Min Range

Max Range

int

2

-32,768

32,767

short

2

-32,768

32,767

unsigned int

2

0

65, 535

long

4

-2,147, 483, 648

2,147, 483, 647

unsigned long

4

0

4,294, 967, 295

char

1

-128

127

Signed char

1

-128

127

Unsigned char

1

0

255

float

4

3.4E-38

3.4E+38

double

8

1.7E-308

1.7E+308


Integer Constants
  • An integer constant is an integer-valued number
  • It consists of a sequence of digits
  • Integer constant can be written in 3 number systems
                 Consists of                                         e.g.
decimal    - 0 to 9                                               0  1 473  32767
octal         - 0 to 7                                               0 01  0743  077777
hexadecimal  - 0 to 9 & A to F (i.e. 10 to 15)   0x  0X1 0X7FFF Oxabcd
                      - must begin with either  0x or 0X

Unsigned and Long Integer Constants

  • An unsigned integer constant can be identified by appending the letter U (upper or lower ) to the end of the constant
  • Long Integer Constant can be identified by appending the letter L (upper or lower)to the end of the constant
  • Unsigned integer constant can be identified by appending the letter UL (upper or lower) to the end of the constant  
  Example:
 

Constant

 Number System

50000

decimal  (unsigned)

123456789L

decimal  (long)

123456789UL

decimal  (unsigned long)

0123456L

octal (long)

0777777U

octal  (unsigned long)

0X5000U

hexadecimal  (unsigned)

0XFFFFFUL

hexadecimal  (unsigned long)

 
Floating-Point constants
  • A Floating-Point constant is a base 10 number that contains either a decimal point or an exponent

Examples:
    0.  1.  0.2  827.602  50000  2E-8  0.006e-3
Character constants
  • A character is a single character, enclosed in apostrophes ( ' )
 Examples:
    'A'      'X'     '3'    '$'      ' ' 

String constants
A string constant consists of any number of consecutive characters enclosed in double quotation marks ( " )

Examples:
    "fine"    "The Answer Is : "    "$20.45"

Variables

  • A variable is an identifier that is used to represent some specified type of information within a designated  portion of the program.
  • A variable represents a single data item, that is, a numerical quantity or a character constant.
  • A data item must be assigned to the variable and can be accessed in the program simply by referring to the variable name.
  • A variable can be assigned different data items at various places within the program. So, the information represented by the variable can change during the execution  of the program.
  • Data type associated with the variable cannot be changed

Examples:
    int a, b, c,    b=6;             a=3;
    char d;         c=a + b;      d= 'Y' ;

Arrays

  • An array is an identifier that refers to a collection of data items which all have the same name.
  • The data-items must all be of the same data-types.
  • The individual data items are represented by  their corresponding array elements.
  • The individual array elements are distinguished from one another by the value that is assigned to a subscript.
  • The subscript associated with each element is shown is square brackets [ ].
  • The valve of the subscript for first element is 0, second element 1, and so on.
  • Different categories of Arrays are: Integer arrays, Character arrays, one-dimensional arrays, multidimensional arrays.
Example:
    Suppose the string "Computer" is to be stored in a one-dimensional character array called     A1. If "Computer" sting consists of 8 character, A1 will be an 9-element array. A1 [0]         will represent the letter C, A1 [1] will represent the letter and so on. 
 
Explanation:

Element

Subscript

Array

Corresponding

Number

Value

Element

Data Item

1

0

A1 [0]

C

2

1

A1 [1]

o

3

2

A1 [2]

m

4

3

A1 [3]

p

5

4

A1 [4]

u

6

5

A1 [5]

t

7

6

A1 [6]

e

8

7

A1 [7]

r

9

8

A1 [8]

\0

Declaration

  • A declaration associates a group of variables with a specific data type.
  • All variables must be declared before they can appear in executable statements.
  • A declaration consists of a data types, followed by one or more variable names ending with semicolon.
 
Example :
    int a, b, c;
    float sqrt ;
 
  • Each array variable must be followed by a pair of square brackets,  containing a positive integer which specifies the size of the array.
 char name[25];

  • Initial values can be assigned to variables within a type declaration. The declaration must consist of a data type, followed by a variable name , an equal sign ( = ) and a constant  of the appropriate type . A semicolon must appear at the end.
Example:
    int    j = 15;
    char ans = 'Y';
    float temp = 0.;

  • A character  type array can be initialized within a declaration by writing the array name, a pair  of square bracket ( either empty or array size) followed by an equal  sign, the string (enclosed in quotes) and a semicolon.
Example:
       char A1[ ]     =    "Computer" ;
or    char A1[9]    =    "Computer" ;

Note: The first 8 element will represent the 8 characters within the word Computer, and the 9th element will represent the null character (\0) which is automatically added at the end of the string.

Expressions

  • An expression represents a single data item, such as a number or a character.  
  • The expression may consist of a single entity, such as a constant, a variable, an array element, a reference to a function, or combination of such entries interconnected by one or more  operators.
  • Expression can also represent logical conditions that are either true or false.

Example:

x + y          addition operator ( + )
a = b          assignment operator ( = )
i = j + k      combination of addition  & assignment operators
a == b        test for equality, the expression will return value 1 if true or 0 if false.
m <=  n      relational operator ( <= )
i++             increment

Statements     

  • There are 3 types of statements in C:
        (a) Expression statements        
        (b) Compound statements 
        (c) Control statements
 
(a) Expression statements     

Consists of an expression followed by a semicolon, the execution of an
expression statement causes expression to be evaluated.
 
Example:
    a = 5 ;          - Assignment-type statement
    i = j + k ;     - Assignment-type statement 
    i++ ;            - incrementing-type statement
    printf("Answer  = %d" , ans) ;    - causes a standard C library function Answer = will be                                                             displayed,  followed  by the current value of the variable                                                           ans 
                                                        - Does nothing. It is an empty expression it is also known                                                           as a null statement. 
 

(b) Compound statements 
  • Consists of several individual statements enclosed within  a pair of curly braces
  • A compound statement does not end with a semicolon.
  • The individual statements may themselves be expression statements compounds statements or control statements.
  • a compound statement provides capability for  embedding statements within other statements.
Example:
{        pi =3.141593 ;
         circumf =2. * pi * radius ;
         area  = pi * radius * radius ; }



(c) Control statements
  • Are used to create logical tests, loops and branches.
Example:
    while (counter  <=i)
{        Printf("x = ") ;
          scanf("%f", &x) ;
          total += x ;
          ++counter ;       
   
 
Thank you for visit my site. If you find this article informative, please share the post to your friends.
Learn how to write the Turbo C program step-by-step | Lesson -1 Learn how to write the Turbo C program step-by-step  | Lesson -1 Reviewed by Neel Kamal on October 12, 2020 Rating: 5

No comments:

For More Details Subscribe & Comment..!

Powered by Blogger.