ALGORITHM
An algorithm is any set of detailed instructions which results in a predictable end-state from a known beginning. Algorithms are only as good as the instructions given, however, and the result will be incorrect if the algorithm is not properly defined.
To make a computer do anything, you have to write a computer program. To write a computer program, you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal.
When you are telling the computer what to do, you also get to choose how it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done. Let's follow an example to help get an understanding of the algorithm concept.
Let's say that you have a friend arriving at the airport, and your friend needs to get from the airport to your house. Here are four different algorithms that you might give your friend for getting to your home:
• The taxi algorithm: Go to the taxi stand. Get in a taxi.
Give the driver my address. • The call-me algorithm:
When your plane arrives, call my cell phone. Meet me outside baggage claim.
• The rent-a-car algorithm:
Take the shuttle to the rental car place. Rent a car.
Follow the directions to get to my house. • The bus algorithm:
Outside baggage claim, catch bus number 70. Transfer to bus 14 on Main Street.
Get off on Elm street.
Walk two blocks north to my house.
All four of these algorithms accomplish exactly the same goal, but each algorithm does it in completely different way.
Each algorithm also has a different cost and a different travel time. Taking a taxi, for example, is probably the fastest way, but also the most expensive. Taking the
bus is definitely less expensive, but a whole lot slower. You choose the algorithm based on the circumstances.
In computer programming, there are often many different ways -- algorithms -- to accomplish any given task. Each algorithm has advantages and disadvantages in different situations.
PSEUDOCODE
An outline of a program, written in a form that can easily be converted into real programming statements .
For example, the pseudocode
If student's grade is greater than or equal to 60 Print "passed"
else
Print "failed"
---initialize passes to zero
initialize failures to zero initialize student to one
while student counter is less than or equal to ten input the next exam result
if the student passed add one to passes else
add one to failures add one to student counter print the number of passes print the number of failures if eight or more students passed
print "raise tuition"
---Some Keywords that should be used
For looping and selection, The keywords that are to be used include Do While...EndDo; Do Until...Enddo; Case...EndCase; If...Endif; Call ... with
(parameters); Call; Return ....; Return; When; Always use scope terminators for loops and iteration.
As verbs, use the words Generate, Compute, Process, etc. Words such as set, reset, increment, compute, calculate, add, sum, multiply, ... print, display, input,
output, edit, test , etc. with careful indentation tend to foster desirable pseudocode.
Do not include data declarations in your pseudocode.
Pseudocode (pronounced SOO-doh-kohd) is a detailed yet readable description of what a computer program or algorithm must do, expressed in a formally-styled natural language rather than in a programming language. Pseudocode is
sometimes used as a detailed step in the process of developing a program. It allows designers or lead programmers to express the design in great detail and provides programmers a detailed template for the next step of writing code in a specific programming language.
Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules. It is simply one step - an important one - in producing the final code. The benefit of pseudocode is that it enables the programmer to
concentrate on the algorithms without worrying about all the syntactic details of a particular programming language. In fact, you can write pseudocode without even knowing what programming language
Because pseudocode is detailed yet readable, it can be inspected by the team of designers and programmers as a way to ensure that actual programming is likely to match design specifications. Catching errors at the pseudocode stage is less costly than catching them later in the development process. Once the
pseudocode is accepted, it is rewritten using the vocabulary and syntax of a programming language.
FLOWCHART
The flowchart is a means of visually presenting the flow of data through an information processing systems, the operations performed within the system and the sequence in which they are performed.
The program flowchart can be likened to the blueprint of a building. As we know a designer draws a blueprint before starting construction on a building. Similarly, a programmer prefers to draw a flowchart prior to writing a computer program. As in the case of the drawing of a blueprint, the flowchart is drawn according to defined rules and using standard flowchart symbols
A flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem. Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts facilitate communication between programmers and business people. These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the
flowchart is drawn, it becomes easy to write the program in any high level language. Often we see how flowcharts are helpful in explaining the program to others. Hence, it is correct to say that a flowchart is a must for the better
documentation of a complex program.
Flowcharts are usually drawn using some standard symbols; however, some special symbols can also be developed when required. Some standard symbols, which are frequently required for flowcharting many computer programs are shown in Fig. 25.1
Start or end of the program
Computational steps or processing function of a program Input or output operation
Decision making and branching
Connector or joining of two parts of program
Magnetic Tape Magnetic Disk Off-page connector Flow line Annotation Display
a. In drawing a proper flowchart, all necessary requirements should be listed out in logical order.
b. The flowchart should be clear, neat and easy to follow. There should not be any room for ambiguity in understanding the flowchart.
c. The usual direction of the flow of a procedure or system is from left to right or top to bottom.
d. Only one flow line should come out from a process symbol.
or
e. Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible answer, should leave the decision symbol.
f. Only one flow line is used in conjunction with terminal symbol.
g. Write within standard symbols briefly. As necessary, you can use the annotation symbol to describe data or computational steps more clearly.
h. If the flowchart becomes complex, it is better to use connector symbols to reduce the number of flow lines. Avoid the intersection of flow lines if you want to make it more effective and better way of communication.
i. Ensure that the flowchart has a logical start and finish.
j. It is useful to test the validity of the flowchart by passing through it with a simple test data.
The benefits of flowcharts are as follows:
1. Communication: Flowcharts are better way of communicating the logic of a system to all concerned.
2. Effective analysis: With the help of flowchart, problem can be analysed in more effective way.
3. Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase.
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part
LIMITATIONS OF USING FLOWCHARTS
1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and clumsy.
2. Alterations and Modifications: If alterations are required the flowchart may require re-drawing completely.
3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
4. The essentials of what is done can easily be lost in the technical details of how it is done.
Examples:
Example 3
Draw a flowchart for computing factorial N (N!) Where N! = 1 ´ 2 ´ 3 ´ …… N .
Assignment :
Algorithm and flowchart to find the roots of quadratic equation ax2+bx+c=0 for all cases
Algorithm and flowchart for finding maximum and minimum of given n numbers
Algorithm and flowchart to generate Fibonacci numbers up to n In mathematics, the Fibonacci numbers are the numbers in the following sequence:
By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two.
COMPILERS and INTERPRETERS
A compiler is a special program that processes statements written in a particular programming language and turns them into machine language or "code" that a computer's processor uses.
Typically, a programmer writes language statements in a language such as Pascal or C one line at a time using an editor. The file that is created contains what are called the source statements . The programmer then runs the
appropriate language compiler, specifying the name of the file that contains the source statements.
When executing (running), the compiler first parses (or analyzes) all of the language statements syntactically one after the other and then, in one or more successive stages or "passes", builds the output code, making sure that
statements that refer to other statements are referred to correctly in the final code.
Traditionally, the output of the compilation has been called object code or sometimes an object module . (Note that the term "object" here is not related to object-oriented programming .) The object code is machine code that the processor can process or "execute" one instruction at a time.
More recently, the Java programming language, a language used in
object-oriented programming ,has introduced the possibility of compiling output
(called bytecode ) that can run on any computer system platform for which a Java virtual machine or bytecode interpreter is provided to convert the bytecode into instructions that can be executed by the actual hardware processor. Using this virtual machine, the bytecode can optionally be recompiled at the execution platform by a just-in-time compiler .
Thus, a compiler differs from an interpreter, which analyzes and executes each line of source code in succession, without looking at the entire program. The advantage of interpreters is that they can execute a program immediately. Compilers require some time before an executable program emerges. However, programs produced by compilers run much faster than the same programs executed by an interpreter.
An interpreter translates high-level instructions into an intermediate form, which it then executes. In contrast, a compiler translates high-level instructions directly into machine language. Compiled programs generally run faster than interpreted programs. The advantage of an interpreter, however, is that it does not need to go through the compilation stage during which machine instructions are
generated. This process can be time-consuming if the program is long. The interpreter, on the other hand, can immediately execute high-level programs. For this reason, interpreters are sometimes used during the development of a program, when a programmer wants to add small sections at a time and test them quickly. In addition, interpreters are often used in education because they allow students to program interactively.
C COMPILERS
Compiler Windows like UNIX- Other OSs License type IDE?
AMPC Yes Yes Yes Proprietary Yes
Amsterdam
Compiler Kit No Yes Yes
Open Source
(BSD) No
Clang Yes Yes Yes Open Source (BSD) No
GCC C Yes Yes Yes IBM mainfraime, AmigaOS, VAX/VMS, RTEMS Open source No
LabWindows/CVI Yes Yes Yes Proprietary Yes
lcc Yes Yes Yes
Proprietary (open-source freeware)
Windows
Nwcc Yes Yes Yes Open source No
Open64 Yes Yes Yes Open source No
Pelles C Yes No No Freeware Yes
Portable C
Compiler Yes Yes Yes
Open source
(BSD) No
SAS/C Yes Yes
Yes IBM mainframe, AmigaOS, 68K,
88K, Unix
Proprietary Yes
Tiny C Compiler Yes Yes No Open source No
CCS C Compiler Yes Yes No Proprietary Yes
ups debugger[1] (includes C
interpreter) No Yes
Yes Solaris,
SunOS Open source Yes
VBCC Yes Yes Yes Open Source No
C/C++ compilers
like OSs
C++ Builder Yes No No Proprietary Yes
AMD x86 Open64 Compiler Suite
? ? ? ? ?
Turbo C++
Explorer Yes No No Freeware Yes
C++ Compiler Yes No No Freeware No
Ch interpreter Yes Yes ? Freeware Yes
Code::Block[2] Yes Yes Yes Open-Source Yes
CINT Yes Yes
Yes Solaris, BeBox,
MS-DOS, Convex, etc.
X11/MIT license Yes
Borland C++ Yes No DOS Proprietary Yes
Turbo C++ for
DOS No No DOS Proprietary Yes
Clang Yes Yes Yes Open source No
CodeWarrior Yes Yes Yes ? Yes
Comeau C/C++ Yes Yes Yes Proprietary ?
CoSy compiler development
system Yes Yes No Proprietary No
Digital Mars Yes No DOS Proprietary Yes
Djgpp No No DOS Open source No
EDGE ARM
C/C++ Yes Yes Yes Proprietary Yes
MinGW Yes No No Open source No
GCC Yes Yes Yes Open source
Yes Apple Xcode for Mac OS X,
Eclipse
HP aC++ No Yes No Proprietary No
IAR C/C++
Compilers Yes No No Proprietary Yes
Intel C++
Compiler Yes Yes Yes Proprietary Yes
KAI C++
Compiler ? ? ? ? ?
Microtec Yes Yes Yes Proprietary Yes
MULTI Yes Yes Yes Proprietary Yes
Open Watcom Yes No Yes Open source Yes
PathScale No Yes No Proprietary/Open source No
PGI Workstation Yes Yes No Proprietary Yes
ProDev
WorkShop No No Yes Proprietary Yes
RealView C/C++ Compiler
(armcc) Yes Yes ? Proprietary Yes
SAS/C C++ ? ? IBM mainframe Proprietary ?
Sun Studio No Yes Yes Proprietary Yes
TenDRA No Yes No Open source No
VectorC Yes No No Proprietary No
Visual C++ Yes No No Proprietary Yes
Visual C++
Express Yes No No Freeware Yes
VisualAge C++ Yes AIX OS/2 Proprietary Yes
XL C/C++ No Yes Yes Proprietary No
Wind River
(Diab) Compiler Yes Yes Yes Proprietary Yes
Linker (computing)
In computer science, a linker or link editor is a program that takes one or more objects generated by a compiler and combines them into a single executable program.
Computer programs typically comprise several parts or modules; all these
parts/modules need not be contained within a single object file, and in such case refer to each other by means of symbols. Typically, an object file can contain three kinds of symbols:
• defined symbols, which allow it to be called by other modules,
• undefined symbols, which call the other modules where these symbols are defined, and
• local symbols, used internally within the object file to facilitate relocation. When a program comprises multiple object files, the linker combines these files into a unified executable program, resolving the symbols as it goes along. Linkers can take objects from a collection called a library. Some linkers do not include the whole library in the output; they only include its symbols that are referenced from other object files or libraries. Libraries exist for diverse purposes, and one or more system libraries are usually linked in by default.
The linker also takes care of arranging the objects in a program's address space. This may involve relocating code that assumes a specific base address to
another base. Since a compiler seldom knows where an object will reside, it often assumes a fixed base location (for example, zero). Relocating machine code may involve re-targeting of absolute jumps, loads and stores.
The executable output by the linker may need another relocation pass when it is finally loaded into memory (just before execution). This pass is usually omitted on hardware offering virtual memory — every program is put into its own address space, so there is no conflict even if all programs load at the same base address. This pass may also be omitted if the executable is a position independent
executable.
The GNU Compiler Collection (usually shortened to GCC) ,Originally named the GNU C Compiler, because it only handled the C programming language, GCC 1.0 was released in 1987, and the compiler was extended to compile C++ in December of that year
TURBO C COMPILER
Turbo C++ was a C++ compiler and integrated development environment (IDE) originally from Borland. Most recently it was distributed by Embarcadero
Technologies, which acquired all of Borland's compiler tools
Turbo C++ v1.01 and Turbo C v2.0 can be downloaded, free of charge, from Borland's Antique Software website
C PROGRAMMING LANGUAGE HISTORY
The development of Unix in the C language made it uniquely portable and improvable.
The first version of Unix was written in the low-level PDP-7 assembler language. Soon after, a language called TMG was created for the PDP-7 by R. M. McClure. Using TMG to develop a FORTRAN compiler, Ken Thompson instead ended up developing a compiler for a new high-level language he called B, based on the earlier BCPL language developed by Martin Richard.
When the PDP-11 computer arrived at Bell Labs, Dennis Ritchie built on B to create a new language called C which inherited Thompson's taste for concise syntax, and had a powerful mix of high-level functionality and the detailed features required to program an operating system. Most of the components of Unix were eventually rewritten in C, culminating with the kernel itself in 1973. Because of its convenience and power, C went on to become the most popular programming language in the world over the next quarter century.
This development of Unix in C had two important consequences:
• Portability . It made it much easier to port Unix to newly developed
computers, because it eliminated the need to translate the entire operating system to the new assemble language by hand:
o First, write a C-to-assembly language compiler for the new machine.
o Then use the new compiler to automatically translate the Unix C language source code into the new machine's assembly language. o Finally, write only a small amount of new code where absolutely
required by hardware differences with the new machine. • Improvability . It made Unix easy to customize and improve by any
programmer that could learn the high-level C programming language. Many did learn C, and went on to experiment with modifications to the operating system, producing many useful new extensions and
enhancements.
What is the advantages of c language?
• Speed of the resulting application. C source code can be optimized much more than higher-level languages because the language set is relatively small and very efficient .It is about as close as you can get to
programming in assembly language, without programming in assembly language .Heck you can even use assembly and C together!
• That leads to a second advantage that C has which is its application in Firmware programming (hardware). That is due to its ability to use/work with assembly and communicate directly with controllers, processors and other devices.
• C is a building bock for many other currently known languages. Look up the history of C and you will find that it has been around for some time . Take a look at Python for example a fully Object-Oriented High-Level programming language. It is written in C (perhaps C++ too). That tells you if you ever want to know what is going on under the hood in other
languages; understanding C and how it works is essential.
• C is a compiled language versus an interpreted language. Explained simply, this means that the code is compacted into executable instruction (in the case of windows anyway) rather than being "translated" on the fly at run time. This feature also lends heavily to the speed of C programs.
DISADVANTAGES OF C ARE: 1. There is no runtime checking.
2.There is no strict type checking(for ex:we can pass an integer value for the floating data type).
3. As the program extends it is very difficult to fix the bugs. FEATURES OF C
C has facilities for structured programming and allows lexical variable scope and recursion, while a static type system prevents many unintended operations. In C, all executable code is contained within functions. Function parameters are
always passed by value. Pass-by-reference is simulated in C by explicitly
passing pointer values. C also exhibits the following more specific characteristics: • variables may be hidden in nested blocks
• partially weak typing; for instance, characters can be used as integers • low-level access to computer memory by converting machine addresses
to typed pointers
• function and data pointers supporting ad hoc run-time polymorphism • array indexing as a secondary notion, defined in terms of pointer
arithmetic
• a preprocessor for macro definition, source code file inclusion, and conditional compilation
• complex functionality such as I/O, string manipulation, and mathematical functions consistently delegated to library routines
• A relatively small set of reserved keywords
o A lexical structure that resembles B more than ALGOL Absent features
The relatively low-level nature of the language affords the programmer close control over what the computer does, while allowing special tailoring and aggressive optimization for a particular platform. This allows the code to run efficiently on very limited hardware, such as embedded systems.
C does not have some features that are available in some other programming languages:
• No nested function definitions
• No direct assignment of arrays or strings (copying can be done via standard functions; assignment of objects having struct or union type is supported)
• No requirement for bounds checking of arrays • No operations on whole arrays
• No syntax for ranges, such as the A..B notation used in several languages • Prior to C99, no separate Boolean type (zero/nonzero is used instead)[6]
• No formal closures or functions as parameters (only function and variable pointers)
• No generators or coroutines; intra-thread control flow consists of nested function calls, except for the use of the longjmp or setcontext library functions
• No exception handling; standard library functions signify error conditions with the global errno variable and/or special return values, and library functions provide non-local gotos
• Only rudimentary support for modular programming
• No compile-time polymorphism in the form of function or operator overloading
• Very limited support for object-oriented programming with regard to polymorphism and inheritance
• Limited support for encapsulation
• No native support for multithreading and networking
• No standard libraries for computer graphics and several other application programming needs
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.
Programmers are free to name C program functions (except the main() function).
A C program basically has the following form: • Preprocessor Commands
• Functions • Variables
• Statements & Expressions • Comments
/* Documentation section */ /* Link section */
/* Definition section */
/* Global declaretion section */ /* Function section */
(return type) (function name) (arguments...) void main()
{
Declaration part
Executable part (statements) }
/* Sub-program section */
(return type) (function name 1) (arguments...) (return type) (function name 2) (arguments...) .
. .
(return type) (function name n) (arguments...)
________________________________________________________________ The following program is written in the C programming language. Open a text file
hello.c using vi editor and put the following lines inside that file.
#include <stdio.h> int main() { /* My first program */ printf("Hello, World! \n");
return 0;// return interger value zero }
NOTE: In computer programming, a return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called — known as its return address. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.
If a function does not have a return type (i.e., its return type is void), the return statement can be used without a value, in which case the program just breaks out of the current function and returns to the calling one.
exit(0)
This causes the program to exit with a successful termination. exit(1)
This causes the program to exit with a system-specific meaning. On many systems, exit(1) signals some sort of failure, however there is no guarantee.
As I recall, the C standard only recognizes three standard exit values:
EXIT_SUCCESS -- successful termination EXIT_FAILURE -- unsuccessful termination 0 -- same as EXIT_SUCCESS
_____________________________________________________________ Preprocessor Commands: These commands tells the compiler to do
preprocessing before doing actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. You will learn more about C
Preprocessors in C Preprocessors session.
Functions: are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. This function is prefixed with keyword int which means this function returns an integer value when it exits. This integer value is retured using return statement.
The C Programming language provides a set of built-in functions. In the above example printf() is a C built-in function which is used to print anything on the screen.
Variables: are used to hold numbers, strings and complex data for manipulation..
Statements & Expressions : Expressions combine variables and constants to create new values. Statements are expressions,
assignments, function calls, or control flow statements which make up C programs
Comments: are used to give additional useful information inside a C Program. All the comments will be put inside /*...*/ as given in the example above. A comment can span through multiple lines.
Note the followings
• C is a case sensitive programming language. It means in C printf and Printf will have different meanings.
• C has a free-form line structure. End of each C statement must be marked with a semicolon.
• Multiple statements can be one the same line.
• White Spaces (ie tab space and space bar ) are ignored. • Statements can continue over multiple lines.
C Program Compilation
To compile a C program you would have to Compiler name and program files name. Assuming your compiler's name is cc and program file name is hello.c, give following command at Unix prompt.
$cc hello.c
This will produce a binary file called a.out and an object file hello.o in your current directory.
Here a.out is your first program which you will run at Unix prompt like any other system program. If you don't like the name a.out then you can produce a binary file with your own name by using -o option while compiling C program. See an example below
$cc -o hello hello.c
Now you will get a binary with name hello. Execute this program at Unix prompt but before executing / running this program make sure that it has execute permission set. If you don't know what is execute permission then just follow these two steps
$chmod 755 hello $./hello
This will produce following result Hello, World
The skeleton of a simple C program is given below : main() { statement 1 ; statement 2 ; } function1() { variable declarations; statement 1; statement 2; }
· A C program is nothing but a collection of one or more functions. A function name is always followed by a pair of parenthesis, as in case of main().
· Every program must have a special function named main(). The program execution starts from this function.
· The group of statements within main() are executed sequentially. The closing brace of the main() function signals the end of the program. When this brace is reached, the program execution stops and the control is handed over to the operating system.
· There should be a main() function somewhere in the program so that the computer can determine where to start the execution.
· The main() function can be located anywhere in the program, but the general practice is to place it as the first function for better readability.
WRITING YOUR FIRST C PROGRAM
The following is a simple C program that prints a message ‘Hello, world’ on the screen.
/*
Author: JNTU Date: 13/10/2009
Purpose: This program prints a message */ 1.#include<stdio.h> 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.
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<stdio.h>’ 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 in function shipped along with the C compiler. Many other built-in functions are available that perform specific tasks. The power of C lies built-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. 2. 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.
3. 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
a. when you instruct your computer to divide a number by zero. b. when you instruct your computer to find logarithm of a
negative number.
c. 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. Assignment
1. Write a C program to print your name and address on the screen. 2. Write a C program to print the name of your favorite cricketer.
Every C program must contain a main function , since the main function is the rst function called when you run your program at the command line.
int main(void) {
printf(‘‘Hello world!\n’’); }
The int stands for the \return type", which says that the main function returns an integer if you tell it to do so. We will get into more detail with functions and return types, but you can return a number to the command line with the return function in C, as in
int main(void) {
printf(‘‘Hello world!\n’’); return 2;
}
When you compile and run your program, it will return a 2 to the command line, that you can access with the $? character, which stores the value returned by the last command executed, as in
$ ./a.out Hello world! $ echo $? 2
Just as in shell scripts, you can specify exit codes in C as well, which perform the same function as the return function in the previous example:
int main(void) {
printf(‘‘Hello world!\n’’); exit(2);
}
Compiling and running this example yields the same result as the previous example. The void statement in main(void) tells the main function that there are no arguments being supplied to it at the command line.
Note that all statements in C programs end with the semicolon ; except for the prepro-cessor directives that begin with #.
How C program works
The jump to the object oriented C++ language becomes much easier. C++ is an extension of C, and it is nearly impossible to learn C++ without learning C first. What is C?
C is what is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an executable that the computer can run (execute).
The C program is the human-readable form, while the executable that comes out of the compiler is the machine-readable and executable form. What this means is that to write and run a C program, you must have access to a C compiler.
If you are using a UNIX machine (for example, if you are writing CGI scripts in C on your host's UNIX computer, or if you are a student working on a lab's UNIX machine), the C compiler is available for free. It is called either "cc" or "gcc" and is available on the command line.
If you are a student, then the school will likely provide you with a compiler -- find out what the school is using and learn about it. If you are working at home on a Windows machine, you are going to need to download a free C compiler or purchase a commercial compiler.
On a UNIX machine, type gcc samp.c -o samp (if gcc does not work, try cc). This line invokes the C compiler called gcc, asks it to compile samp.c and asks it
to place the executable file it creates under the name samp. To run the program, type samp (or, on some UNIX machines, ./samp).
•
• On a DOS or Windows machine using DJGPP, at an MS-DOS prompt type gcc samp.c -o samp.exe. This line invokes the C compiler called gcc, asks it to compile samp.c and asks it to place the executable file it creates under the name samp.exe. To run the program, type samp.
•
• If you are working with some other compiler or development system, read and follow the directions for the compiler you are using to compile and execute the program.
If you mistype the program, it either will not compile or it will not run. If the program does not compile or does not run correctly, edit it again and see where you went wrong in your typing. Fix the error and try again.
• This C program starts with #include <stdio.h>. This line includes the "standard I/O library" into your program. The standard I/O library lets you read input from the keyboard (called "standard in"), write output to the screen (called "standard out"), process text files stored on the disk, and so on. It is an extremely useful library. C has a large number of standard libraries like stdio, including string, time and math libraries.
•
• A library is simply a package of code that someone else has written to make your life easier (we'll discuss libraries a bit later).
•
• The line int main() declares the main function. Every C program must have a function named main somewhere in the code. We will learn more about functions shortly. At run time, program execution starts at the first line of the main function.
• In C, the { and } symbols mark the beginning and end of a block of code. In this case, the block of code making up the main function contains two lines. •
• The printf statement in C allows you to send output to standard out (for us, the screen). The portion in quotes is called the format string and describes how the data is to be formatted when printed. The format string can contain string literals such as "This is output from my first program!," symbols for carriage
returns (\n), and operators as placeholders for variables (see below). •
• If you are using UNIX, you can type man 3 printf to get complete
documentation for the printf function. If not, see the documentation included with your compiler for details about the printf function.
• The return 0; line causes the function to return an error code of 0 (no error) to the shell that started execution.
Header file
In computing, header files are a feature of some programming languages (most famously C and C++) that allows programmers to separate certain elements of a program's source code into reusable files.
Header files commonly contain forward declarations of classes, subroutines, variables, and other identifiers. Programmers who wish to declare standardized identifiers in more than one source file can place such identifiers in a single header file, which other code can then include whenever the header contents are required. The C standard library traditionally declare their standard functions in header files.
Newer compiled languages (such as Java, C#) do not use forward declarations; identifiers are recognized automatically from source files and read directly from dynamic library symbols. This means header files are not needed.
In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, or a function) for which the
programmer has not yet given a complete definition. but at some point the programmer would still have to provide definitions for the declared entities. struct person;
int elements[]; void print(int);
After processing these declarations, the compiler would allow the programmer to refer to the entities person, elements and print in the rest of the program struct person
{
const char *name; char sex; int age; }; int elements[10]; void print(int x) { printf("%d\n", x); }
the following are some of the header files in c: #include<stdio.h> #include<string.h> #include<math.h> #include<stdlib.h> #include<floats.h> #include<conio.h> #include<time.h> #include<limits.h> #include<graphic.h> #include<ctype.h> #include<malloc.h> #include<calloc.h> #include<sound.h> there are about 32 header files in c
A header file is used to define constants, variables, macro's and functions that may be common to several applications. When a system consists of multiple applications that all access the same data it becomes essential that each
application uses identical definitions and it is safer for all of those applications to use the same methods to read that data. updating data should only be performed by a single function, from a single application, but reading data can be safely performed by using the common defintions found in header files.
A header file is a file containing C declarations and macro definitions to be shared between several source files. You request the use of a header file in your program by including it, with the C preprocessing directive `#include'. Header files serve two purposes.
• System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries.
• Your own header files contain declarations for interfaces between the source files of your program. Each time you have a group of related declarations and macro definitions all or most of which are needed in several different source files, it is a good idea to create a header file for them.
Including a header file produces the same results as copying the header file into each source file that needs it. Such copying would be time-consuming and error-prone. With a header file, the related declarations appear in only one place. If they need to be changed, they can be changed in one place, and programs that include the header file will automatically use the new version when next recompiled.
The header file eliminates the labor of finding and changing all the copies as well as the risk that a failure to find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with .h. It is most portable to use only letters, digits, dashes, and underscores in header file names, and at most one dot.
Both user and system header files are included using the preprocessing directive `#include'. It has two variants:
#include <file>
This variant is used for system header files. It searches for a file named file in a standard list of system directories. You can prepend directories to this list with the -I option.
#include "file"
This variant is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. You can prepend directories to the list of quote directories with the -iquote option.
The argument of `#include', whether delimited with quote marks or angle brackets, behaves like a string constant in that comments are not
recognized, and macro names are not expanded. Thus, #include <x/*y> specifies inclusion of a system header file named x/*y.
C library headers
Name Description
<assert.h> Contains the assert macro, used to assist with detecting logical errors and other types of bug in debugging versions of a program.
<complex.h> A set of functions for manipulating complex numbers.
<ctype.h>
Contains functions used to classify characters by their types or to convert between upper and lower case in a way that is independent of the used character set (typically ASCII or one of its extensions, although implementations utilizing EBCDIC are also known).
<errno.h> For testing error codes reported by library functions.
<fenv.h> For controlling floating-point environment.
<float.h>
Contains defined constants specifying the implementation-specific properties of the floating-point library, such as the minimum
difference between two different floating-point numbers
(_EPSILON), the maximum number of digits of accuracy (_DIG) and the range of numbers which can be represented (_MIN, _MAX).
<inttypes.h> For precise conversion between integer types.
<iso646.h> For programming in ISO 646 variant character sets.
<limits.h>
Contains defined constants specifying the implementation-specific properties of the integer types, such as the range of numbers which can be represented (_MIN, _MAX).
<locale.h> For setlocale and related constants. This is used to choose an appropriate locale.
<math.h> For computing common mathematical functions.
<setjmp.h> Declares the macros setjmp and longjmp, which are used for non-local exits.
<signal.h> For controlling various exceptional conditions.
<stdarg.h> For accessing a varying number of arguments passed to functions.
<stdint.h> For defining various integer types.
<stddef.h> For defining several useful types and macros.
<stdio.h> Provides the core input and output capabilities of the C language. This file includes the venerable printf function.
<stdlib.h>
For performing a variety of operations, including conversion, pseudo-random numbers, memory allocation, process control, environment, signalling, searching, and sorting.
<string.h> For manipulating several kinds of strings.
<tgmath.h> For type-generic mathematical functions.
<time.h> For converting between various time and date formats.
<wchar.h> For manipulating wide streams and several kinds of strings using wide characters - key to supporting a range of languages.
<wctype.h> For classifying wide characters.
C standard library
The C standard library consists of a set of sections of the ISO C standard which describe a collection of header files and library routines used to implement
common operations, such as input/output and string handling, in the C programming language.
The C standard library is an interface standard described by a document; it is not an actual library of software routines available for linkage to C programs. No such implementation is properly called C standard library.
The term C runtime library is used on some platforms to refer to a set of base libraries, which may be distributed in dynamically linkable form with an operating system (with or without header files), or distributed with a C compiler.
Another term sometimes used is libc. Not just any library is called the run-time library; run time in this context means the run-time support package associated with a compiler which is understood to make a language complete. The run-time support provides not only the C standard library functions, but possibly other material needed to create an environment for the C program, such as
initialization prior to the invocation of the main function, or subroutines to provide arithmetic operations missing from the CPU that are needed by code generated by the C compiler.
WHAT IS A GLOBAL DECLARATION?
A global declaration of a function or variable is a declaration that is at the global scope of the program, not inside another function. This means that the name will be visible within all functions in the program.
THE MAIN FUNCTION AND PROGRAM EXECUTION
Every C program has a primary (main) function that must be named main. If your code adheres to the Unicode programming model, you can use the
wide-character version of main, wmain. The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program. A program usually stops executing at the end of main, although it can terminate at other points in the program for a variety of reasons. At times, perhaps when a certain error is detected, you may want to force the termination of a program. To do so, use the exit function.
MAIN FUNCTION IN C IS A USER-DEFINED FUNCTION. No doubt it is a rule that without main function C program can not be compiled means that Main function is just to inform compiler about starting of program which is pre-defined in C.
DON'T BE CONFUSED BETWEEN THE PRE-DEFINED STATEMENT AND PRE-DEFINED FUNCTION.
PRE-DEFINED STATEMENT IS PROGRAM STARTS WITH MAIN FUNCTION AND PRE-DEFINED FUNCTIONS ARE THE FUNCTIONS WHICH ARE
TOTALLY DEFINED IN LIBRARY/HEADER FILE.
Functions within the source program perform one or more specific tasks. The main function can call these functions to perform their respective tasks. When main calls another function, it passes execution control to the function, so that execution begins at the first statement in the function. A function returns control
to main when a return statement is executed or when the end of the function is reached.
You can declare any function, including main, to have parameters. The term "parameter" or "formal parameter" refers to the identifier that receives a value passed to a function. When one function calls another, the called function receives values for its parameters from the calling function. These values are called "arguments." You can declare formal parameters to main so that it can receive arguments from the command line using this format
When you want to pass information to the main function, the parameters are traditionally named argc and argv, although the C compiler does not require these names. The types for argc and argv are defined by the C language. Traditionally, if a third parameter is passed to main, that parameter is named envp.
******In C, main() cannot return anything other than an int.Something like void main() is illegal. There are only three valid return values from main() - 0, EXIT_SUCCESS, and EXIT_FAILURE
The C preprocessor (cpp) is the preprocessor for the C programming language. In many C implementations, it is a separate program invoked by the compiler as the first part of translation. The preprocessor handles directives for source file
inclusion (#include), macro definitions (#define), and conditional inclusion (#if). WHAT ARE MACROS?
Macros, which are special lines/fragments of code, differ from any other code written in the source files in the aspect that it's not passed to the compiler (either for the purpose of encoding into machine instructions, or some intermediate form instructions). Instead, macros perform textual manipulations on the source code before passing it to the compiler, where this process preliminary to compiling the source files is called "preprocessing", and the software component responsible of doing it is called the "preprocessor". Henceforth, macros are usually defined as "preprocessor directives", where a segment of code is replaced by the results of the macro processing before passing the source code to the compiler. A very valuable technique to gain a thorough understanding of the operation of macros in any environment is to learn how to obtained the preprocessed source code, and see how the macro directives are expanded.
In C and C++, a Macro is a piece of text that is expanded by the preprocessor part of the compiler. This is used in to expand text before compiling.
Everywhere that VALUE is used the number of 10 will be used instead. int fred[VALUE];
#define A 2 #define B 3 #define C A + B
It is better to use constants with const instead of the #define macro. NESTED COMMENTS
In the following program, the second printf() is a comment: #include <stdio.h>
int main(void) {
printf("This program has a comment.\n");
/* printf("This is a comment line and will not print.\n"); */ return 0;
}
Because the second printf() is equivalent to a space, the output of this program is:
This program has a comment.
Because the comment delimiters are inside a string literal, printf() in the following program is not a comment.
#include <stdio.h> int main(void) {
printf("This program does not have \ /* NOT A COMMENT */ a comment.\n"); return 0;
}
The output of the program is: This program does not have
You can nest single line comments within C-style comments. For example, the following program will not output anything:
#include <stdio.h> int main(void) {
/*
printf("This line will not print.\n"); // This is a single line comment
// This is another single line comment printf("This line will also not print.\n"); */
return 0; \\ }
RULES IN C PROGRAMMING LANGUAGE
Here are some of the syntax rules in C Programming
that must be familiarize:
a. Put semicolon at the end of variable declaration. b. Commas should be used to separate variables.
c. Variables should be declared first before it can be used. d. An identifier must not begin with a digit.
e. An identifier must consist only of letters, digits, or underscores. f. An identifier defined in a C standard library must not be redefined. g. C reserved words cannot be used as an identifier.
h. In using the scanf function the order of the placeholders must correspond to the order of the variables in the input list.
C PROGRAM COMPILATION STEPS? There are 6 steps
1. Pre-processor - which replaces macros 2. Code will be separated from comments 3. syntax error will be given - types of parsing
5. assembler - will convert assembly to machine language 6. linker - will generate final executable.
THE C CHARACTER SET
The character set in C Language can be grouped into the following categories. 1. Letters
2. Digits
3. Special Characters 4. White Spaces
White Spaces are ignored by the compiler until they are a part of string constant. White Space may be used to separate words, but are strictly prohibited while using between characters of keywords or identifiers.
C Character-Set Table
Letters Digits
Upper Case A to Z 0 to 9
Lower Case a to z .
A character denotes any alphabet ,digit or symbols to represent
information.The following are the valid alphabets, numbers and special symbols permitted in C
Numerals: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Alphabets: a, b, ….z
A, B, ……...Z
Arithmetic Operations: +, -, *, /, %(Mod) Special Characters:
( ) { } [ ] < >
= ! $ ? . , : ;
‘ “ & | ^ ~ ` #
\ blank - _ / * % @
CONSTANTS, VARIABLES AND KEYWORDS
A ‘constant’ is an entity that does not change, but a ‘variable’ as the name suggests may change.
We do a number of calculations in a computer and the computed values are stored in some memory spaces. Inorder to retrieve and re-use those values from the computer’s memory locations they are given names. Since the value stored in each location may change, the names given to these locations are called as ‘variable names’.
Constants:
There are mainly three types of constants namely: integer, real and character constants.
Integer Constants: The integer constants
• Whole Numbers • Eg. 25, 35, -25, -46
• Computer allocates only 2 bytes in memory.
• 16th bit is sign bit. (if 0 then +ve value, if 1 then –ve value)
• 0 to 9
• E.g: 49, 58, -62, … (40000 cannot come bcoz it is > 32767) (ii) Octal Integer Constant:
• 0 to 7
• Add “0” before the value. • Eg.: 045, 056, 067
(iii) Hexadecimal Integer: • 0 to 9 and A to F
• Add 0x before the value • E.g: 0x42, 0x56, 0x67
REAL CONSTANTS:
The real or floating point constants are in two forms namely fractional form and the exponential form.
A real constant in fractional form must: • Have at least one digit
• It must have a decimal point
• Could have positive or negative sign(default sign is positive) • Must not have commas or spaces within it
• Allots 4 bytes in memory Ex: +867.9, -26.9876, 654.0
In exponential form, the real constant is represented as two parts. The part lying before the ‘e’ is the ‘mantissa’, and the one following ‘e’ is the
‘exponent’.
The real constant in exponential form must follow the following rules: • The mantissa part and the exponential part should be separated by
the letter ‘e’
• The mantissa may have a positive or negative sign(default sign is positive)
• The exponent must have at least one digit
• The exponent must be a positive or negative integer(default sign is positive)
• The range of real constants in exponential form is -3.4e38 and -3.4e38
Ex: +3.2e-4, 4.1e8, -0.2e+4, -3.2e-4 CHARACTER CONSTANTS
A character constant is an alphabet, a single digit or a single special symbol enclosed within inverted commas. The maximum length of a character constant can be 1 character. Allots 1 byte of memory
Ex: ’B’, ’l’, ’#’ STRING CONSTANTS
Strings in C are represented by arrays of characters. The end of the string is marked with a special character, the null character, which is simply the character with the value 0. The null or string-terminating character is represented by
another character escape sequence, \0.
In fact, C's only truly built-in string-handling is that it allows us to use string constants (also called string literals) in our code. Whenever we write a string, enclosed in double quotes, C automatically creates an array of characters for us, containing that string, terminated by the \0 character. For example, we can declare and define an array of characters, and initialize it with a string constant:
char string[] = "Hello, world!";
To do anything else with strings, we must typically call functions. The C library contains a few basic string manipulation functions, and to learn more about strings, we'll be looking at how these functions might be implemented.
Since C never lets us assign entire arrays, we use the strcpy function to copy one string to another:
#include <string.h>
char string1[] = "Hello, world!"; char string2[20];
TOKENS IN C
In a C source program, the basic element recognized by the compiler is the "token." A token is source-program text that the compiler does not break down into component elements.
There are 6 types of Tokens in C which are as follows:-1. Keyword 2. Identifier 3. Constants/Literals 4. Variable 5. Operator 6. Punctuator TYPES OF C VARIABLES
Variable names are names given to locations in the memory. These
locations can contain integer, real or character constants. An integer variable can hold only an integer constant, a real variable can hold only a real
constant and a character variable can hold only a character constant. Rules for Constructing Variable Names
A variable name is any combination of 1 to 31 alphabets, digits or
underscores. Some compilers allow variable names whose length could be up to 247 characters.
• The first character in the variable name must be an alphabet • No commas or blanks are allowed within a variable name.
• No special symbol other than an underscore (as in net_sal) can be used in a variable name.
Ex.: si_int e_hra pod_e_81
C compiler makes it compulsory for the user to declare the type of any variable name that he wishes to use in a program. This type declaration is
done at the beginning of the program. Following are the examples of type declaration statements:
Ex.: int si, e_hra ; float bas_sal ; char code ;
Since, the maximum allowable length of a variable name is 31
characters, an enormous number of variable names can be constructed using the above-mentioned rules. It is a good practice to exploit this
enormous choice in naming variables by using meaningful variable names. C Keywords
C makes use of only 32 keywords or reserved words which combine with the formal syntax to the form the C programming language. Note that all
keywords in C are written in lower case. A keyword may not be used as a variable name. auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while
As a programmer, you will frequently want your program to "remember" a value. For example, if your program requests a value from the user, or if it calculates a value, you will want to remember it somewhere so you can use it later. The way your program remembers things is by using variables. For example:
int b;
This line says, "I want to create a space called b that is able to hold one integer value." A variable has a name (in this case, b) and a type (in this case, int, an integer). You can store a value in b by saying something like:
b = 5;
You can use the value in b by saying something like: printf("%d", b);
In C, there are several standard types for variables: • int - integer (whole number) values
• float - floating point values
• char - single character values (such as "m" or "Z")
A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.
The Programming language C has two main variable types • LOCAL VARIABLES
• GLOBAL VARIABLES
Local Variables
• Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. • When a local variable is defined - it is not initalised by the system, you
must initalise it yourself.
• When execution of the block starts the variable is available, and when the block ends the variable 'dies'.
Check following example's output main()
{ int i=4; int j=10; i++; if (j > 0) {
/* i defined in 'main' can be seen */ printf("i is %d\n",i);
}
if (j > 0) {
/* 'i' is defined and so local to this block */ int i=100;
printf("i is %d\n",i); }/* 'i' (value 100) dies here */
printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/ }
This will generate following output i is 5
i is 100 i is 5
Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1;
You will see -- operator also which is called decremental operator and it
decreases the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1;
Global Variables
Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.
Global variables are initalised automatically by the system when you define them! Data Type Initialser
int 0
char '\0'
float 0
If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.
int i=4; /* Global definition */
main() {
i++; /* Global variable */ func();
printf( "Value of i = %d -- main function\n", i ); }
func() {
int i=10; /* Local definition */ i++; /* Local variable */
printf( "Value of i = %d -- func() function\n", i ); }
This will produce following result Value of i = 11 -- func() function Value of i = 5 -- main function
i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global.
DATA TYPES IN C
A programming language is proposed to help programmer to process certain kinds of data and to provide useful output. The task of data processing is accomplished by executing series of commands called program. A program usually contains different types of data types (integer, float, character etc.) and need to store the values being used in the program. C language is rich of data types. A C programmer has to employ proper data type as per his requirement. C has different data types for different types of data and can be broadly classified as :
1. Primary data types 2. Secondary data types
Primary data types consist following data types. Data Types in C
Integer types:
Integers are whole numbers with a range of values, range of values are machine dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32768 (that is, -215 to +215-1). A signed integer use
one bit for storing sign and rest 15 bits for number.
To control the range of numbers and storage space, C has three classes of integer storage namely short int, int and long int. All three data types have signed and unsigned forms. A short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned integers are always positive and use all the bits for the magnitude of the number. Therefore the range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a longer range of values and it occupies 4 bytes of storage space.
Syntax: int <variable name>; like int num1;
short int num2; long int num3;
Example: 5, 6, 100, 2500.