Monday 27 January 2014

Chapter 3: Data Input and Processing

So far we have learned the basic C programming architecture. However, that is not all with programming. Mostly, it is required to accept some input data from user, process it and then produce and show results.

So , in this chapter, we will learn following concepts

* Variables: definition, declaration and usage

* Input Function

* Processing Data

* Showing Results

 

What is meant by the term VARIABLE?

Variable can be defined as “a named memory space to store data of particular type”. The type of data being stored in variable is known as the DATA TYPE of Variable.

The term DATA TYPE

C offers 5 primary data types to allocate space within memory and store data. These are:

* int                (occupies 2 Bytes in memory, accepts whole numbers)

* char              (occupies 1 Bytes in memory, accepts single character,alphabet or Symbol )

*float              (occupies 4 Bytes in memory, accepts large fractional/double precision value)

* double          (occupies 8 Bytes in memory, same as float)

* void              (occupies 0 Bytes in memory, valueless, used as return types of functions)

The other data types defined using PRIMARY DATA TYPES are known as SECONDARY DATA TYPES such as ARRAY and STRUCTURE.

Data Type signifies the type of value along with the Storage Capacity of the variable in the memory.

Variable means changeable ;thus the value within variable can be changed at any moment within program scope.It must be remembered that the data stored within variables gets destroyed as soon as the program terminates.

How to define VARIABLE?

<type> var_name;                                -----------------(1)

or,

<type> var1, var2, … , varn;                -----------------(2)

For single variable declaration of any type, use the syntax (1) and for multiple variable declaration of same type use syntax (2).

Rules for Naming Variable

* Must be declared just at the beginning of main block().

* Variable name must begin within an alphabet.

* No spaces allowed.

* No two variables(same or different data types) can have same name.

* Special characters/symbols such as :;,./<> @#$%^&*()!~+=|\ etc not allowed. In case, variable name is multiword, join it using hyphen(-).

Example:

int ecode;                                  --------------------(Correct)

but, the below given examples of variable declaration are all incorrect

int e code;                                  --------------------(Space Not Allowed)

or

char e%name;                             --------------------(Special Symbol Not Allowed)

or

double 1sal;                           -----------------(Must begin within an Alphabet)                  

How to Input Values in variable?

Like the Output Function(used to show any message on screen), C offers Input Function to accept input from CONSOLE(i.e. Keyboard) and assign it to the specified variable. Following is the general syntax of input function,

scanf(“Format Specifier”, & var_name);

Understanding the scanf()

scanf() let your program to wait for console input by user and assign the data in mentioned format to the variable’s address.

Following is the list of format specifiers for the different data types , you could use to define variables:

int ---------- %d

char -------- %c

float -------- %f

double------%lf

It must be noted that for Double Precision Values , Double Data Type is preferred rather than float.

Also, in case you forget to mention & while scanning the variable, the entered data will not be assigned to actual memory location and your variable will contain GARBAGE DATA.

How to Output Variable’s Value

printf(“format specifier”,var_name);

or , if you want it with some message,

printf(“Message1 format specifier ”, var_name);

How to prepare EXPRESSION

Any  C Expression can be prepared using following general format

           res_var= var1 op1 var2 op2 …;

Here, the var1, var2,… are known as Operands and Op1, Op2,… are known as Operators(Mathematical Operators, the symbols that defines the working among two values of same type). The Data Type of Operands and the Result Variable must be same;otherwise Implicit Data Conversion will take place and may sometimes cause, DATA LOSS.

The permissible Mathematical Operators are:

+ – / % * ()

Along with this you may use the MATH.H library function (discussed in later chapters)

Implementing the Data Input, Processing and OUTPUT

This program accepts Employee Code, Salary from User and calculates Bonus as 12.5 % and Net Salary (Salary+Bonus)

#include <stdio.h>

main()

