Saturday, October 13, 2007

Variables,constants and Data types

Programming is all about processing data to get the desired results. Programs accept data and perform some kind of task. The task could be as simple as calculating percentage of marks or as complex as DNA fingerprint analysis.

In this article, you will learn how C programs work with data and perform tasks.

Data is generally defined as the raw facts input into the computer. However, in reference to C, data has a more specific meaning. It refers to two kinds of values — those associated with constants and those represented by variables.

Variables and constants

Constants refer to data that remains unchanged throughout the program execution. For example, in a program to find the area of a circle, the value of ∏ (3.1412) is constant. Some more examples of constants include numbers such as 10, 100, 22.34 and characters such as ’A’,’ ’Z’, ’*’ and ’$’.

Variables, on the other hand, store data that may vary during program execution. In the example of finding the area of a circle, the area will change from circle to circle.

In programming, each variable actually refers to a memory location where a constant is stored. Every variable has a name. You should note the following rules before naming a variable:

  1. Only alphabets, numerals, and underscores (_) are permitted (spaces and special symbols are not allowed).
  2. The name cannot start with a digit.
  3. Upper case and lower case letters are treated as different.
  4. A variable cannot be a C language keyword.

Note: Always choose meaningful names for variables.

Examples of variable names: marks1, student_no, sum, product, etc.

Data types

The C compiler must be informed about the type of data (numbers, alphabets, or special characters) you intend to store in a variable. For this, you can use C’s built-in data types.

There are three primary data types in C — int, float, and char. Other data types such as long and double are derived from these.

The int data type

The int data type can be used to store both positive and negative integers, and thus stands for ‘signed integer’. This data type also offers variations such as long and short to accommodate larger and smaller values. See Table 1 for information on the amount of memory this data type occupies and the range of values you can store).

The float data type

The float data type is used to store fractional numbers (real numbers). So, if you wish to write a program to compute something, you should use the float data type. A float value consists of an exponential and a fractional portion. Consider these values:

2.3456e-1 =2.3456 x 10-1 = 0.23456

2.3456e+2 =2.3456 x 10+2 = 234.56

Here, the values to the left of the character ‘e’ denote the fraction while those to the right denote the exponent. The complier uses the ‘e’ to separate and identify these two components. The exponent must have a positive or negative value (positive by default). To accommodate larger fractions, C provides another data type called double. See Table 1 for the memory this data type occupies and the range of values you can store using float and double).

The char data type

