SOMETHING ABOUT PROGRAMMING
Introduction
Today almost everybody knows what a computer system is. The reason behind this is that we have come in contact with computers in all areas of our daily lives, such as paying our electricity bills, shopping bills, telephone bills and so on. You can say that it would be easier to list those areas of our lives not affected by computers. In fact, the field of computer is so vast that it is not possible to cover all those fields in just one book. The fields of computer depend upon the environment in which it is intended to solve problems by writing programs. Be forewarned: This book is not just about computers in the abstract. This is a text to teach you how to solve several problems in a variety of domains by writing programs in a language ‘C’.
In this MY ARTICLE you will also study – what a computer program is, what is programming, what are the basic steps involved in writing a program, what are major parts of a computer system and how they work together, and what is a programming language. In MY NEXT ARTICLE you will study history of ‘C’ as well as some the features associated with the ‘C’ programming – one of the most exciting languages. Firstly we will study about programming.
What is a Computer?
At this stage it is not mandatory to understand much about a computer in order to use it as an efficient tool because this book is intended for writing programs in a programming language ‘C’. But if you know something about the physical components of a computer system, you can better understand the effect of each instruction in the programming language.
Let us begin with the definition of a computer. Computer is a programmable device that can store, retrieve, and process data. A typical computer system has three major components:
- Memory
- Central Processing Unit
- Input / Output Devices
Figure-1 shows these components.
The memory unit is a used to hold the data and instructions. The memory unit is an ordered sequence of storage cells, each capable of holding a piece of data. Each memory cell has a distinct address to which one refers in order to store or retrieve information.
Central Processing Unit (CPU) is the part of the computer system that executes the instructions of a program stored in memory. The CPU has two main components: arithmetic/logic unit (ALU) and control unit (CU). The arithmetic/logic unit performs arithmetic operations, such as addition, subtraction, multiplication, division, and logical operations (comparison of two numbers). The control unit controls the actions of the other components in order to execute instructions (the program) in sequence.
Input/Output devices are used to receive information from the outside world and to produce the result to outside world respectively. The keyboard is a typical standard input device and a video display unit (VDU) is a standard output device. A printer is another example of a device that is used for output from the computer.
The differences among various types of computers basically involve the size of the memory, the speed with which data can be recalled from it, the efficiency by which the data can be transferred, and limitations of Input/Output devices.
Computers can also have a wide variety of peripheral devices. Peripheral devices are input, output, or auxiliary device of a computer. An auxiliary device, often called as a secondary storage device, is used to hold coded data, ready for use by the computer, in between the times when we actually want to use the data. An auxiliary device is external to computer’s memory.
The Concept of Programming
Have you ever noticed that your behavior and your thoughts are characterized by logical sequences. Every step of your life has a certain order to it. No doubt, a lot of what you do everyday is done automatically, on an unconscious level since it is not necessary for you to consciously think of every step involved in a process as simple as you brush your teeth. If you try to do this at conscious level then it involves all the following actions in a certain order or sequence as follows:
- take a brush
- clean it with water
- put some toothpaste on it
- rub the brush against your teeth for a minute
- take a glass of water and clean your teeth
Initially you had to learn this. But after some time, the action is completely automatic. In other words much of what you do unconsciously you once had to learn. After all every music requires a definite a sequence of notes in order to be recognizable.
The ultimate conclusion is that whatever we do at conscious level or at unconscious level, it takes place in a prescribed order. This ordering is called programming and when this programming is done on a computer language it is called computer programming. On the similar track, a computer program is a sequence of instructions that must be understood by the computer.
The programming process is basically a two step process:
- A problem solving phase
- An implementation phase
In problem solving phase, we firstly understand (define) the problem or you can say what a problem is. After knowing the problem, we develop a logical sequence of steps to be used to solve this problem because the computer can not itself analyze the problem and come up with a solution. It is the user or you can say a programmer who must arrive at a solution and communicate it to the computer. Thus the programmer begins the programming process by analyzing the problem and developing a general solution called an algorithm. In other words, an algorithm is just a step-by-step procedure for solving a problem in a finite amount of time.
After developing a general solution, the programmer “walk through” the algorithm by following logical sequences step by step mentally or manually. If programmer finds that this testing of the algorithm does not produce satisfactory result, he/she repeats the problem solving phase, understand the problem again and coming up with another algorithm. Of course there may be more than one solution to a problem, it is the programmer who selects which is the best one.
Once the solution is selected, it is programmer’s duty to translate this algorithm into a programming language. Translating an algorithm into a programming language is called coding the algorithm. For this we use ‘C’ programming language in this book. Like any simple language, a programming language is a set of rules, symbols, and special words used to construct a program. A programming language is essentially a simplified form of English (with math symbols) that adheres to a strict set of grammar rules.
After coding the algorithm, the resulting program is tested by executing (running) it on the computer system. If the program produces correct result then it is OK; otherwise the programmer must determine what is wrong and modify the algorithm and program as needed. If the program produces the desired results then it is used in practical application. The combination of coding and testing an algorithm is often referred to as implementing an algorithm.
Figure-2 shows the relationship between a problem solving phase and an implementation phase.
Here one should not confuse with the definition of a program and an algorithm. An algorithm is just a way of expressing the solution. It may be in a programming language or in English. And when an algorithm is expressed in a programming language it is called a program. Another main point to note is that you should not try to take a short cut in the programming process by going directly from the problem definition to the coding of the program as shown in figure-3.
Of course it saves a lot of time, but if the program does not produce the desired result in first chance then you will spend a lot of extra time in correcting errors (debugging) and revising an ill-conceived program. Therefore the best strategy is to go to problem solving phase first and then implementation phase.
The Programming Style
The concept of programming involves more than simply writing a program. In addition, using meaningful names to variables and functions, documentation and maintenance of programs are important parts of programming.
Documentation
Documentation is just a written text and comments that make a program easier for others to understand, use and modify. Documentation should be kept up to date. Any change made in the program should be marked in all of the pertinent documentation. As far as small programs are concerned you indeed can keep all the details in your head, and so needs documentation only to explain the program to someone else. But as far as large and complex programs are concerned it becomes impossible to remember how every detail relates every other and therefore, it is essential that appropriate documentation be prepared along with each small part of the program. Thus the important point is that keep your documentation concise but descriptive.
Spaces, blank lines, and indentation in a program are an important form of documentation. These white space characters make the program easy to read, allow you to tell at a glance which parts of the program relate to each other, which statements are contained in which loop, and so on. In other words, you can say that using white space characters, it is easier to determine the structure of the program.
Once a program is fully debugged and in use, it is necessary to maintain it. Maintenance of programs is the modification of programs needed to meet new requests after they have been completed.
Naming Variables and Functions
While writing a program, one should give meaningful names to variables and functions so that their places in the program can be properly recognized and appreciated. Although finding good names is not an easy task, the careful choice of names go a long way in clarifying a program and in helping to avoid common errors. Let us see what should be kept in mind while selecting names.
- Use the meaningful names for variables, constants and functions such that they should suggest clearly the purpose of variables and functions.
- Use a single letter for the variable controlling a loop.
- Use common prefixes or suffixes to associate names to variables and functions as:
- readArray
- displayArray
- insert
- delete
Debugging of Programs
The process of detecting and removing errors in a program is referred as program testing and debugging. No body is perfect, at least I am not. When we code the algorithm then it is not necessary that our program should be 100 percent error–free. It means that there may occur any type of errors in the program. And it is totally our duty to trace out such errors and correct them that are likely to be present in the program.
There are four basic types of errors:
- Syntax errors
- Run–time errors
- Logical errors
- Latent errors
Syntax Errors
Every programming language has its own set of rules and the errors, which violate such rules, are referred as syntax errors. Fortunately syntax errors are immediately detected and isolated by the compiler during compilation purpose. The compilation phase of the program would not be completed until any syntax error is present in the program.
Following are the example of some syntax errors:
- int area-square, radius-of-circle; /* no hyphen */
- float 10salary; /* starts with a number sign */
- char @basic /* starts with a @ sign */
Normally the compiler specifies the line number where the error has occurred. But in some cases, the line number may not exactly indicate the place of error. So you have to find out that place.
Run–Time Errors
The errors, which occur during the runtime of a program, are referred as run–time errors or execution–time errors. Generally run–time errors come when there is any mismatch of basic data types or make an illegal reference and so on.
Logical Errors
The errors, which are directly related to the logic of the program, are referred as logical errors. Logical errors occurs due to wrong jumping, failure to satisfy a particular condition, and any incorrect order of evaluation of statements. Like run–time errors, the logical errors are not recognized by the compiler.
Following are the examples of some logical errors:
- if (i=1)
{
stat1;
stat2;
}
Here instead of using logical equal to (==) operator we have used assignment operator. A test condition like this would always be result in true.
- if (num==sum)
printf (“Both are equal”);
If ‘num’ and ‘sum’ are float types values, then it is not necessary to become equal due to truncation error. Generally such type of errors occur due to incorrect coding of the algorithm.
Latent Errors
The errors that come in existence when we enter some special values during the execution of a program are called as latent errors. Consider the following statements:
- a = 1 / b;
In this statement an error occurs only when b is equal to 0.
- x = 4 + c / (a-b);
Here an error occurs when ‘a’ and ‘b’ are equal.
Latent errors can be detected only by using all possible combination of test data.
Program Testing
Program testing is the process of running the program on sample data chosen to find errors, if they are present, before the program is used on actual data. Earlier we have discussed that the compiler can detect only the syntactic and semantics errors. All other errors can be traced out at run time only. Therefore it is necessary for the programmers to detect all such errors by taking some realistic data.
One of the most effective way to find errors is called a structured walkthrough. You can also call it as human testing. In this the programmer shows the complete source code to another programmer or a peer group. Structured walkthrough is carried out statement by statement by the programmer and is analyzed with respect to a checklist of common errors.
The testing should be done initially on function level and when all goes well then it should be made on the complete program level. When we talk about the program testing, it is also necessary to point out the quality of test data. The quality of test data should be selected in the following ways:
- Easy values – The program is tested with data that are easy to check; otherwise the complicated data may embarrass the programmer.
- Typical Realistic value – The testing data should be simple realistic so that the result can be checked by hand.
- Extreme values – Testing should be done at the limits of his range of application.
- Illegal values – The program should also be tested for some illegal values so that it becomes able to produce a sensible error message.
The ultimate conclusion is that program testing can be used to show the presence of errors but never their absence.
Methodology for Developing Programs
We have already studied that the programming process consists of a problem solving phase and an implementation phase. Whatever may be the problem, you were warned not to try to bypass the problem solving phase even when a problem is small. When we solve even small problem we must need to take care of every details and follow a methodological approach. The practice of applying the following methodology approach to small problems will prepare you to tackle larger programming problems that you can not solve directly.
Top-Down Approach
The top-down approach divides the problem into smaller problems (subproblems) that can be handled more easily. If these subproblems are still too difficult to handle then they are subdivided again and so on. This process continues until each subproblem can not be further divided. Figure-4 shows this. It is the programmer who decides exactly how the work will be divided among them.
Sometimes we also follow bottom-up approach in which the programmer might choose to solve different parts of the problem directly in his programming language and them combine these pieces into a complete program. Experience suggests that the top-down approach should be followed when creating a program.
It is true that it is often not easy to decide exactly how to divide the work into subproblems and sometimes even a decision once made must later be modified. But once a problem has been divided into subproblems, each subproblem can be solved independently of the others. These subproblems are also called modules. That’s why the top-down approach is also called as modular programming or step-wise programming. Modules at one level can call on the services of the module at lower level. For example one module could read elements of a matrix, another could display these values, and some other modules could add, subtract, or multiply matrices.
The top-down approach can be broken down as follows:
- Understand the problem very carefully.
- Write the main (super) module.
- Write the remaining sub modules, if any.
- Resequence and revise, if necessary.
Programming Languages
Every computer system stores data and information, whether it is alphabetic or numeric, in binary codes of 0’s and 1’s. For earlier computer systems, the only programming language was machine language.
Machine Language
Machine language is the language that is used directly by the computer and composed of binary-coded instruction. Almost every computer provides some kinds of operations, therefore different system designers have chosen different sets of binary codes of 0’s and 1’s to stand for each operation. That’s why every computer system has its own machine language that depends on the specific hardware of the computer system.
While programming in machine language, one has to sufficient knowledge of the numeric codes of various operations. Obviously it is very tedious and error prone process. Even if you want to modify a correct program, you need to study the whole program repeatedly. To overcome this limitation assemble languages were developed.
Assembly Language
Assembly language is a low level programming language in which the sequence of 0’s and 1’s are replaced by mnemonic (pronounced “ni-monic”) codes. Data items and operations are specified in mnemonic codes. Typical instructions for addition and subtraction might look like this ADD and SUB. But unfortunately the instructions written in assembly language could not be directly executed by a computer because a computer does not understand assembly language program. So a system program, known as assembler, was designed to translate an assembly language program into a machine language program. Figure-5 shows the role of assembler.
However the programming in assembly language was still highly machine dependent and the programmer was still concerned with the large and complex programs. Eventually it was the first step towards the development of high-level programming languages.
High-level Languages
High-level programming languages were closer to natural languages, such as English. They also relieve programmer from the burden of low-level details of the computer system. High-level languages require a little or no knowledge of machine instructions. The main advantage of a high level language is that they are much easier to maintain and modify.
But like assembly language programs, high-level language programs needs to be translated into machine language programs prior to their execution. Therefore a system program, compiler, is written. A compiler translates a high-level language program into machine instructions. Each high-level language has its own compiler. Figure 6 shows the role of compiler.
A program written in high-level language is called a source program. When this source program is compiled by the compiler with the program as its input, an object program is produced by the compiler. Thus an object program is the machine language equivalent of a source program that results when a compiler translates a source program into binary codes for a particular computer.
Actually it is a two step process – first step translates the source program into an object program (compilation) and second step executes the object program (machine language version of the program). Figure-7 shows this two step process.
The source program is entered through an interactive program, editor. An editor is an interactive program that is used to create and modify source programs or data. Fortunately C has an built-in text editor. While coding an algorithm the programmer should keep in mind the things a computer can do.
Almost every programming language uses certain structures to express algorithms as programs. There are four basic structures, as follows:
- Sequential
- Conditional
- Repetition
- Procedures
The sequential structure is composed of statements executed one after another. The conditional structure (selection structure) executes different set of statements depending upon certain condition. The repetitive structures repeat a set of statements while certain conditions are met. The procedure enables us to replace a set of statements with a single statement. Figure-8 shows these basic structures of programming languages.
A procedure is a combination of the basic structures that is considered as a single statement in the program. In C procedures are called as functions. They allow you to write parts of your programs separately, then assemble into final form.
NOTE : IN MY NEXT ARTICLE( THE OTHER P[ART OF THIS ARTICLE ) YOU WILL READ ABOUT THE C LANGUAGE.
SOMETHING ABOUT PROGRAMMING
What is ‘C’?
As a programming language, C is rather like Pascal or Fortran. Like these programming languages, C uses variables to store values, constructs, structured programs by defining and calling functions, controls program flow using loops, if statement and switch statement. C uses arrays and structures in order to group homogeneous and non-homogeneous elements respectively. Input and output can be directed to the terminal or to files.
Programmers, who are familiar with the use of pointers, will welcome the ease of use compared with some other languages, such as in Pascal. But remember that if you use the pointers in an undisciplined way then they are very hard to trace these. In this book we will deal with the simplest application of pointers.
Of course if you are new to ‘C’ then you will find C as useful and friendly language. You have to take care of many of the extra facilities in order to avoid extra types of program errors. Once you will have to deal with these to successfully make the transition to being a C programmer.
History of C
The programming language ‘C’ was designed and written by a system programmer Dennis Ritchie at AT&T (American Telephone and Telegraph) Bell Labs in New Jersey, USA in 1972. Ritchie goal was to provide a language that would allow the programmer to access the hardware as is done with assembly language but with structured programming features similar to those found in high-level programming languages.
Actually ‘C’ was written for the UNIX operating system on a PDP-11 computer at the AT&T Bell Labs. Initially it was a totally selfish motto because Ken Thompson, another system programmer of Bell Labs, was working on a project – UNIX, a multiuser, multitasking operating system which ran first on PDP-7 and then on PDP-11. Ken Thompson wrote the original Unix system in PDP-7 assembler. It was very difficult for him to debug a program in assembly language because such programs are highly machine dependent. He was soon joined by Dennis Ritchie. Due to lack of portability, they need such a high-level language that may help them.
With these concepts, Ken Thomson developed a new language ‘B’ at AT&T Bell Labs in 1970. He adapted it from a language BCPL (Basic Combined Programming Language) developed by Matrin Richards in 1967 at Cambridge University. BCPL was used during the early 1970s for several interesting projects, among of them the OS6 operating system at Oxford, and parts of the seminal Alto work at Xerox PARC. The major limitations of BCPL was that it was too specific and it could deal with only specific problems. Ken Thomson selected the first of the initials BCPL. But like BCPL, ‘B’ too turned out to very specific. After this Dennis Ritchie modified and improved this language ‘B’, inheriting the features of ‘B’ and BCPL. Additionally he added some of his own features and developed ‘C’. It is mere coincidence that the letter B and C are alphabetic in order. Though an alternate theory holds that the letter ‘B’ is derived from Bon, an unrelated language created by Thompson during the Multics days. Bon in turn was named either after his wife Bonnie or after a religion whose rituals involving the murmuring of magic formulas. The earlier languages belonging to this ancestry are Cambridge’s CPL (Combined Programming Language) in 1963 and Algol-60 (Algorithm) in 1960.
After this UNIX operating system was rewritten in C language. More than 80% of UNIX is in C. UNIX became the first major operating system to be written in something other than assembly language. C rapidly became most programmer’s favorite language for writing program under MS-DOS. MS-DOS itself consists of C programs, as do most of its utility programs. You will be surprised to know that Windows 3.x graphical operating system was written in C. Even Windows 98 and Windows NT are written mostly in C.
Another important factor is that C is not limited to any one operating system or machine. C is one of the most portable programming language existing today. C was originally defined in 1981 in the C Programming Language (Prentice Hall) by Brian Kernighan and Dennis Ritchie. This book described C the way Ritchie implemented it. This book became known simply as K&R C. Some programmers now refer to K&R C as “Classic C”. Over the years, compiler builders added features of C according to the requirements of their own users.
Standards of C
Many different organizations have their own C compilers which may differ from one another to a greater or lesser extent. Some of the well known C compilers are as:
- Aztech
- Boroland International (Turbo C)
- Lattice DeSmet
- MicroSoft
- Power C
- Quick C
- White Smiths
Compilers can be very sensitive even to minor differences of the syntax. Therefore if you experience any difficulties then just consult the manual that comes with your version of C.
In order to provide a standard for C, a technical committee X3J11 on C language standardization, was formed by American National Standard Institute (ANSI) in 1983. The X3J11 committee represents a cross-section of C community: it consists of about fifty active members representing hardware manufacturers, vendors of compilers and other software development tools, software designers, application programmers and so on. The committee took as its reference in the K&R definition and began its lengthy and painstaking work. The job of committee was to try to eliminate ambiguities and preserve the spirit of C. ANSI was joined in their task by a committee of the International Standard Organization (ISO), which formed to define the language for the international programming community.
Development of the standard took a long time, as standards often do. Much of the work of the committee is not just technical but also procedural. The painstaking work of obtaining consensus among committee members is critical to the success of a practical standard, even if at times it means comprising on technical perfection” whatever that might be. The technical work was completed by Dec, 1988. But it took a further year to resolve procedural objections. And on Dec 7th 1989, the C language was finalized by the ANSI-committee and ISO.
The language defined by them is known as Standard C. This book introduces ANSI C since it is supported by the SUN workstation compilers. Most C programming texts are not available in ANSI editors, Unfortunately, not all compilers written adhere strictly to the standard. For one reason or another, various compilers recognize slightly different versions of the C language. Fortunately Turbo C, for example, is a 100% implementation of the ANSI C standard.
Features of ‘C’
C was first used for system programmers because it possesses the features of both low-level and high-level languages. That’s why C language is also called the middle level language. C provides the facility of manipulating bits, bytes and addresses. Such programs run faster. Now-a-days, C is also being used in developing application softwares.
Spirits of C
Some of the facets of the spirit of C can be summarized as follows:
- trust the programmer
- keep the language small and simple
- don’t prevent the program from doing what needs to be done
- provide only one way to do an operation
- make it fast
You can say that the committee kept as a major goal to preserve the traditional spirit of C.
Virtues of ‘C’
C is rapidly becoming one of the most important and popular programming languages. Virtues of C are as:
Modern Language – C is a modern and general purpose programming language that has much in common with the best of the high-level languages.
Efficient – C provides the features of both low-level and high-level language, that’s why C programs run faster than other high-level language.
Limited Data Types – Although C has four basic data types, it is not strong type language as other high-level languages, such as Pascal, Ada.
Portable – C is portable language because C compilers are available for a number of systems. C programs written on one machine can be run with little or no modification on other machine.
Powerful – C is powerful and flexible language. UNIX, compilers and interpreters for other languages, well known packages such as AUTO CAD, ORACLE, are written in C. One of the most interesting things about C language is that its compiler is written in C.
Limitations of ‘C’
No doubt, ‘C’ is reliable, simple and easy to use, but it has some limitations, as follows:
- C provides no direct provision for taking input and displaying output, rather it depends heavily on UNIX function library which is supplied with most C compilers.
- Some of the operators have the wrong precedence.
- Some part of the syntax could be better.
Regardless of these limitations, C is an extremely effective and expressive language for a wide variety of programming applications.
The Structure of a Typical ‘C’ Program
C is a procedural programming language. It means that you can design and code programs as procedural modules. The procedural modules in C programs are called functions. Every C program consists of one or more functions. Every function in a program has a unique name and it can be called through a function call. Any function can call any function. Even a function can call itself.
Functions may contain parameters. When a function is called, the values for its parameters are passed to the called function. Some functions return a value and others do not. The calling function that returns a value can code the function call on the right hand side of an assignment statement, assigning the returned value to a named variable. Each function consists of one or more block statements. In C a block is just a set of statements enclosed in a pair of curly braces ‘{’ and ‘}’. Each block has its own set of local variables, which remains in scope as long as the statements in that block are executed. A C program can also have global variables. Global variables are declared outside all functions. Global variables are called as global because the statements in all functions in the same source file can reference them.
In C statements are one of the following types:
- Declaration Statements – The statements that declare variables and functions are called as declaration statements. A variable declaration specifies the variable’s storage class, data’s type, name and dimensions, if it is an array. A function declaration, also known as function prototype, declares the function’s return type, name and number and types of its arguments.
- Definition Statements – The statements that define the instances of variables and functions are called as definition statements. A variable definition includes the components of declaration and may include an initializer if the variable has an initializing value. A function definition contains the function’s executable code.
Here one should remember that a variable declaration and definition are the same statement but a function declaration and definition are usually in different places. However the function definition may also serve as its prototype only if the function’s definition appears in the source code file ahead of all calls to the function.
- Procedural Statements – These statements include assignments, expressions, or control statements. Expressions consist of variables, constants, operators, and function calls. An expression can stand on its own or be on the right side of an assignment statement.
We have already studied that a function is collection of statements which is designed to perform a specific task. The statements must appear in the function in the same order in which we wish them to be executed. C provides sequential, selective and repetitive statements. C allows separately compiled functions to used without being in the program proper, that is a function can be accessed by any program.
Here is the structure of a typical C program:
[Comments][Preprocessor Directives]
[External Variable Declaration]
main()
{
[Local Variable Declaration]
Program Statements
}
[User-defined Functions]
The square brackets denote optional structures.
Now let us study a simple C program.
A Simple ‘C’ Program
Before going into the depth of C, let us consider a very simple program, examine it and try to discover what it does.
1. /* Program – AB.c */
2. #include
3. main()
4. {
5. printf(“Welcome to C Programming.”);
6. }
Every C program is basically a collection of functions in which main() is an essential function and several other fundamentals. Typically, we organize a program into major tasks, and then design separate functions to carry out these tasks. Here the program chap0101.c has following elements:
- Source code comments, that may contain any message starting with the character sequence /* and ending with the sequence */.
- A preprocessor #include directive
- A function heading : main()
- A function body enclosed within { and }
- A function statement that writes a message on the screen
Comments
Line numbers 1 contains a comment statement. Comments are an important part of any C program. It is helpful to understand what’s going on. Comments have no effect on the executable program because the compiler simply ignores them.
In C, comments begin with the /* character sequence and continue through the */ character sequence as follows:
/* This is a typical C comment’s style */
Usually /* …. */ style can also be used for commenting out a block of code or you can say where comments are spanned several source-code lines as:
/* This is a typicalC-style comment
that may have one or
two or three
or multiple lines */
However you can also insert a /* …. */ anywhere within the text of a program lines as:
main() /* This is main() function */{ /* main starts */
….
} /* main ends */
But we can not use nested comments, therefore following comments cause an error message:
/* It will not /* work properly *//* It will also not /* work */ properly */
However, some compilers, such as Lattice C, allow comments to be nested.
One should clear in one’s mind where to use and how to use comments. Comments are used in a program to make it meaningful, not for yourself only but also for others. Comments document your intentions, so use them, if necessary.
The Preprocessor Directives: #include
A preprocessor is a program that processes a source file before the main compilation takes place. The C language handles directives whose names begin with a number sign #. We don’t need to do anything special to invoke this preprocessor. It is invoked automatically by the compiler when we compile the program
In the program AB.c, we have used the following preprocessor directive
#include
The #include directive tells the compiler to include a different source-code file in your program. This directive tells the compiler to add the contents of the stdio.h file into your source file. This action of preprocessor is similar to pasting a block of text data into a document with your word processor.
Now the question arises – why add the contents of the stdio.h file to the program? Actually the stdio.h describes some functions that are used for console input/output because the C language does not provide any such facility of reading/writing directly on the console. The stdio.h stands for standard input–output and ‘.h’ stands for header file. By input we mean the information brought into the program and output sends out the information from the program. We can receive information either from a standard input device, keyboard, or from a file. Similarly we can send information either to a standard output device, VDU, or to a file.
The stdio.h provides scanf() function to receive information from a standard input device and printf() function to send information to a standard output device. That’s why it is necessary for the programs that use scanf() and printf() functions for input and output, to include the stdio.h file. Without its inclusion, the compiler would not recognize scanf() and printf() functions. However in some compilers, the inclusion of header files are optional. But in other compilers, it is necessary. Remember that files with .h extension are referred as header files.
The filename in the #include directive is enclosed by angle brackets, that is ‘’ (greater than symbol). This usage identifies header files that compiler system provides. However if you want to include your own header files then you would surround these user-defined header files within double quotes (“….”) as:
#include “userfile.h”
Here userfile.h is an user-defined header file.
The function main()
The third line of the program AB.c specifies a function main. Every C program must have a main() function. The word main is followed by a pair of ordinary parentheses ‘(’ and ‘)’. Here you can not use square brackets ‘[’ and ‘]’ or even curly braces ‘{’ and ‘}’. There is nothing enclosed in the parentheses because the main function does not have any parameters. In later chapters, we shall have much more to say about the parameters contained within these parentheses.
The word main() is followed by the statement(s) enclosed within the curly braces ‘{’ and ‘}’. However in C, the curly braces, along with the statements enclosed within them are referred to as a compound statement.
In some books you may also find the following notations for main() function:
- void main()
- void main(void)
- int main()
Actually the part that precedes the function main is called the function return type. The word void that precedes the function main in first and second notations specify that this function does not return any value to the caller. Similarly the word that follows the main in second notation specifies that this function receives no argument from the function that calls it. Now look at the third notation. This third notation specifies that this function returns an int value. Therefore you have to place a return statement before the closing brace of main() function as:
int main()
{
….
return 1;
}
Finally one may ask you – who calls main() function? It is not you (although in fact you can call main() if you want, just as you can call other functions); but it is the startup code who is the primary customer for main() function.
The printf() Function
The printf() function is used to display a message enclosed between the double quotes, to the monitor. It is the most important function used to display text on the screen. Like any function, the printf() function has two parentheses between which comes the string to be displayed, enclosed in double quotations.
Here the printf() function is embedded into a statement whose ending is marked by the semicolon (;). Note that every statement in C is terminated by a semicolon (;). In other words, you can say that the semicolon tells the compiler that a statement is terminated. Now look at the strange character ‘\n’ that comes right after the string and before ending the double quote mark. This character is called new-line character. This new-line character (\n) brings the cursor to the beginning of the next line.
In this ARTICLE we have studied what a program is and what a programming is. A program is basically a sequence of instructions that must be understood by a computer. The process of planning a sequence of instructions for a computer to follow is called computer programming. An algorithm is a step-by-step procedure for solving a problem in a finite amount of time.
Before writing a program one must be very careful about naming the variable names or functions. The variable names or function names must be chosen according to the activities performed by them. . Documentation is also desirable. Documentation is just a written text and comments that make a program easier for others to understand, use and modify. The process of detecting and removing errors in a program is referred as program testing and debugging.
Computer is a programmable device that can store, retrieve, and process data. A typical computer system consists of three main part: memory, central processing unit (CPU) and I/O devices. Memory is used to hold data and information. CPU is used to perform arithmetic and logical calculations and control the execution of a program and I/O devices are used to receive information from outside world and produce results to outside world.
C is middle level language which is designed by Dennis Ritchie in 1972 at AT & T Bell Labs in USA. C language is very simply, structured, portable, powerful and modern language.
...Continued with for loop.
Syntax:
for(initialization; termination; incrementation)
{
loop_statements
}
The first statement in the for loop is called intialization, which sets the loop_controller variable to its initial value. It executes only once in the beginning of the for loop.
The second statement in the for loop is called termination, which checks the loop_controller variable's value and decides whether the loop will execute further or not. This statements always executes to check the condition of the for loop.
The third statement in the for loop is called incrementation which, either increments or decrements, the loop_controller variable's value. (depending on the situation). This statement executes if the condition of the loop_controller variable is true.
so the above program to print the values from 1 to 10 can be re-written as follows:
for(int x=1;x<11;x++)
{
cout<
Here's the explanation, how this will work.
Initially a variable X will have it's initial value 1.
Then it'll check whether X is less than 11 or not. Coz the condition is true(X is less than 11), It'll enter the for loop body and print the value of X i.e. 1 this time.
Then value of x will be incremented by 1 and X will have value 2.
Now, as i told first expression (i.e. initialization will not execute) coz it executes only once in the beginning of the loop.
Then again condition will be checked and will result to true. cos X is having a value less than 11 (i.e. 2 this time).
Then it's value will be printed.
Then X will be incremented by 1.
And again it's value will be checked and be printed till X becomes 10.
Then as X will be incremented by 1. X will have a value 11.
Now when the condition is checked it'll results to false and the loop terminates.
Continued...... with Variables.
-------------
A basic objective in all computer programs is to manipulate some data and get some output. An element in this process is having a piece of memory that you can refer using a meaningful name, and where you can store an item of data. Each individual piece of memory so is called a variable. you already know, each variable will store a particular kind of data, and the type of data that can be is fixed when you define the variable in your program.
So, Now you would come to know what a variable is???
In simple words, we can say a variable is a named location in memory where we can store some data and retrieve that data by the name of the location (i.e. variable name).
In your applications, there would be a situation where you want to store the age of a person or you would want to store the marital status of a person.
So what value a variable hold will depends on situations and what data type we associate with that variable.
You can declare many variables in a program having different datatypes. So there are many kinds of datatypes in C++ and which are used frequently are as follows:
int
char
float
bool
long
User Defined Data types like Enum and Struct
and many more in the row which we will learn later.
So, you would be familiar with int data type till now which is used to store integer values.
The syntax to declare a variable is simple.
datatype variablename;
or you can store the value in the variable at the time of declaration as:
datatype variablename=value;
like,
int i=10;
above statement will declare a variable with integer datatype and having a value 10.
Char:
-------
Char datatype is used to store character values. Like
char[20]="We are using Orkut";
And float datatype is used to store floating point (fractional/decimal point value) value.
Bt now allow me to formally introduce you to Functions.
Functions/Methods:
------------------------
Functions are the set of statements which are having a function name and which we can access by referring to its name.
Or you can say, Methods are a set of actions taken by a receiver in response to a message(i.e. variable).
Functions plays an important role in object oriented programming. By these we can group some statements under one name and access them from anywhere the application.
Syntax:
---------
the syntax to create a method is as follows:
accessspecifier returntype methodname(parameters)
{
//body of the method.
}
So, in the syntax there are a few things to understand the structure of a function.
Access specifier: This specifies whether we are allowed to access/call the function from any other place(i.e class/namespace) or not. Means whether it is accessible to other program entities or not.
Return type: Specifies whether the function will return any value or not to the place from where we've called/access it. We might or might not want to return any value depending on the situations.
Method name: There should be the valid name for Method, so that we can refer to it. It should be unique and should not be same as any keyword like variable datatypes or class.
Method Body: In method body we place statements that we want to group together under a single name.
Functions:
public void add()
{
int a,b,sum;
cout<<"Enter the value of a:"a;
cout<<"Enter the value of b:"b;
sum=a+b;
cout<<"The total is: "<
In the above statements we've created a simple function that have public accessibility. Means we can access it from anywhere in our program.
Other access specifier are protected, private and friendly which we'll learn later.
The above function will not return any value to its caller. For function that do not return any values we uses void as its return type.
If we want to return any value than we can simply give the data type of the value that we want to return like int, float, char or bool.
The above method will have the name "add" which should be uniqe.
And in the body, user will be prompted to enter two values and sum will be displayed to him.
type name ( parameter1, parameter2, ...) { statements }
where:
* type is the data type specifier of the data returned by the function.
* name is the identifier by which it will be possible to call the function.
* parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.
* statements is the function's body. It is a block of statements surrounded by braces { }.
Here you have the first function example:
// function example
#include
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
The result is 8
In order to examine this code, first of all remember something said at the beginning of this tutorial: a C++ program always begins its execution by the main function. So we will begin there.
We can see how the main function begins by declaring the variable z of type int. Right after that, we see a call to a function called addition. Paying attention we will be able to see the similarity between the structure of the call to the function and the declaration of the function itself some code lines above:
The parameters and arguments have a clear correspondence. Within the main function we called to addition passing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition.
Function addition declares another local variable (int r), and by means of the expression r=a+b, it assigns to r the result of a plus b. Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8.
The following line of code:
return (r);
finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main). At this moment the program follows it regular course from the same point at which it was interrupted by the call to addition. But additionally, because the return statement in function addition specified a value: the content of variable r (return (r);), which at that moment had a value of 8. This value becomes the value of evaluating the function call.
Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This means that when calling a function with parameters, what we have passed to the function were copies of their values but never the variables themselves. For example, suppose that we called our first function addition using the following code:
int x=5, y=3, z;
z = addition ( x , y );
What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves.
This way, when the function addition is called, the value of its local variables a and b become 5 and 3 respectively, but any modification to either a or b within the function addition will not have any effect in the values of x and y outside it, because variables x and y were not themselves passed to the function, but only copies of their values at the moment the function was called.
But there might be some cases where you need to manipulate from inside a function the value of an external variable. For that purpose we can use arguments passed by reference, as in the function duplicate of the following example:
// passing parameters by reference
#include
using namespace std;
void duplicate (int& a, int& b, int& c)
{
a*=2;
b*=2;
c*=2;
}
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
x=2, y=6, z=14
The first thing that should call your attention is that in the declaration of duplicate the type of each parameter was followed by an ampersand sign (&). This ampersand is what specifies that their corresponding arguments are to be passed by reference instead of by value.
To explain it in another way, we associate a, b and c with the arguments passed on the function call (x, y and z) and any change that we do on a within the function will affect the value of x outside it. Any change that we do on b will affect y, and the same with c and z.
That is why our program's output, that shows the values stored in x, y and z after the call to duplicate, shows the values of all the three variables of main doubled.
If when declaring the following function:
void duplicate (int& a, int& b, int& c)
we had declared it this way:
void duplicate (int a, int b, int c)
i.e., without the ampersand signs (&), we would have not passed the variables by reference, but a copy of their values instead, and therefore, the output on screen of our program would have been the values of x, y and z without having been modified.
Passing by reference is also an effective way to allow a function to return more than one value. For example, here is a function that returns the previous and next numbers of the first parameter passed.
// more than one returning value
#include
using namespace std;
void prevnext (int x, int& prev, int& next)
{
prev = x-1;
next = x+1;
}
int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0;
}
previous=99 and next=101
Suppose we have written a method
int printhello()
{
cout<<"Say Hello!!!";
return 0;
}
coz we have specified the return type for the method "int" in this case. then we have to return some value from the function to the Callee function.
Thats why we have to write this.
The alternative of this is, in this case, just specify return type as void instead of int.
Like this one:
void printhello()
{
cout<<"Say Hello!!!";
}
Operators are used to compute and compare values and test any condition. Operators can be classified as:
1. Arithmetic Operators.
2. Arithmetic Assignment Operators.
3. Unary Operators.
4. Comparison Operators.
5. Logical Operators.
6. Conditional Operators.
Now We'll take Arithmetic Operators first.
As the name suggests we use Arithmetic Operators to perform ny Arithmetic Operations such as Addition, Subtraction, Multiplication and Deletion. So, these are the Arithmetic Operators : (+, -, *, /, %)
Examples:
x=y+z
Adds the value of y and z and stores the result in x
x=y-z
Subtracts the value of z from y and stores the result in x
x=y*z
Multiplies the value of y and z and stores the result in x
x=y/z
Divides the y by z and stores the result in x
x=y%z
Divides the y by z and stores the remainder in x.
In the above operators only %(Modulo Operator) needs attention. This is used to find the remainder of a division expression.
*****-----------------------------------
Now Take the Arithmetic Assignment Operators
Take any operator, like for example, += operator adds the value of the variable on the right side to the value of variable on the left side and stores the result on d variable at left side.
For example:
X += Y
This is equivalent to (X=X+Y). Both Statements will produce d same result
Examples:
x+=y
Adds the value of x and y and stores the result in x
x-=y
Subtracts the value of y from x and stores the result in x
x*=y
Multiplies the value of x and y and stores the result in x
x/=y
Divides the x by y and stores the result in x
x%=y
Divides the x by y and stores the remainder in x.
Unary operators are very useful operators in scenarios where we want to increment/Decrement the value of a variable by 1.
There are two unary operators:
++ (Two Plus Signs)
- - (Two Minus Signs)
Now Lets use them,
Suppose we want to increment the value of x by 1. We can do this by two methods.
X=X+1;
or
X++;
Yes, In Second Statement i've used unary operator to increment the value of x by one.
You can choose any method which ever suits you.
Same as you can use the decrement unary operator.
i.e.
X--;
Which will decrement the value of x by 1.
Now, In Unary Operators one thing is interesting is that, you can use it as Prefix and Postfix Notations. Like:
Suppose we have declared two variables X and Y and assigned 10 to them,
int x=y=10;
X=Y++;
and
X=++Y;
Both Statements will increment the value of Y by 1. Then what's the diff. between these two statements. The difference is that,
In 1st statement Firstly the value of Y will be copied in X and then Y will be incremented. Means here value of X and Y will be
X will show 10, and
Y will show 11.
But in Second Statement they both will show 11. Because In Second statement Y will first be incremented and then be assigned to X. So both will Show 11.
Comparison Operators:
------------------------------
As the name suggests comparison operators are used to compare two expressions, values or variables. Note, Comparison Operators returns their result in either true or false.
These are the Comparison Operators: ==, !=, >, =, <=.
== (Equals to) operator is used to compare two expressions. Say we have two variables X and Y with any values stored in them. Then, we can compare their values like,
if(X==10)
{
//ny statement
}
It will return true if value in x equals 10 or false otherwise.
Same as, we can compare for a expression that is not equals a value in a variable with !=(Not Equal to) operator. i.e.
If(X!=40)
{
//any statements
}
It will return true if value in x is not equals to 40 and false otherwise.
Same as above you can use the remaining comparison operators which are (> Greater than operator), (= Greater than equal to operator), (<= Less than equal to operator). you are also familiar with these operators as these are the basic operators used in mathematics.
----------------------------------------
Now we'll continue with Logical Operators.
Logical Operators:
-----------------------
Logical operators are used to test any two or more conditions. C++ provides the AND(&&), OR(||) and Not(!) logical operators.
AND(&&) Operator:
----------------------
It evaluates to true if all the specified conditions(two or more) are true or it returns false if any of the specified conditions results in false. Like, we have two variables, say, X and Y with values 976 and -29 respectively. We can check the values in these variables using &&(AND) operator. For eg.
if(X>897 && Y>0)
{
//any statements
}
Now what the above expression will return. Just guess!
It is going to return false because
the first expression (X>897) will return true, but
the second expression (Y>0) will return false coz y having value of (-29) i.e. less than zero.
-------------------------------
It evaluates to true if any of the specified conditions(two or more) are true or it returns false if all of the specified conditions results in false. Like, we have two variables, say, X and Y with values 976 and -29 respectively. We can check the values in these variables using &&(AND) operator. For eg.
if(X>897 || Y>0)
{
//any statements
}
Now what the above expression will return. Just guess!
It is going to return true because first statement will return true and if any conditions results a true in OR operator it returns true.
the first expression (X>897) will return true, but
the second expression (Y>0) will return false coz y having value of (-29) i.e. less than zero which will not effect the result (True this time).
Not(!) Logical Operator:
-------------------------------
The effect of this operator is that the logical value(result) of its expression is reversed.
Let's understand it with an example, suppose we have a variable X with value 12.
and if we check its value, like.
If(!(X>10))
{
////any statements...
}
Now the interesting question is, what the above exression will result. Just think by urself.
It is going to return false.
I'll tell you why.
firstly the inner expression (X>10) will return true because x is having a value greater than 10 means x is equals to 12.
now the use of NOT(!) operator has reversed the result, as it is intended to do.
That's why the above expression will return false.
---------------------------
You can exchange simple if-else code for a single operator – the conditional operator. The conditional operator is the only C++ ternary operator (working on three values).
FORMAT:
-----------
conditional Expression ? expression1 : expression2;
** if the conditional Expression is true, expression1 executes, otherwise if the conditional Expression is false, expression 2 executes.
If both the true and false expressions assign values to the same variable, you can improve the efficiency by assigning the variable one time:
(a>b) ? (c=25) : (c=45);
can be written as:
c = (a>b) ? 25 : 45;
Or Let's take another example:
Suppose X=10 and we can check for a condition i.e. X equals to 10 or not. Like
(x==10)? cout<<"x is ten": cout<<"x is not ten";
or the same work can be done also by the if else construct instead of Conditional operator. Like
if(X==10)
{
cout<<"X equals ten";
}
else
{
cout<<"Y not equals ten";
}
Conditional constructs
The If... else Construct.
The if...else conditional construct is used to make decisions for selective execution or programming statements based on the result of the comparisons. If conditional construct is followed by a logical expression where data is compared in the specified expression.
Syntax:
if(expression)
{
///any statements here.
}
else
{
///any statements here.
}
Eg.
#include
void main()
{
clrscr();
char ch;
cout<<"enter a character";
cin>>ch;
if(ch=="A")
{
cout<<"The character is A"<
else
{
cout<<"The character is not A"<
getch();
}
if we execute the above program. Firstly it'll prompt the user to enter a character. Based on the character entered it'll show the result by making a decision whether the entered character was "A" or "not A".
More Articles …
Page 14 of 21