Module 1
Module 1
UNIT – I
Introduction to Computers:
Computer Systems:
A computer is a system made of two major components: hardware and software. The computer
hardware is the physical equipment. The software is the collection of programs (instructions) that
allow the hardware to do its job.
Computer
System
Hardware Software
Computer Hardware
The hardware component of the computer system consists of five parts: input devices, central
processing unit (CPU) ,primary storage, output devices, and auxiliary storage devices.
The input device is usually a keyboard where programs and data are entered into the computers.
Examples of other input devices include a mouse, a pen or stylus, a touch screen, or an audio
input unit.
The central processing unit (CPU) is responsible for executing instructions such as arithmetic
calculations, comparisons among data, and movement of data inside the system. Today’s
computers may have one ,two, or more CPUs .Primary storage ,also known as main memory, is
a place where the programs and data are stored temporarily during processing. The data in
primary storage are erased when we turn off a personal computer or when we log off from a
time-sharing system.
The output device is usually a monitor or a printer to show output. If the output is shown on the
monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard copy.
Auxiliary storage, also known as secondary storage, is used for both input and output. It is the
place where the programs and data are stored permanently. When we turn off the computer, or
programs and data remain in the secondary storage, ready for the next time we need them.
Computer Software
Computer software is divided in to two broad categories: system software and application
software .System software manages the computer resources .It provides the interface between the
hardware and the users. Application software, on the other hand is directly responsible for
helping users solve their problems.
Software
System Application
software software
System Software:
System software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.
The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this
software is to keep the system operating in an efficient manner while allowing the users access to
the system.
System support software provides system utilities and other operating services. Examples of
system utilities are sort programs and disk format programs. Operating services consists of
programs that provide performance statistics for the operational staff and security monitors to
protect the system and data.
The last system software category ,system development software, includes the language
translators that convert programs into machine language for execution ,debugging tools to ensure
that the programs are error free and computer –assisted software engineering(CASE) systems.
Application software
Application –specific software can be used only for its intended purpose.
A general ledger system used by accountants and a material requirements planning system used
by a manufacturing organization are examples of application-specific software. They can be used
only for the task for which they were designed they cannot be used for other generalized tasks.
The relationship between system and application software is shown in fig-2.In this
figure, each circle represents an interface point .The inner core is hard ware. The user is
represented by the out layer. To work with the system ,the typical user uses some form of
application software. The application software in turn interacts with the operating system ,which
is apart of the system software layer. The system software provides the direct interaction with the
hard ware. The opening at the bottom of the figure is the path followed by the user who interacts
directly with the operating system when necessary.
Computing Environments:
In the early days of computers, there was only one environment: the main frame computer
hidden in a central computing department. With the advent of mini computers and personal
computers, the environment changed, resulting in computers on virtually every desktop.
Time-Sharing Environment
Employees in large companies often work in what is known as a time-sharing environment. In
the times-sharing environment, many users are connected to one or more computers. These
computers may be minicomputers or central mainframes. The terminals they use are often
nonprogrammable, although today we see more and more microcomputers being used to
simulate terminals. Also, in the time-sharing environment, the output devices and auxiliary
storage devices are shared by all of the users.
A typical college lab in which a minicomputer is shared is shared by many students is shown in
figure :
In the time-sharing environment ,all computing must be done by the central computer. The
central computer has many duties: It must control the shared resources; it must manage the
shared data and printing and it must do the computing.
Client/Server Environment
A client/server computing environment splits the computing function between a central
computer and users’ computers. The users are given personal computers or work stations so that
some of the computation responsibility can be moved from the central computer and assigned to
the workstations. In the client-server environment, the users’ micro computers or workstations
are called the client. The central computer, which may be a powerful microcomputer,
minicomputer, or central mainframe system, is known as the server. Because the work is now
shared between the users’ computers and the central computer, response time and monitor
display are faster and the users are more productive.
Distributed Computing
A Distributed Computing environment provides a seamless integration of computing
functions between different servers and clients .The internet provides connectivity to different
servers throughout the world. For example eBay uses several computers to provide its auction
services. This environment provides a reliable, scalable, and highly available network.
Fig: Distributed Computing
Computer Languages:
To write a program for a computer, we must use a computer language. Over the years computer
languages have evolved from machine languages to natural languages.
COMPUTER LANGUAGES
In all over the world, language is the source of communication among human beings. Different
countries/regions have different languages. Similarly, in order to communicate with the
computer user also needs to have a language that should be understood by the computer. For this
purpose, different languages are developed for performing different types of work on the
computer.Basically, languages are divided into two categories according to their interpretation.
Low level computer languages are machine codes or close to it. Computer cannot understand
instructions given in high level languages or in English. It can only understand and execute
instructions given in the form of machine language i.e. language of 0 and 1. There are two types
of low level languages:
Machine Language.
Assembly Language
Machine Language: It is the lowest and most elementary level of Programming language and
was the first type of programming language to be Developed. Machine Language is basically the
only language which computer Can understand. In fact, a manufacturer designs a computer to
obey just one Language, its machine code, which is represented inside the computer by a String
of binary digits (bits) 0 and 1. The symbol 0 stands for the absence of Electric pulse and 1 for the
presence of an electric pulse . Since a computer is Capable of recognizing electric signals,
therefore, it understand machine Language.
Advantages of Machine Language
ii) It requires no translator to translate the code i.e.Directly understood by the computer
inconveniences of machine language. This is another low level but a very important language in
which operation codes and operands are given in the form of alphanumeric symbols instead of
0’s and l’s. These alphanumeric symbols will be known as mnemonic codes and can have
maximum up to 5 letter combination e.g. ADD for addition, SUB for subtraction,
START,LABEL etc. Because of this feature it is also known as ‘Symbolic Programming
Language’. This language is also very difficult and needs a lot of practice to master it because
very small
English support is given to this language. The language mainly helps in compiler orientations.
The instructions of the Assembly language will also be converted to machine codes by language
translator to be executed by the computer.
Many languages have been developed for achieving different variety of tasks, some are fairly
specialized others are quite general purpose.
Examples are
These languages emphasize their capabilities for maintaining data processing procedures
and files handling problems. Examples are:
COBOL (Common Business Oriented Language).
RPG (Report Program Generator
b) String and List Processing: These are used for string manipulation including search for
patterns, inserting and deleting characters. Examples are:
C++
Java
e) Visual programming language: these are designed for building Windows-based applications
Examples are:
Visual Basic
Visual Java
Visual C
Advantages of High Level Language
User-friendly
Similar to English with vocabulary of words and symbols
Therefore it is easier to learn.
They require less time to write.
They are easier to maintain.
Problem oriented rather than 'machine' based.
Program written in a high-level language can be translated into many machine language
and therefore can run on any computer for which there exists an appropriate translator.
It is independent of the machine on which it is used i.e.Programs developed in high level
language can be run on any Computer
Disadvantages of High Level Language
A high-level language has to be translated into the machine language by a translator and
thus a price in computer time is paid.
The object code generated by a translator might be inefficient Compared to an equivalent
assembly language program
ALGORITHM:
An algorithm (pronounced AL-go-rith-um) is a procedure or formula for solving a problem. A
problem in a finite sequence is called an algorithm.
The word ‘Algorithm’ is the name of one Persian author meaning rules of restoration and
reduction. Once the problem is analyzed, its solution is broken into a number of sample steps
Algorithms was developed by an Arab mathematician. It is chalked out step-by-step
approach to solve a given problem. It is represented in an English like language and has some
mathematical symbols like ->, >, <, = etc. To solve a given problem or to write a program you
approach towards solution of the problem in a systematic, disciplined, non-adhoc, step-by-step
way is called Algorithmic approach. Algorithm is a penned strategy(to write) to find a solution.
Properties of an Algorithm
i. Finiteness: An algorithm must always terminate after a finite number of steps.
ii. Definiteness: Each step must be clearly defined that actions carried out must be unambiguous.
iii. Input: Input should be provided at the beginning of algorithm.
iv. Output: Algorithm must produce on or more output.
v. Effectiveness: All the operations defined must be sufficiently basic that they can be done
exactly in finite length of time manually.
iii. Input Statement: Algorithm takes one or more inputs to process. The statements used to
indicate the input is Read a or Input b. This is illustrated in example
Let a , b be the names of the Input
Input a or Read a
Input b or Read b
Where a and b are variable names.
iv. Output Statements: Algorithm produces one or more outputs. The statement used to show
the output is output a or print b.
Syntax: Output variable name
Print variable name
For example output a or print a
output b or print b
where a and b are variable names.
vi. Order in which the steps of an algorithm are executed is divided in to 3 types namely
i) Sequential Order
ii) Conditional Order
iii) Iterative Order
i) Sequential Order
Each step is performed in serial fashion I.e. in a step by step procedure this is illustrated in
example
Task : Write an algorithm to add two numbers.
Step 1 : Start
Step 2 : Read a
Step 3 : Read b
Step 4 : Add a , b
Step 5 : Store in d
Step 6 : Print d
Step 7 : End
a) Syntax :
if (condition)
Then {set of statements S1}
Here condition means Boolean expressions which evacuates to TRUE or FALSE. If condition is
TRUE then the statements S1 is evaluated. If false S1 is not evaluated Programme skips that
section.
This is illustrated in example 1.6
Task : Write an algorithm to check equality of numbers.
Step 1 : Start
Step 2 : Read a, b
Step 3 : if a = b, print numbers are equal to each other
Step 4 : End
Flow Charts
The diagrammatic representation of way to solve the given problem is called flow chart. A flow
chart is a graphical or symbolic representation of a process. Each step in the process is
represented by a different symbol and contains a short description of the process step. The flow
chart symbols are linked together with arrows showing the process flow direction.
Algorithm for large problems becomes complex and there by difficult to write the code.
Problem analysts found ‘Flow charts’ an easier way to solve the problem. Here each step is
represented by a symbol and also contains a short description of the process steps within the
symbol.
Flow charts are linked by arrows. The other names of flow chart are flow diagram, process chart,
and business flow diagram etc., most often it is called by name flow chart only. Flow charts can
be used for following aspects
i. Define and analyze
ii. Build step by step picture of a process
iii. To find the areas of improvement in the process
Advantages
i. Communication – it is better way of communicating the logic of a program solution.
ii. Effect analysis – with the help of flow charts problem can be analyze in a effective way
iii. Effective coding – flow charts acts as a blue print during the system analysis
iv. Proper debugging – flow chart helps in debugging process.
Limitations
i. Alterations and modifications: If alterations are required, the flowchart may require re-drawing
completely.
Types of Flowcharts
Flow charts can be broadly classified in to two types
i) system flow charts
These are used by system analyst to describe the data flow and operation in a data processing
cycle. System flow chart defines the broad processing in organizations showing the origin of data
filing structure,processing to be performed and output to be generated.
ii) Program flow chats
Program flow charts are used by programmers. It is used to describe the sequence of operations
and decisions for a particular problem. Generally to solve any of the programs belonging to
COBOL, C, C++, Java. . etc.,program flow charts are used.
Examples:
Structure chart: A structure chart, also known as hierarchy chart, shows the functional flow
through our program. The structure chart shows how we are going to break our program into
logical steps each step will be a separate module. The structure chart shows the interaction
between all the parts (modules) of our program.
We can use flowchart or pseudo code to complete the design of your program will depend on
experience and difficulty of the program your designing.
Write the program
When we write a program, we start with the top box on the structure chart and work our way to
the bottom. This is known as top-down implementation. We will write the programs by using
structure chart and flowchart or pseudo code.
Test the Program
Program testing can be a very tedious and time- consuming part of program development. As the
programmer we are responsible for completely testing our program. In large-development
projects test engineers are responsible for testing to make sure all the programs work together.
There are 2 types of testing.
1. Black box testing: This is done by the system test engineer and the user. Black box
testing is the programs are tested without knowing what is inside it, with out knowing
how it works. Black box test plans are developed by looking only the requirements
statement. The test engineer uses these requirements to develop test plans.
2. White box testing: This is the responsibility of the programmer. White box testing
assumes that the tester knows everything about the program.
Introduction to c
History of C
“C” is a programming language developed at AT & T Bell Laboratories of USA in 1972. It was
developed Dennis Ritche in late 1970‟s. it began to replace the more familiar languages of that
time like PL/1, ALGOL etc.
“C” became popular because of its reliability, simple and easy to use
It was friendly capable and reliable
ALGOL 60 was developed and did not become popular because it was too general and
too abstract.
They developed “CPU” (Combined Programming Language)
Next as it could not come up to make ALGOL 60 better one they moved to “BCPL”
(Basic Combines Programming Language. Developed by martin Richard Cambridge
university)
At the same time a language called “B” written by ken Thompson at AT & T‟S. Bell
laboaratories as a further simplification of BCPL.
“C” s compactness and coherence is mainly due to it‟s one man language. Ex- LISP,
AASCA
Features of C:
Advantages:
1. Modularity
modularity is one of the important characteristics of C. we can split the C program into no. of
modules instead of repeating the same logic statements (sequentially). It allows reusability of
modules.
Structure of C program
The program written in C language follows this basic structure. The sequence of sections should
be as they are in the basic structure. A C program should have one or more sections but the
sequence of sections is to be followed.
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section
5. Main function section
{
Declaration section
Executable section
}
6. Sub program or function section
1. DOCUMENTATION SECTION : comes first and is used to document the use of logic or
reasons in your program. It can be used to write the program's objective, developer and logic
details. The documentation is done in C language with /* and */ . Whatever is written
between these two are called comments.
2. LINKING SECTION : This section tells the compiler to link the certain occurrences of
keywords or functions in your program to the header files specified in this section.
e.g. #include <stdio.h>
3. DEFINITION SECTION : It is used to declare some constants and assign them some value.
e.g. #define MAX 25
Here #define is a compiler directive which tells the compiler whenever MAX is found in
the program replace it with 25.
4. GLOBAL DECLARATION SECTION : Here the variables which are used through out the
program (including main and other functions) are declared so as to make them global(i.e
accessible to all parts of program)
e.g. int i; (before main())
5. MAIN FUNCTION SECTION : It tells the compiler where to start the execution from
main()
{
point from execution starts
}
6. SUB PROGRAM OR FUNCTION SECTION : This has all the sub programs or the
functions which our program needs.
Example:
//Area of rectangle -comments-Documentation
#include<stdio.h> //header file-linker
#define pi 3.14 //symbolic constants -Definition
float r=3.2; //Global declaration
int main( ) //main section
{
float h,cyl; //declaration
area();// Executable Statement -function call
printf("enter h value\n"); // Executable Statement
scanf("%f",&h); // Executable Statement
cyl=pi*r*r*h; //Executable Statement
printf("volume of cylinder =%f\n",cyl); //Executable Statement
return 0;
}//end of main()
area() // subprogram section
{
float ar; //declaration
ar=pi*r*r; //statements
printf("Area of circle is %f\n",ar);
}//end of sub program section
The software used to write programs is known as a text editor. A text editor helps us enter,
change, and store character data. Depending on the editor on our system, we could use it to write
letters, create reports, or write programs. The main difference between text processing and
program writing is that programs are written using lines of code, while most text processing is
done with character and lines.
Text editor is a generalized word processor, but it is more often a special editor included with the
compiler. Some of the features of the editor are search commands to locate and replace
statements, copy and paste commands to copy or move statements from one part of a program to
another, and formatting commands that allow us to set tabs to align statements.After completing
a program, we save our file to disk. This file will be input to the compiler; it is known as a
source file.
Compiling Programs:
The code in a source file stored on the disk must be translated into machine language ,This is the
job of the compiler. The c compiler is two separate programs. the preprocessor and the
translator.
The preprocessor reads the source code and prepares it for the translator. While
preparing the code ,it scans for special instructions known as preprocessor commands. These
commands tell the preprocessor to look for special code libraries, make substitutions in the code
,and in other ways prepare the code for translation into machine language. The result of
preprocessing is called the translation unit.
After the preprocessor has prepared the code for compilation, the translator does the actual work
of converting the program into machine language. The translator reads the translation unit and
writes the resulting object module to a file that can then be combined with other precompiled
units to form the final program. An object module is the code in machine language. The output
of the compiler is machine language code, but it is not ready to run; that is ,it is not executable
because it does not have the required C and other functions included.
Linking Programs:
A C program is made up of many functions. We write some of these functions, and they are a
part of our source program. There are other functions, such as input/output processes and,
mathematical library functions, that exist elsewhere and must be attached to our program. The
linker assembles all of these functions, ours and systems into our final executable program.
Executing Programs:
Once program has been linked, it is ready for execution. To execute a program we use an
operating system command, such as run, to load the program into primary memory and execute
it. Getting the program into memory is the function of an operating system program known as
the loader. It locates the executable program and reads it into memory. When everything is
loaded, the program takes control and it begins execution.
In a typical program execution, the reads data for processing ,either from the user or from
a file. After the program processes the data, it prepares the output. at output can be to the user’s
monitor or to a file. When the program has finished its job, it tells the operating system ,which
then removes the program from memory.
There are three basic phases that are important when programming in C and using a C compiler.
The phases are called preprocessing,compiling, and linking. When programming in other
languages, only two phases are required: compiling and linking. An C input file is first passed
to a preprocessing program called the preprocessor. The output of the preprocessor is passed to
the true-C compiler. The output of the C compiler is then fed into a linker program. The linker
finally produces an executable form of your program. The following diagram demonstrates a C
program one.c being converted into an executable program.
one.c --> PREPROCESSOR -> tmp.c(temporary) -> COMPILER -> one.obj ->
LINKER -> one.exe (final Executable)
Preprocessing Phase:
A C preprocessor is a program that accepts C code with preprocessing statements and produces a
pure form of C code that contains no preprocessing statements. A preprocessor basically reads
line by line from the input and replicates the line to the output. If the line is a preprocessing
statement, then it performs the preprocessing directives. All preprocessing statements in C begin
with the # symbol and are at the beginning of a line. The operations of taking the input file and
generating the output file, pre-processed file, is called pre-processing.
Input File(ie One.c) ---> Preprocessor --> Output File (ie tmp.c )
The output file is then fed as input into the true C compiler. If there are no preprocessing
directives in the original C input file, then the output file will look identical to the input file. Also
called preprocessor directives, preprocessor statements are special statements that tell the
preprocessor to perform special set of operations.
The main two preprocessor statements are the #define and the #include statements. Preprocessor
statement must be on independent lines. Two preprocessor statements cannot be on the same
line.
The #define preprocessing statement tells the preprocessor to generate a replacement sequence
of characters for a given symbol.
The next example defines four preprocessor symbols. The preprocessor first starts reading the
first line of the input file. As this line is a comment, no output is generated. The next statement is
the first #define statement. This statement tells the preprocessor that, any time in the future that
it reaches a symbol called "Print", it will replace the symbol with the sequence "int printf(...)".
The next define statement directs the preprocessor to equate the symbol "Ret" with the sequence
"return 0". The third define statement equates the symbol "BEGIN" with "{". The final define
statement equates "END" with the "}". The next line beyond the define statements is a blank line.
This is the first generating line of output : a blank line is sent out to the output file.
Input To Preprocessor
#define BEGIN {
#define END }
Print;
int main(void)
BEGIN
END
Output Of Preprocessor:
printf(...);
int main(void)
The next statement that is read is a "Print;". Notice that at this point the preprocessor has already
been told that whenever it reaches a symbol "Print" to generate an output of "printf(...). The final
";" is just copied to the output. So, this statement generates an output of "printf(char *,...);" The
line "int main()" is copied to the output as usual. The next line " BEGIN", produces an out put of
" {", since the preprocessor has been previously told to generate a different sequence of output
when it reaches a symbol "BEGIN". The next statement " printf("Hello World");" is copied to the
output unchanged. The " Ret;" generates the output " return 0;". The final " END" translates to "
}".
The #include preprocessing statement is used to tell the preprocessor to preprocess another file
before continuing on. In the next example Box 2, the first file myfile contains the declaration of
printf. The second file will use the include preprocessor statement to include the contents of the
file myfile in the output. The input C File is passed to the preprocessor. The preprocessor skips
generating output for the first line as it is a comment line. The next line it reads is the
preprocessing directive "#include <MyFile>". The preprocessor stops processing the current
input C file and opens the file "MyFile" to continue processing. Other than opening the file for
new input, the preprocessor does not generate any output. Notice that the next line that is read by
the preprocessor is the comment "//This is the contents of the file". The statement "int printf(char
*,...); is copied to the output without modification. As this is the last line of the file "MyFile", the
preprocessor closes the the file, and resumes preprocessing of the original source C file. The next
line that is read by the preprocessor is the empty line. This is copied to the output as usual. The
preprocessing continues until the rest of the file is sent to the output.
int printf(...);
#include <MyFile>
int main(void)
return 0;
int printf(...)
int main(void)
return 0;
Most programmers tend to forget the exact declaration "int prinf(...);". There are many other
functions other than printf that are part of the standard input/output libraries of C. Again like
printf, they are not part of the C language. All these other functions have to be declared too.
Declaring all the functions that can be used is often too tiring to write every time one writes a C
program. Instead all the declaration for standard input and output is declared in a single file
called stdio.h. The following program, Box #3, uses the #include statement with filestdio.h. The
file is referred to as the standard input and output header file. It is called a header file as most
programmers place the #include statement at the top of their programs. Header files usually
have a file extension of .h.
#include <stdio.h>
int main(void)
return 0;
Compile Phase:
This is the true C compiler. The C compiler accepts a preprocessed output file from the
preprocessor and produces a special file called an object file. This object file contains machine
code generated from the program you wrote in your original C file. It does not as of yet contain
code for functions such as printf. Since the code for printf is not in your code, the object file
contains symbol printf. Usually a special file extension(obj) is given to an object file.
Preprocessor Output File ---> True C-Compiler ---> Object File
Think of an object file as a partially complete program with missing blocks of code(ie the code
for printf). During the next phase called the Link Phase, it is the linker program that is
responsible to find the missing code "printf" and link it(bind it) to the object file generated by the
compiler.The compiler also removes all comments from the input file.
Link Phase:
The link phase is implemented by the linker. The linker is a process that accepts as input object
files and libraries to produce the final executable program. Libraries contain object code. This
object code in turn contains functions. In the link phase the object code from the compile phase
is bound to the missing function code such as printf. The function printf is located in the standard
input and output libraries. The final executable now contains all the necessary code for
execution.
Compilation(syntax ) errors:
These are raised when we compile the program and can be located and corrected easily. Most
common compilation or syntax errors are.
Undefined variable
Redeclaration of variable
Unterminated string character
Missing semicolon ;
Function call missing ( ,;”)
Function should have prototype.
Compiler errors are generated whenever either the syntax of the C language is not met or
undefined symbols are met in the code. The next program in Box #5 has three errors which are
explained with comments.
#include <stdio.h>
int main(void)
Linker errors:
Linker Errors are generated when linker finds missing symbol references in the object code
generated by the compiler. As an example, if the standard input/output library is missing and the
object code contains a reference to the printf function, the linker will generate an error stating
"Unresolved external reference to _printf".
In the next program in Box #6, a missing _main symbol error is generated. As all programs
must have a main definition ( a body for the main code) to execute. It is the linker that notices
that the main function is missing.
#include <stdio.h>
printf("Hello World\n");
return 0;
The next class of errors are called logical-errors. These errors are errors in the design of the
program. The next program(Box #7) is supposed to print out hello world, but the programmer
miswrote the program.
The program must be linked to the ‘C’ library. If it fails in such case these errors are raised .
most common errors are:
Unable to link cos.obj
Undefined symbol
It is very important to know the different phases as many errors are directly related to them. The
errors generated can be preprocessing errors, compiler errors, linker errors, logical errors, and
run-time errors.
#include <stdio.h>
int main(void)
printf("Hello ");
printf("World\n");
return 0;
The last class of errors are those programs that execute and fail. These are called run-time
errors. The next program(Box #8) will generate a divide by zero error during execution of the
program.
#include <stdio.h>
int main(void)
printf("Hello World\n");
Preprocessing errors:
A common preprocessor error is not finding the include file in the include statement. Either the
filename is spelled wrong or the preprocessor has the wrong directory to search for that file.
Sometimes a #define statement might subtly lead to an compiler error as in the following(Box
#4). The programmer defines the symbol "PRINT" for the sequence of characters "printf // This
is a comment". In the body of the main function, the "PRINT("Hello World");" is replaced with
"printf // this is a comment ("Hello World");". Since everything after the "//" is considered a
comment. The output that is generated for that line by the preprocessor is "printf // ...". The
preprocessed file is then sent to the compiler, which then generates a compile time error of
"Error: Unexpected return after function call printf"!
int printf(...);
int main(void)
PRINT("Hello World");
return 0;
Output of Preprocessor
int printf(...);
int main(void)
return 0;
Identifier:
In C programming, identifiers are names given to C entities, such as variables, functions,
structures etc. Identifier are created to give unique name to C entities to identify it
during the execution of program.
Here, sum is a identifier which denotes a variable of type integer. Similarly, sec_num is
another identifier, which denotes another variable of type integer.
Rules for writing identifier
An identifier can be composed of letters (both uppercase and lowercase letters),
digits and underscore '_' only.
The first letter of identifier should be either a letter or an underscore. But, it is
discouraged to start an identifier name with an underscore though it is legal. It is
because, identifier that starts with underscore can conflict with system names.
In such cases, compiler will complain about it. Some system names that start with
underscore are _fileno, _iob, _wfopen etc.
There is no rule for the length of an identifier. However, the first 31 characters of an
identifier are discriminated by the compiler. So, the first 31 letters of two identifiers
in a program should be different.
Data Types in C
Data type in C defines the amount of storage allocated to variables ,the values that they can
accept ,and the operation that can be performed on those variables.
C is rich in data types. The verity of data type allow the programmer to select appropriate data
type to satisfy the need of application as well as the needs of different machine.
Variable:
A variable is a name for a location in memory used to store a data value.
We use variables to save and restore values or the results of calculations.
The programmer has to tell Java what type of data will be store in the variable’s memory
location. Its type cannot change.
During the program execution the data saved in the memory location can change; hence the
term “variable”.
#include<stdio.h>
void test();
int main()
{
int m = 22, n = 44;
// m, n are local variables of main function
/*m and n variables are having scope within this main function only.
These are not visible to test funtion.*/
/* If you try to access a and b in this function, you will get 'a' undeclared and 'b' undeclared
error */
printf("\nvalues : m = %d and n = %d", m, n);
test();
}
void test()
{
int a = 50, b = 80;
// a, b are local variables of test function
/*a and b variables are having scope within this test function only.These are not visible to
main function.*/
/* If you try to access m and n in this function, you will get 'm' undeclared and 'n' undeclared
error */
printf("\nvalues : a = %d and b = %d", a, b);
}
Output:
values : m = 22 and n = 44
values : a = 50 and b = 80
The scope of global variables will be throughout the program. These variables can be
accessed from anywhere in the program.
This variable is defined outside the main function. So that, this variable is visible to main
function and all other sub functions.
#include<stdio.h>
void test();
int m = 22, n = 44;
int a = 50, b = 80;
int main()
{
printf("All variables are accessed from main function");
printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);
test();
}
void test()
{
printf("\n\nAll variables are accessed from" \ " test function");
printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);
}
Output:
All variables are accessed from main function
values : m = 22 : n = 44 : a = 50 : b = 80
All variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80
Constants
C Constants are also like normal variables. But, only difference is, their values can not be
modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of C constants:
1. Integer Constants in C:
An integer constant must have at least one digit.
It must not have a decimal point.
It can either be positive or negative.
No commas or blanks are allowed within an integer constant.
If no sign precedes an integer constant, it is assumed to be positive.
The allowable range for integer constants is -32768 to 32767.
2. Real constants in C:
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to be positive.
No commas or blanks are allowed within a real constant.
Keywords
Key words or Reserve words of the C language are the words whose meaning is already
defined and explained to the C language compiler. Therefore Reserve words can not be used
as identifiers or variable names. They should only be used to carry the pre-defined meaning.
For example int is a reserve word.
It indicates the data type of the variable as integer. Therefore it is reserved to carry
the specific meaning.
keywords are also called ‘Reserved words’.
Keywords are the words whose meaning has already been explained to the C compiler and
their meanings cannot be changed.
Keywords serve as basic building blocks for program statements.
Keywords can be used only for their intended purpose.
Keywords cannot be used as user-defined variables.
All keywords must be written in lowercase
Any attempt to use it other than the intended purpose will generate a compile time error.
C language has 32 keywords. Following are some of them
Identifier keyword
Identifiers are names that are given to various C take some reserved word called keyword,
program elements, such as variable, function they have predefine meaning in C.
and arrays.
Identifiers consist of letters and digits. Keyword consist only letter.
Identifier’s first character must be a letter. Keyword’s all character is letter.
Identifiers Upper and lowercase letter is use. Keywords are all lowercase.
Upper and lowercase are not equivalent. Upper and lowercase are also not equivalent.
Like: X, sum_5, _weather etc. Like: auto, short, long etc.
But 4th is not identifier cause identifier first
character must a letter.
Operators in c:
C has a large number of built in operators. An operator is a symbol which acts on operands to
produce certain result as output. The data items on which operators act upon are called
‘operands’ For example in the expression a+b; + is an operator, a and b are operands. The
operators are fundamental to any mathematical computations.
Based on the number of operands the operator acts upon, Operators can be classified as follows:
Unary operators: acts on a single operand.
For example: unary minus(-5, -20, etc), address of operator (&a)
Binary operators: acts on two operands. Ex: +, -, %, /, *, etc
Ternary operator: acts on three operands. The symbol ?: is called ternary operator in C
language.
Usage: big= a>b?a:b; i.e if a>b,then big=a else big=b.
Based on the functions, operators can be classified as given below in the
1. Arithmetic Operators:
These operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus.
1 + Addition
2 - Subtraction
3 * multiplication
4 / Division
5 % Modulus
# include <stdio.h>
int main()
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
Output:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
2. Assignment operators:
The values for the variables are assigned using assignment operators. For example, if the value
10 is to be assigned for the variable sum, it can be done like below.
sum = 10;
Below are some of other assignment operators:
Operator Example Explanation
1 # include <stdio.h>
2 int main()
3 {
4 int Total=0,i;
5 for(i=0;i<10;i++)
6 {
8 }
10 }
Output:
Total = 45
3. Relational operators:
These operators are used to find the relation between two variables. That is, used to
compare the value of two variables.
1 #include <stdio.h>
2 int main()
3 {
4 int m=40,n=20;
5 if (m == n) {
7 }
8 else {
10 }
11 }
Output:
4. Logical operators:
These operators are used to perform logical operations on the given two variables.
Meaning of
Operator Operator Example
Logical
! NOT If c=5 then, !(c==5) returns false.
1 #include <stdio.h>
2 int main()
3{
4 int m=40,n=20;
7 }
8}
Output:
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Binary Left Shift Operator. The left operands value is moved left by the A << 2 will give 240 which is 1111
<<
number of bits specified by the right operand. 0000
Binary Right Shift Operator. The left operands value is moved right by the A >> 2 will give 15 which is 0000
>>
number of bits specified by the right operand. 1111
#include <stdio.h>
main()
{
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
6. Conditional operators:
Conditional operators return one value if condition is true and returns other value is condition
is false.
This operator is also called as ternary operator.
Here, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
1 #include <stdio.h>
2 int main()
3{
4 int x=1, y ;
5 y = ( x ==1 ? 2 : 0 ) ;
8}
Output:
x value is 1
y value is 2
These operators are used to either increase or decrease the value of the variable by one.
var_name++; (or)
– - var_name; (or)
var_name- -;
2 #include <stdio.h>
3 int main()
4 {
5 int i=1;
6 while(i<10)
7 {
8 printf("%d\n",i);
9 i++;
10 }
11 }
Output:
1
2
3
4
5
6
7
8
9
2. #include <stdio.h>
3. int main()
4. {
5. int i=20;
6. while(i>10)
7. {
a. printf("%d\n",i);
b. i--;
8. }
9. }
Output:
20
19
18
17
16
15
14
13
12
11
8. Special Operators:
Do you know difference between pre/post increment and pre/post decrement operators?
Below table will explain you how these operators to be used in a C program.
while(- - i <
4 The value of i is decremented by 1, before comparing with 5.
5)
3 #include <stdio.h>
4 int main()
5 {
6 int i=0;
7 while(++i < 5 )
8 {
9 printf("%d\n",i);
10 }
11 return 0;
12 }
Output:
1
2
3
4
1 #include <stdio.h>
2 int main()
3 {
4 int i=0;
5 while(i++ < 5 )
6 {
7 printf("%d\n",i);
8 }
9 return 0;
10 }
Output:
1
2
3
4
5
1 #include <stdio.h>
2 int main()
3 {
4 int i=10;
5 while(--i > 5 )
6 {
7 printf("%d\n",i);
8 }
9 return 0;
10 }
Output:
9
8
7
6
1 #include <stdio.h>
2 int main()
3 {
4 int i=10;
5 while(i-- > 5 )
6 {
7 printf("%d\n",i);
8 }
9 return 0;
10 }
Output:
9
8
7
6
5
EXPRESSIONS :
An expression is a sequence of operands and operators that reduces to a single value. Expression
can be simple or complex. An operator is a syntactical token that requires an action be taken.
An operand is an object on which an operation is performed.
A simple expression contains only one operator.E.g: 2 + 3 is a simple expression whose
value is 5.A complex expression contains more that one operator. E.g: 2 + 3 * 2.
To evaluate a complex expression we reduce it to a series of simple expressions. In this first we
will evaluate the simple expression 3 * 2 (6)and then the expression 2 + 6,giving a result of 8.
The order in which the operators in a complex expression are evaluated is determined by
a set of priorities known as precedence, the higher the precedence ,the earlier the expression
containing the operator is evaluated. If two operators with the same precedence occur in a
complex expression ,another attribute of an operator ,its associativety ,takes
control.Associativity is the parsing direction used to evaluate the expression. It can be either left-
to-right or right-to-left .When two operators with the same precedence occur in an expression
and their associativity is left-to-right ,the left operator is evaluated first. For example ,in the
expression 3*4/6 ,there are two operators multiplication and division ,with the same precedence
and left-to-right associativity .Therefore the multiplication is evaluated before the division .
ARITHMETIC EXPRESSIONS :
It is a combination of variables, constants and operators arranged according to the syntax of C
language.
Some examples - A * B – C ,(M + N) * (X + Y)
Evaluation of expressions : Expressions are evaluated using an assignment statement of the form
Variable = expression
Eg x = x*y + z-3 *(z *y)
TYPE CONVERSION:
In an expression that involves two different data types ,such as multiplying an integer and a
floating point number to perform these evaluations ,one of the types must be converted.
We have two types of conversions
•If the operands are of different types the lower type is automatically converted to the higher
type before the operation proceeds. The result is of higher type.
Conversion rules
If one operand is long double, the other will be converted to long double and result will be
long double.
If one operand is double, the other will be converted to double and result will be double.
If one operand is float, the other will be converted to float and result will be float.
If one of the operand is unsigned long int, the other will be converted into unsigned long int
and result will be unsigned long int.
If one of the operand is long int, the other will be converted to long intand the result will be
long int.
If one operand is unsigned intthe other will be converted to unsigned intand the result will be
unsigned int.
Many times there may arise a situation where we want to force a type conversion in a way that is
different from automatic conversion.
Consider for example the calculation of number of female and male students in a class
Ratio = female_students /male_students
Since if female_students and male_students are declared as integers, the decimal part will be
rounded off and its ratio will represent a wrong figure.This problem can be solved by converting
locally one of the variables to the floating point as shown below.
Ratio = (float) female_students/ male_students
The operator float converts the female_studentsto floating point for the purpose of evaluation of
the expression.Then using the rule of automatic conversion, the division is performed by floating
point mode, thus retaining the fractional part of the result.
If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the result of the
evaluation becomes the result of the operation. If the condition is FALSE (zero), then
expression2 is evaluated and its result becomes the result of the operation. An example will help,
s = ( x < 0 ) ? -1 : x * x;
Formatted I / O Functions
Formatted I / O means reading and writing data in formats which are desired by the user. The
function used to input action is scanf() and output action is printf().
Format specifiers
For example %d, will pad a number with ‘zeros’ if numbers is less than five digits. So that
the total length is 5. %d will pad a number with ‘apace’. If number is less than five digits. So
that the total length is five.
The following example demonstrates the working of minimum field width specifier.
Double count;
Count = 10.51324; // here total digits are 8, includes dot ( . )
operators.
printf (“ %f” , count);
printf (“ %10f” , count);
printf (“ %010f” , count);
Output
10.51324
10.51324 // inserts 2 blank spaces. So that total length = 10
digits
0010.51324 // inserts 2 zeros. So that total length = 10 digits
176.012543871
00005214
This is C language book
Unformatted I / O Function
A simple reading of data from keyboard and writing to I / O device,without any format is called
unformatted I / O functions. This is classified as string I / O and character I /O.
Character Input/Output(I/O)
In order to read and output a single character character I / O functions
are used. The functions under character I / O are
(I) getchar()
(II) putchar()
(III) getch()
(IV) getche()
Alternatives to getchar()
The two common alternative functions to getchar() are
getch()
getche()
The getch() function reads a single character at a time and it waits for key press. It does not echo
the character on the screen. The getche() is
same as getch()/ but the key is echoed. This is illustrated below.
char ch;
Ch = getch() // let key press = k
putchar(ch);
Output
String I / O
In order to read and write string of characters the functions gets() and puts() are used gets()
function reads the string and puts() function takes the string as argument and writes on the
screen. This is illustrated below char name [50]
puts (“Enter your name”);
gets (name);
puts(“ The name entered is “)
Output:
Enter your name: Fredric /* string as entered by user*/
The name entered is: Fredric
Note: Char name (50) is character array declaration.
A statement causes an action to be performed by the program. It translates directly into one or
more executable computer instructions. You may have noticed that we have used a
semicolon at the end of the statements in our programs. Most statements need a semicolon at
the end; some do not
STATEMENT TYPES:
2.EXPRESSION STATEMENT :
An expression is turned in to a statement by placing a semicolon(;)after it.
expression; //expression statement
Eg: a=2;
3.RETURN STATEMENT :
A return statement terminates a function. All functions ,including main, must have a return
statement. Where there is no return statement at the end of the function ,the system inserts one
with a void return value.
return expression; //return statement
The return statement can return a value to the calling function. In case of main ,it returns a value
to the operating system rather than to another function. A return value of zero tells the operating
system that the program executed successfully.
4.COMPOUND STATEMENTS:
A compound statement is a unit of code consisting of zero or more statements .It is also known
as a block. The compound statement allows a group of statements to become one single entity.