The char data type is used for storing characters such as alphabets and special symbols (e.g. ‘*’, ‘$’, and ‘#’). Computers use a numerical code called ASCII (American Standard Code for Information Interchange) to represent these characters. There are 256 characters in the ASCII set, all of which can be stored using the char data type.

Note: All the data types discussed above can be prefixed with the keywords signed or unsigned. The keyword signed represents both positive and negative values, whereas unsigned refers only to positive values.

Table 1

Data type

Memory size (in bytes)

Range

int

2 or 4 (depends on whether you are using 16-bit processor or 32-bit processor)

-32,768 to +32767 (2-bytes)

-2,147,483,648 to +2,147,483,648 (4-bytes)

short

2

-32768 to +32767

long

4

-2,147,483,648 to +2,147,483,648

float

4

±10 e-37 to ±10e+37

double

8

±10 e-307 to ±10e+307

char

1

-128 to +127

Declaring variables in a C program

As mentioned earlier, you have to inform the compiler about each variables name and the kind of data it is meant to store. This is called variable declaration. For example, you can create a variable called ‘num’ to store an integer value in memory by writing the statement:

int num;

Here, int is the data type and num is the name of the variable.

Understanding the "C" program

Understanding the program

In the program you saw above, the information enclosed between ‘/* */’ is called a ‘comment’ and may appear anywhere in a C program. Comments are optional and are used to increase the readability of the program.

The ‘#include’ in the first line of the program is called a preprocessor directive. A preprocessor is a program that processes the C program before the compiler. All the lines in the C program beginning with a hash (#) sign are processed by the preprocessor.

‘stdio.h’ refers to a file supplied along with the C compiler. It contains ordinary C statements. These statements give information about many other functions that perform input-output roles.

Thus, the statement ‘#include’ effectively inserts the file ‘stdio.h’ into the file hello.c making functions contained in the ‘stdio.h’ file available to the programmer. For example, one of the statements in the file ‘stdio.h’ provides the information that a function printf() exists, and can accept a string (a set of characters enclosed within the double quotes).

The next statement is the main() function. As you already know, this is the place where the execution of the C program begins. Without this function, your C program cannot execute.

Next comes the opening brace ‘{’, which indicates the beginning of the function. The closing brace ‘}’ indicates the end of the function.

The statement printf() enclosed within the braces‘{}’ informs the compiler to print (on the screen) the message enclosed between the pair of double quotes. In this case, ‘Hello, world’ is printed. As mentioned earlier, the statement printf() is a built-in function shipped along with the C compiler. Many other built-in functions are available that perform specific tasks. The power of C lies in these functions.

Be cautious about errors!

Errors/bugs are very common while developing a program. If you don't detect them and correct them, they cause a program to produce wrong results. There are three types of errors — syntax, logical, and run-time errors. Let us look at them:

  1. Syntax errors: These errors occur because of wrongly typed statements, which are not according to the syntax or grammatical rules of the language. For example, in C, if you don’t place a semi-colon after the statement (as shown below), it results in a syntax error.

printf(“Hello,world”) – error in syntax (semicolon missing)

printf("Hello,world"); - This statement is syntactically correct.

  1. Logical errors: These errors occur because of logically incorrect instructions in the program. Let us assume that in a 1000 line program, if there should be an instruction, which multiplies two numbers and is wrongly written to perform addition. This logically incorrect instruction may produce wrong results. Detecting such errors are difficult.

  1. Runtime errors: These errors occur during the execution of the programs though the program is free from syntax and logical errors. Some of the most common reasons for these errors are

    1. when you instruct your computer to divide a number by zero.
    2. when you instruct your computer to find logarithm of a negative number.
    3. when you instruct your computer to find the square root of a negative integer.

Unless you run the program, there is no chance of detecting such errors.

Try it out

1. Write a C program to print your name on the screen.

2. Write a C program to print the name of your favorite cricketer.

Structure of a C program

Every C program consists of one or more functions. A function is nothing but a group or sequence of C statements that are executed together. Each C program function performs a specific task. The ‘main()’ function is the most important function and must be present in every C program. The execution of a C program begins in the main() function.

The figure below shows the structure of a C program.


Programmers are free to name C program functions (except the main() function).

Writing your first C program

Learning any programming language becomes easy with a hands-on approach, so let’s get right to it. The following is a simple C program that prints a message ‘Hello, world’ on the screen.


main() function1() function2()

{ { {

statement1; statement1; statement1;

statement2; statement2; statement2;

……; ……..; ……;

……; ……..; ……;

} } }


------------------------------------------------------------------------------------------

/*

Author: Globarena

Date: 13/10/2002

Purpose: This program prints a message

*/

1.#include

2.main()

3.{

4. printf(“Hello, world”);

5.}


Type this program in any text editor and then compile and run it using a C-compiler. However, your task will become much easier if you are using an IDE such as Turbo C (available freely from http://community.borland.com/downloads/). Download and install Turbo C on your machine and follow the steps given below in order to type and run the program given above:

1. Go to the directory where you have installed Turbo C.
2. Type TC at the DOS command prompt.
3. In the edit window that opens, type the mentioned program above.
4. Save the program as hello.c by pressing F2 or Alt + ‘S’.
5. Press Alt + ‘C’ or Alt + F9 to compile the program.
6. Press Alt + ‘R’ or Ctrl + F9 to execute the program.
7. Press Alt + F5 to see the output.

If you are using a Linux machine, you have to follow the steps mentioned below:

1. Go to the Linux command prompt (# or $).
2. Type vi.
3. The vi editor will open.
4. Type the program in the editor.
5. Press ‘Esc + Shift + ‘:’.
6. Type ‘w’ + ‘q’ followed by file name ‘hello.c’.
7. At the command prompt type ‘gcc hello.c’.
8. Type ‘./a.out’ to run the program.

Note: C is a case-sensitive language. It makes a distinction between letters written in lower and upper case. For example, ‘A’ and ‘a’ would be taken to mean different things. Also, remember that all C language keywords should be typed in lower case.

Introduction to C programming

Introduction to C programming

Powerful features, simple syntax, and portability make C a preferred language among programmers for business and industrial applications. Portability means that C programs written for a computer with a particular kind of processor, say Intel, can be executed on computers with different processors such as Motorola, Sun Sparc, or IBM with little or no modification.

C language is widely used in the development of operating systems. An Operating System(OS) is a software(collection of programs) that controls the various functions of a computer. Also it makes other programs on your computer work. For example, you cannot work with a word processor program, such as Microsoft Word, if there is no operating system installed on your computer. Windows, Unix, Linux, Solaris, and MacOS are some of the popular operating systems.

Origin of C

Dennis M. Ritchie, a systems engineer at Bell Laboratories, New Jersey developed C in the early 1970’s. Although designed for the Unix operating system, it soon proved itself a powerful, general purpose programming language. You can learn more about the history and development of C by visiting the following Web page: http://cm.bell-labs.com/cm/cs/who/dmr/chist.html

Where is C useful?

C’s ability to communicate directly with hardware makes it a powerful choice for system programmers. In fact, popular operating systems such as Unix and Linux are written entirely in C. Additionally, even compilers and interpreters for other languages such as FORTRAN, Pascal, and BASIC are written in C. However, C’s scope is not just limited to developing system programs. It is also used to develop any kind of application, including complex business ones. The following is a partial list of areas where C language is used:

Ø Embedded Systems

Ø Systems Programming

Ø Artificial Intelligence

Ø Industrial Automation

Ø Computer Graphics

Ø Space Research

Ø Image Processing

Ø Game Programming

What kind of language is C?

C is a structured programming language, which means that it allows you to develop programs using well-defined control structures (you will learn about control structures in the articles to come), and provides modularity (breaking the task into multiple sub tasks that are simple enough to understand and to reuse).

C is often called a middle-level language because it combines the best elements of low-level or machine language with high-level languages.

Why you should learn C?

You should learn C because:

· C is simple.

· There are only 32 keywords so C is very easy to master. Keywords are words that have special meaning in C language.

· C programs run faster than programs written in most other languages.

· C enables easy communication with computer hardware making it easy to write system programs such as compilers and interpreters.

C-Language keywords

auto double if static

break else int struct

case enum long switch

char extern near typedef

const float register union

continue far return unsigned

default for short void

do goto signed while

Getting equipped to write C programs

The tools required for C programming are simple. All you need are:

  1. A text editor: A text editor allows you to type in, modify, and save your program. Notepad in Windows, Edit in DOS, and vi and Emacs in Unix/Linux are some popular text editors.

  1. A C compiler: A compiler is a program that converts the high-level language (HLL) program (referred to as source code) into machine language (object code). Borland C, GCC, and Microsoft C are some of the popular compilers.

Earlier text editors and compiler had to be used separately. However, today most software vendors provide them as a package called IDE (Integrated Development Environment). Popular IDE’s include Turbo C from Borland Inc., and Microsoft C from Microsoft Inc.

C Fundamentals

What is programming?

When we want a computer to perform a specific task, such as generating a marks sheet or a salary slip, we have to create a sequence of instructions in a logical order that a computer can understand and interpret. This sequence of instructions is called a program. The process of writing programs is called programming.

The task of programming involves a lot of effort and careful planning. Without this, the computer will produce erroneous results. The following steps should go into the planning of program:

Ø Defining and analyzing the problem

Ø Developing the solution logically using an algorithm


Defining and analyzing the problem

Before writing a program, we have to define exactly what

1. data we need to provide (input) and

2. information we want the program to produce (the output).

Once we know these, we can figure out how to develop the solution.

Deciding on input

Suppose we want to write a program to work out the total and average of a student’s marks in five subjects, we would need to mention the marks in the five subjects as input.

Deciding on output

Next, we have to think of the output — the elements that should be displayed and those that should not. In the marks example, since the task is to prepare a marks sheet, the marks in all the five subjects, their total and average should be displayed on the screen.


Developing a solution logically

Once we have defined and analyzed the problem — decided on the output and the input — we can go on to develop the solution.

The most important aspect of developing the solution is developing the logic to solve the problem. This requires creating a set of step-by-step instructions and/or rules called an algorithm. Each step performs a particular task. We can write these steps in plain English.. The algorithm for the example on finding total marks and average would look like this:

1. Note down the student’s marks in different subjects.

2. Find the total marks scored by the student.

3. Compute the average marks.

4. Assign grade.

5. Display average percentage of marks and grade.

6. End.

For any computer program to work well, it has to be written properly. Formulating an effective algorithm will make writing an effective program easier. For an algorithm to be effective, it has to have the following characteristics:

1. Finiteness: An algorithm should terminate after a fixed number of steps.

2. Definiteness: Each step of the algorithm should be defined precisely. There should be no ambiguity.

3. Effectiveness: All the operations in the algorithm should be basic and be performed within the time limit.

4. Input: An algorithm should have certain inputs.

5. Output: An algorithm should yield one or more outputs that are the result of operations performed on the given inputs.

The famous mathematician, D.E. Knuth, first expressed these characteristics.

Programming: The next step after developing an algorithm

Once we develop the algorithm, we need to convert it into a computer program using a programming language (a language used to develop computer programs). A programming language is entirely different from the language we speak or write. However, it also has a fixed set of words and rules (syntax or grammar) that are used to write instructions for a computer to follow.

Programming languages can be divided into three types. They are:

1. Machine language

This is the basic language understood by a computer. This language is made up of 0’s and 1’s. A combination of these two digits represents characters, numbers, and/or instructions. Machine language is also referred to as binary language.

2. Assembly language

This language uses codes such as ADD, MOV, and SUB to represent instructions. These codes are called mnemonics. Though these codes have to be memorized, assembly language is much easier to use than machine language.

3. High-level languages

High-level languages such as BASIC, FORTRAN, C, C++, and JAVA are very much easier to use than machine language or assembly language because they have words that are similar to English.

A quick comparison of programming languages

Machine Language

Assembly Language

High-level Languages

Time to execute

Since it is the basic language of the computer, it does not require any translation, and hence ensures better machine efficiency. This means the programs run faster.

A program called an ‘assembler’ is required to convert the program into machine language. Thus, it takes longer to execute than a machine language program.

A program called a compiler or interpreter is required to convert the program into machine language. Thus, it takes more time for a computer to execute.

Time to develop

Needs a lot of skill, as instructions are very lengthy and complex. Thus, it takes more time to program.

Simpler to use than machine language, though instruction codes must be memorized. It takes less time to develop programs as compared to machine language.

Easiest to use. Takes less time to develop programs and, hence, ensures better program efficiency.

Developing a computer program

Follow the steps given below to become a successful programmer:

  1. Define the problem: Examine the problem until you understand it thoroughly.

  1. Outline the solution: Analyze the problem.

  1. Expand the outline of the solution into an algorithm: Write a step-by-step procedure that leads to the solution.

  1. Test the algorithm for correctness: Provide test data and try to work out the problem as the computer would. This is a critical step but one that programmers often forget.

  1. Convert the algorithm into a program: Translate the instructions in the algorithm into a computer program using any programming language.

  1. Document the program clearly: Describe each line of instruction or at least some important portions in the program. This will make the program easy to follow when accessed later for corrections or changes.

  1. Run the program: Instruct the computer to execute the program. The process of running the program differs from language to language.

  1. Debug the program: Make sure that the program runs correctly without any errors or bugs as they are called in computer terminology. Finding the errors and fixing them is called debugging. Don’t get depressed when bugs are found. Think of it as a way to learn.