{

int ecode;

double esal,ebonus,net_sal;

clrscr();

printf(“"\n Enter Employee Code:”);

scanf(“%d”,ecode);

printf(“\n Enter Salary:”);

scanf(“%lf”,&esal);

// bonus being calculated as 12.5% of salary.

ebonus= esal* 12.5/100;

net_sal=esal+bonus;

printf(“\n Employee Code is :" %d”,ecode);

printf(“\n Employee Basic Salary   : %lf”,esal);

printf(“\n Employee Bonus            : %lf”,ebonus);

         printf(“\n Employee Net Salary       : %lf”,net_sal);

getch();

}

Press CTRL +F9 to compile and execute the above code.

Self Assessment Question

1. What is Operator and Operand in C Expression?

2. Give the Mathematical Operator Permissible in C Expressions?

3. Define the default Input Function scanf() in C?

4. How to Output any variable’s value along with some message?

5. Give the list of Format specifiers used to accept values in Primary Data Types in C?

6. What is variable. How to define it. Give the general rules to be remembered while defining variables?

7. Write C program code for following

       a. Accept two values from user and calculate their SUM, DIFFERENCE, MULTIPLICATION and DIVISION and Output the results on screen.

      b. Accept Sales amount from user and calculate the SALES Commission as 15 % of the sales amount

 

 

 

 

 

 

 

Chapter 2: Developing first C Program and learning basic Interface of TurboC

 

To learn programming in C, we must start with a dummy program and then understand various terms being used in that code. So write the below given code in a New File (Open TurboC> File> New>Noname00.c, the default name given to new C File).

#include <stdio.h>

main()

{

clrscr();

printf(“Welcome to My BLOG : Learning C is a FUN”);

getch();

}

After typing, press CTRL + F9 to compile and execute the above code.

Now, let us understand the statements written within main() block.

1. clrscr(); This is a library function, used to clear the Output Window and place the cursor at Top Left corner of the screen. This function can be used, whenever you want to clear the existing contents available on the screen.

2. printf(): This is the default Output Function and is used to output any message on screen. We will be discussing this in a few moments.

3. getch(): This is Input Function which accepts a single character from Console Input i.e. Keyboard but doesn’t echo it on screen. Thus, rather than using it as Input MEthod, we mostly use it as a wait statement in our program, so that as soon as user hits any Key, the program may proceed further.

The printf()

printf() is the standard Output Function used to output any message or value current position on Output Screen. The generalized format for printf is :

printf(“Message”);

Using two printf’s doesn’t make sure that the Message will appear at Next Line on Output Screen. To do this, Place New Line Character just before your message , just like shown below:

printf (“\n Message”);

You can place as many \n as you want , in any printf statement. The number of \n is equal to the number of lines after which the message will appear on screen.

Similarly, to have a TAB distance within message text, you can use “\t” within the message.

Basic TURBOC Editor Commands

1. ALT + F3 : To close any Window

2. Alter + ENTER : Toggle the FULL SCREEN and RESTORE view

3. CTRL +F9 : Compile and RUN

4. ALT +F5 : Toggle between CODE and OUTPUT Window

5. F5: To get the FULL SCREEN VIEW of any WINDOW.

6. F2: Save Program File.

7. ALT + X: Quit TURBOC .

Self Assessment Question

1. Explain the working and usage of : clrscr() and getch() function

2. Define the general format of printf() function.

3. Write a C program Code to output following on screen:

 AARTI C BLOGS

           AARTI C BLOGS

                                AARTI C BLOGS

 

 

            

Thursday 23 January 2014

Starting C : A series of Chapters to learn C

So far you have gone through the solved examples in my Blogs.I have received a lot of emails demanding “Step by Step learning of C Language'” in easy to understand language with illustrative examples.

So here we go….

Chapter 1: Basic C Program Structure

Prior to learning,the basic program structure, here are some rules to be followed while writing program,

* C being case-sensitive ; entire program should be typed in Small Case letters(By entire program, we mean all the commands and keywords being used in the program).

* Each new statement should begin with a new line.

* To mark the finishing of each statement, place a semicolon(;) at the end of statement.

The Basic C Program Structure

#include <headerfile.h>                      (1)

main()                                                 (2)

{                                                          (3)

//statements                             (4)

}                                                         (5)

 

Understanding the Program structure

(1) #include <headerfilename.h> , Here, # is known as Preprocessor(executes prior to compilation of rest of the program code) and include is a directive(simply we can call it as command). This statement is used to add any of the pre-existing header files, so that we may use the functions defined within those header files.

Some of the prominently used header files are: stdio.h, conio.h,math.h,string.h etc

(2) main(), this the executable body of your program. When you Compile and execute your program, the Compiler search for this function block in your code. If not found, your program even won’t get compiled.

In C, it is not mandatory to place void or other return type before main(), that’s why i have skipped writing that.

(3)   Beginning of main block structure. All your program statements are written within these Opening and Closing Blocks except the functions defined by you and External variables(will be discussed in later chapters).

(4) All your program statements  such as : Variable declarations, Input-Output Statements etc.

(5) End of the main() block structure. In C only, function definitions and External variable declarations are only allowed after end of main() block.

Here comes to end the Intro to C. Now, try the simple questions,

Question 1: Write the basic typing rules to be followed while writing C Program?

Question 2: Discuss the Basic C Program Structure in details?

Question 3: What will happen, if your program contains all statements except the main()?

Question 4: How many types of Basic Program statements are there in C?

Question 5: What is meant by the terms Preprocessors and Directive. Why they are used in C Program?

In the Next Chapter, we will be learning to create our First C Program  and Output Functions.

 

For suggestions and Queries on any topic mail me at softech.ratlam@gmail.com