Imperative Programming 1
Imperative Programming 1
Dear Students
The imperative (or procedural) paradigm is the closest to the structure of actual computers.
It is a model that is based on moving bits around and changing machine state
Imperative programming is a programming paradigm that uses statements that change a program‘s
state from compilation to running.
In imperative language natural languages can be used to express commands for the computer to
perform. Imperative programming focuses on describing how a program operates.
In contrast to it, Declarative programming, which focuses on what the program should accomplish
without specifying how the program should achieve the result.
The basic unit of abstraction is the PROCEDURE, whose basic structure is a sequence of
statements that are executed in succession, abstracting the way that the program counter is
incremented, so as to proceed through a series of machine instructions residing in sequential
hardware memory cells.
Variables play a key role, and serve as abstractions of hardware memory cells. Typically, a
given variable may assume many different values of the course of the execution of a program,
just as a hardware memory cell may contain many different values. Thus, the assignment
statement is a very important and frequently used statement.
The sequential flow of execution can be modified by conditional and looping statements (as
well as by the very low-level goto statement found in many imperative languages), which
abstract the conditional and unconditional branch instructions found in the underlying
machine instruction set.
Machine and Assembly Languages are native languages of a computer for hardware
implementation it is designed and written in imperative style to execute in native code.
Procedural Programming is a type of imperative programming in which the program is built
from one or more procedures (also termed subroutines or functions). Procedural programming
couldbe considered a step towards declarative programming. A programmer can often tell, simply
bylooking at the names, arguments, and return types of procedures (and related comments), what
aparticular procedure is supposed to do, without necessarily looking at the details of how it achieves
itsresult. At the same time, a complete program is still imperative since it fixes the statements to
beexecuted and their order of execution to a large extent.
Structured Programming is a programming with a specific structure of the program and
modular programming is added with structured language to add different functions. These are high
level imperative languages with assignment statements, calculative statements, evaluation
statementsto execute complex expressions which may have arithmetic, relational & logical operators
andfunction evaluations, and the assignment of the resulting value to memory. Looping statements
likewhile, do while, for loop, etc. used to execute sequence, conditional branching, switch case
statementsand looping statements and subroutine or procedure call.Imperative languages are like
Fortran, BASIC, Pascal, COBOL, ALGOL language formathematical algorithms and C language,
Object Oriented Programming are imperative in style, but added features to support objects.
C++ , JAVA, Perl, Rubey, visual c++ are object oriented languages & Python languages
Event Driven Programming languages are imperative style with object based events handlers
Like Visual Basic & PHP with Web designating languages.
Object Based Languages are programming languages with imperative style by introducing
pure object oriented concepts and object based concepts by introducing VB.Net & C#, J# & F#
functional languages.
C is the Mother of all imperative types of programming languages, since from c language
BASIClanguage is invented and from BASIC language Visual Basic & VB.Net languages are
invented. FromC language C++, VC++, C#, J#, JAVA languages are invented.
Hence In this Book we are Considering C as a imperative Language & all examples are
coveredconsidering C language only.
2. Assembly language
Machine Language:
Every computer has its own language called machine language. Itdepends on the specific
Hardware of the computer. A machine language is also known as low levellanguage also
called machine understandable language.Computer understands & executes the program only
in machine level language. This low levellanguage is in the form of (1‘s and 0‘s) binary
codeLow Level Language requires memorizing or looking up numerical codes for every
instructionthat is used.These are machine dependent languages.These are used for simulation
languages, and LISP, artificial intelligence applications.
Assembly Language:
Assembly language is the mnemonic language written in some specificsymbolic codes, such
as ADD, SUB etc. An assembly language program is first translated intomachine language
instruction by system program called assembler, before it can be executed. Theseare
languages understandable by CPU & ALU section of Computer Assembly languages are
calledlow level languages.
High Level Language:
A High level language is a simple English like language. A High levellay program also needs
to be transferred into machine language instructions before it can be executedbecause
computer understands only machine level language.Rules for programming in a particular
high-level language are much the same for all computers,so that a program written for one
computer can generally be run on many different computers withlittle or no alteration.This
translation, called compilation is done by a systems program called a compiler.The original
program written in High level language is called source program and its translationi.e.,
machine code is called object program.Some popular High Level languages are Basic,
Fortran, Cobol, Pascal, C & C++.High-level language offers three significant advantages over
machine language: simplicity,uniformity and portability (i.e., machine
independence).Compilers and InterpretersA program written in a high level language must be
translated into machine language before itcan be executed. This is known as compilation or
interpretation, depending on how it is carried out.
Compilers translate the entire program into machine language before executing any of the instructions.
Interpreters, on the other hand, proceed through a program by translating and then executing single
instructions, or small groups of instructions. A compiler or interpreter is itself a computer program that
accepts a high-level program (e.g. a C program) as input data, and generates a corresponding machine –
language program as output. The original high-level program is called the source program, and the
resulting machine-language program is called the object program. Every high-level language must have its
own compiler or interpreter for a particular platform. It is generally more convenient to develop a new
program using an interpreter rather than a compiler. Once an error-free program has been developed, a
compiled version will normally be executed much faster than an interpreted version. Difference between
compiler and interpreter
Let's see the programming languages that were developed before C language.
C language has evolved from three different structured language ALGOL, BCPL and B Language. It uses
many concepts from these languages and has introduced many new concepts such as data types, struct,
pointer. In 1988, the language was formalized by American National Standard Institute (ANSI). In 1990, a
version of C language was approved by the International Standard Organization (ISO) and that version of
C is also referred to as C89.
Features of C Language
C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem into
parts), the rich set of library functions, data types, etc.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions and
hence the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the pointers.
We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for every function.
Recursion enables us to use the approach of backtracking.
10) Extensible
C language is extensible because it can easily adopt new features.
Applications of C Programming
C was initially used for system development work, particularly the programs that make-up
the operating system. C was adopted as a system development language because it produces
code that runs nearly as fast as the code written in assembly language. Some examples of the
use of C are -
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
First C Program
Before starting the abcd of C language, you need to learn how to write, compile and run the first c
program.
To write the first c program, open the C console and write the following code:
1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
#include <stdio.h> includes the standard input output library functions. The printf() function is
defined in stdio.h .
int main() The main() function is the entry point of every program in c language.
return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for successful
execution and 1 for unsuccessful execution.
By menu
Now click on the compile menu then compile sub menu to compile the c program.
Then click on the run menu then run sub menu to run the c program.
By shortcut
Or, press ctrl+f9 keys compile and run the program directly.
4. Use software (a compiler or interpreter) to translate the program into machine language.
end users.
Examples of end users include payroll management system, they needs a printed list of all employees,
a Billing department that wants a list of clients who are 30 or more days overdue on their payments,
they need their deduction information. Since programmers are providing a service to these users,
programmers must first understand what the users want. When a program runs, you usually think of
the logic as a cycle of input processing-output operations, but when you plan a program, you think of
the output first. After you understand what the desired result is, you can plan the input and processing
steps to achieve it.
Suppose the manager needs a list of all employees who have been here over five years, because we
want to invite them to a special thank-you dinner. On the surface, this seems like a simple request. An
experienced programmer, however, will know that the request is incomplete. For example, you might
not know the answers to the following questions about which employees to include: Does the manager
want a list of full-time employees only, or a list of full and part-time employees together?
Does she want to include people who have worked for the company on a month-to month contractual
basis over the past five years, or only regular, permanent employees?
Do the listed employees need to have worked for the organization for five years as of today, as of the
date of the dinner, or as of some other cutoff date?
What about an employee who worked three years, took a two-year leave of absence, and has been
back for three years?
The programmer cannot make any of these decisions; the user must address these questions to
manager.
For example, no one knew they wanted to play Angry Birds or leave messages on Facebook before
those applications were developed. Mobile app developers also must consider a wider variety of user
skills than programmers who develop applications that are used internally in a corporation. Mobile
app developers must make sure their programs work with a range of screen sizes and hardware
specifications because software competition is intense and the hardware changes quickly.
The main important part of the program is planning the program‘s logic. During this phase of the
process, the programmer plans the steps of the program, deciding what steps to include. You can plan
the solution to a problem in many ways. The two most common planning tools used are flowcharts
and pseudocode. You may hear programmers refer to planning a program as ―developing an
algorithm.‖ An algorithm is the sequence of steps or rules you follow to solve a problem.
The programmer shouldn‘t worry about the syntax of any particular language during the planning
stage, but should focus on figuring out what sequence of events will lead from the available input to
the desired output. Planning the logic includes thinking carefully about all the possible data values a
program might encounter and how you want the program to handle each scenario. The process of
walking through a program‘s logic on paper before you actually write the program is called desk-
checking.
After the logic is developed, only then can the programmer write the source code for a Program in a
respective programming language. The logic developed to solve a programming problem can be
executed using any number of languages. Only after choosing a language must the programmer be
concerned with correct syntax.
Languages like Java or Visual Basic are available for programmers because someone has written a
translator program (a compiler or interpreter) that changes the programmer‘s English-like high-level
programming language into the low-level machine language that the computer understands.
When you learn the syntax of a programming language, the commands work on any machine on
which the language software has been installed. However, your commands then are translated to
machine language, which differs in various computer makes and models.
If you write a programming statement incorrectly the translator program doesn‘t know how to proceed
and issues an error message identifying a syntax error.
Typically, a programmer develops logic, writes the code, and compiles the program, receiving a list of
syntax errors. The programmer then corrects the syntax errors and compiles the program
again.Correcting the first set of errors frequently reveals new errors that originally were not apparent
to thecompiler.
A program that is free of syntax errors is not necessarily free of logical errors. A logical error results
when you use a syntactically correct statement but use the wrong one for the current context.
Input myNumber
setmyAnswer = myNumber * 2
outputmyAnswer
If you execute the program, provide the value 2 as input to the program, and the answer 4 is
displayed, you have executed one successful test run of the program. Testing of logical errors,
syntactically errors are done.
6. Putting the Program into Production
Once the program is thoroughly tested and debugged, it is ready for the organization to use. Putting
the program into production might mean simply running the program once, if it was written to satisfy
a user‘s request for a special list then we can finalize the program.
After programs is completed making necessary changes is called maintenance. Maintenance can be
required for many reasons: for example, because new tax rates are legislated, the format of an input
file is altered, or the end user requires additional information not included in the original output
specifications. you make changes to existing programs, you repeat the development cycle. That is,
you must understand the changes, then plan, code, translate, and test them before putting them into
production.
Writing Pseudocode
You have already seen examples of statements that represent pseudo code earlier in this chapter, and
there is nothing mysterious about them. The following five statements constitute a pseudocode
representation of a number-doubling problem:
start
inputmyNumber
setmyAnswer = myNumber * 2
outputmyAnswer
stop
Using pseudocode involves writing down all the steps you will use in a program. Usually,
programmers preface their pseudocode with a beginning statement like start and end it with a
terminating statement like stop. The statements between start and stop look like English and are
indented slightly so that start and stop stand out. Most programmers do not bother with punctuation
such as period sat the end of pseudocode statements, although it would not be wrong to use them if
you prefer that style. Similarly, there is no need to capitalize the first word in a sentence, although you
might choose to do so. This book follows the conventions of using lowercase letters for verbs that
begin pseudocode statements and omitting periods at the end of statements. Pseudocode is fairly
flexible because it is a planning tool, and not the final product. Therefore, for example, you might
prefer any of the following:
• Instead of start and stop, some pseudocode developers would use the terms begin and end.
• Instead of writing input myNumber, some developers would write getmyNumber or read
myNumber.
• Instead of writing set myAnswer = myNumber * 2, some developers would write calculate
myAnswer = myNumber times 2 or computemyAnswer as myNumber doubled.
• Instead of writing output myAnswer, many pseudocode developers would write display myAnswer,
print myAnswer, or write myAnswer.
The point is, the pseudocode statements are instructions to retrieve an original number from an input
device and store it in memory where it can be used in a calculation, and then to get the calculated
answer from memory and send it to an output device so a person can see it. When you eventually
convert your pseudocode to a specific programming language, you do not have such flexibility
because specific syntax will be required. For example, if you use the C# programming language and
write the statement to output the answer, you will code the following: Console. Write (myAnswer);
The exact use of words, capitalization, and punctuation are important in the C# statement, but not in
the pseudocode statement.
Algorithms
1. A sequential solution of any program that written in human language, called algorithm.
2. Algorithm is first step of the solution process, after the analysis of problem, programmer write the
algorithm of that problem.
3. Example of Algorithms:
Ans.
step 1 : start
else
print "number odd"
endif
step 5 : stop
Flowchart
Defination : - Graphical representation of any program is called flowchart.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Used at the beginning and end of the algorithm to show start and end
Start/Stop
of the program.
Example Flowcharts
Here is the flowchart for going to the market to purchase a pen.
The logic in the flowchart for doubling numbers, shown in Fig. 1.8, has a major flaw—the program
contains an infinite loop.
If, for example, the input numbers are being entered at the keyboard, the program will keep accepting
numbers and outputting their doubled values forever. Of course, the user could refuse to type any
more numbers. But the program cannot progress any further while it is waiting for input; meanwhile,
the program is occupying computer memory and tying up operating system resources.
Any infinite loop in a program has a problem that you can input values infinite time , processing will
be done, result will be displayed. Loop will be continued infinite times. Solution to stop is turn off
your computer, Solution is to somewhere Refuse input value or stop accepting input value.
A better way to end the program is to set a predetermined value for myNumber that means ―Stop the
program!‖ For example, the programmer and the user could agree that the user will never need to
know the double of 0 (zero), so the user could enter a 0 to stop. The program could then test any
incoming value contained in myNumber and, if it is a 0, stop the program.
You represent a decision in a flowchart by drawing a decision symbol, which is shaped like a
diamond. The diamond usually contains a question, the answer to which is one of two mutually
exclusive options—often yes or no.
The question to stop the doubling program should be ―Is the value of myNumber just entered equal to
0?‖ or ―myNumber = 0?‖ for short. The complete flowchart will now look like the one shown in Fig.
One drawback to using 0 to stop a program, of course, is that it won‘t work if the user does need to
find the double of 0. In that case, some other data-entry value that the user never will need, such as
999 or –1, could be selected to signal that the program should end.
A preselected value that stops the execution of a program is often called a dummy value because it
does not represent real data, but just a signal to stop. Sometimes, such a value is called a sentinel
value because it represents an entry or exit point, like a sentinel who guards a fortress.
For one thing, an input record might have hundreds of fields, and if you store a dummy record in
every file, you are wasting a large quantity of storage on ―non data.‖ Additionally, it is often difficult
to choose sentinel values for fields in a company‘s data files.
Any balance Due, even a zero or negative number, can be a legitimate value, and any
customerName, even ―ZZ‖, could be someone‘s name. Fortunately, programming languages can
recognize the end of data in a file automatically, through a code that is stored at the end of the data.
Many programming languages use the term eof (for end of file) to refer to this marker that
automatically acts as a sentinel.
Here In this example, therefore, uses eof to indicate the end of data whenever using a dummy value is
impractical or inconvenient. In the flowchart shown in Fig. 1.10, the eof question is shaded.
EXERCISE:
A text editor is a program that you use to create simple text files. It is similar to a word processor, but
without as many features.
You can use a text editor such as Notepad that is included with Microsoft Windows. The C
Developing Environment is a screen display with windows and pull-down menus. The program
listing, error messages and other information are displayed in separate windows.
The menus may be used to invoke all the operations necessary to develop the program, including
editing, compiling, linking, and debugging and program execution.
If the menu bar is inactive, it may be invoked by pressing the [F10] function key. To select different
menu, move the highlight left or right with cursor (arrow) keys. You can also revoke the selection by
pressing the key combination for the specific menu.
Invoking the Turbo C IDE
The default directory of Turbo C compiler is c:\tc\bin. So to invoke the IDE from the windows you
need to double click the TC icon in the directory c:\tc\bin.
The alternate approach is that we can make a shortcut of tc.exe on the desktop. Opening New Window
in Turbo C
To type a program, you need to open an Edit Window. For this, open file menu and click ―new‖.
A window will appear on the screen where the program may be typed.
When the Edit window is active, the program may be typed. Use the certain key combinations to
perform specific edit functions.
To save the program, select save command from the file menu. This function can also be performed
by pressing the [F2] button. A dialog box will appear asking for the path and name of the file. Provide
an appropriate and unique file name. You can save the program after compiling too but saving it
before compilation is more appropriate
Making an Executable File in Turbo C
The source file is required to be turned into an executable file. This is called ―Making‖ of the .exe file.
The steps required to create an executable file are:
2. Compile the source code into a file with the .obj extension.
3. Link your .obj file with any needed libraries to produce an executable program
All the above steps can be done by using Run option from the menu bar or using key combination
In the Turbo C IDE, compiling and linking can be performed together in one step. There are two ways
to do this: you can select Make EXE from the compile menu, or you can press the [F9] key
If the compiler recognizes some error, it will let you know through the Compiler window. You‘ll see
that the number of errors is not listed as 0, and the word ―Error‖ appears instead of the word
―Success‖ at the bottom of the window. The errors are to be removed by returning to the edit window.
Usually these errors are a result of a typing mistake. The compiler will not only tell you what you did
wrong, they‘ll point you to the exact place in your code where you made the mistake.
If the program is compiled and linked without errors, the program is executed by selecting Run from
the Run Menu or by pressing the [Ctrl+F9] key combination.
Exiting Turbo C IDE An Edit window may be closed in a number of different ways. You can click on
the small square in the upper left corner, you can select close from the window menu, or you can press
the Alt+F3 combination. To exit from the IDE, select Exit from the File Menu or press Alt+X
Combination.
1, 0
Machine Language
Assembly Language
Procedure-oriented Language
Software technology has a growth of a tree. Software evolution has a layer of growth. Each layer
representing an improvement over the previous one.
The oldest programming languages required programmers to work with memory addresses and to
memorize awkward codes associated with machine languages.
Newer programming languages look much more like natural language and are easier to use, partly
because they allow programmers to name variables instead of using unwieldy memory addresses
Initially the programs are to be written in machine language but it is in the form of 0‘s and First hence
difficult to remember.
Second layer of assembly language which has Mnemonics in the form of English language. Language
used by ALU section of the CPU.
Third layer is procedure oriented language (POP) language. In this a problem is viewed as a sequence
of Instructions. All functions or tasks are combined in one procedure program.
In the fourth layer the program is divided into functions. Instructions of the program is divided into
groups known as functions.
In multi function program, many important data items are placed as global so that they may be
accessed by all the functions. Each function may have its own local data. In the fifth layer,
modularization is used with the help of functions and in large programs it is very difficult to identify
what data is used by which function. Hence data hiding concept can be provided using functions.
1. Large programs are divided into smaller programs known as functions called objects.
Currently, two major models or paradigms are used by programmers to develop programs and their
procedures:
Procedural programming focuses on the procedures that programmers create along with
modularization That is, procedural programmers focus on the actions that are carried out—for
example, getting input data for an employee and writing the calculations needed to produce a
paycheck from the data.
Object-oriented programming focuses on objects, or ―things,‖ and describes their features (also called
attributes) and behaviors.
For example, object-oriented programmers might design a payroll application by thinking about
employees and paychecks, and by describing their attributes. Employees have names and Social
Security numbers, and paychecks have names and check amounts. Then the programmers would think
about the behaviors of employees and paychecks, such as employees getting raises and adding
dependents and paychecks being calculated and output. Object-oriented programmers would then
build applications from these entities.
3. Object-oriented programmers focus on a program‘s objects and their attribute and behaviors.
Desirable Program Characteristics
These characteristics apply to programs that are written in any programming language :-
1. Integrity: This refers to the accuracy of the calculations. Integrity is needed to perform correct
calculations if any enhancement is done otherwise there will be no use of enhancement and all
enhancement will be meaningless Thus, the integrity of the calculations is an absolute necessity in any
computer program.
2. Clarity: refers to the overall readability of the program, with specific logic. If a program should not
be complicated it should be clearly written, it should be possible for another programmer to follow the
program logic without much effort. It should also be possible for the original author to follow his or
her own program after being away from the program for an extended period of time. One of the
objectives in the design of C is the development of clear, readable and disciplined approach to
programming
3. Simplicity: The clarity readability of the program and accuracy of a program are usually enhanced
by keeping things as simple as possible, uniqueness and consistency should be included with the
overall program objectives. In fact, it may be desirable to sacrifice a certain amount of computational
efficiency in order to maintain a relatively simple, straightforward program structure.
4. Efficiency: is concerned with execution speed and efficient memory utilization. Many complex
programs require a tradeoff between these characteristics. hence experience and common sense are
key factors are used to increase efficiency of the program.
5. Modularity: Many programs can be broken down into a series of identifiable subtasks. It is good
programming practice to implement each of these subtasks as a separate program module. In C
programming language, such modules are written as functions. The use of a modular programming
structure enhances the accuracy and clarity of a program, and it facilitates future program alterations.
6. Generality: Program to be as general as possible, within reasonable limits. For example, we may
design a program to read in the values of certain key parameters rather than placing fixed values into
the program. As a rule, a considerable amount of generality can be obtained with very little additional
programming effort. All programs should be written in a generalized manner.
EXERCISE:
Fundamentals
Structure of a C Program
Every C program consists of one or more modules called functions. One of the functions must be
called main.
The program will always begin by executing the main function, which may access other functions.
Any other function definitions must be defined separately, either ahead of or after main Each function
must contain:
1. A function heading, which consists of the function name, followed by an optional list of arguments,
enclosed in parentheses.
3. A compound statement, which comprises the remainder of the function. The arguments are symbols
that represent information being passed between the function and other parts of the program.
(Arguments are also referred to as parameters.)Each compound statement is enclosed within a pair of
braces, i.e., { }. The braces may contain one or more elementary statements (called expression
statements) and other compound statements. Thus compound statements may be nested, one within
another. Each expression statement must end with a semicolon (; ). Comments (remarks) may appear
anywhere within a program, as long as they are placed within the delimiters / * and */ (e.g., /* t h i s is
a comment */). Such comments are helpful in identifying the program's principal features or in
explaining the underlying logic of various program features. These program components will be
discussed in much greater detail later in this book. For now, the reader should be concerned only with
an overview of the basic features that characterize most C programs.
EXAMPLE - Area of a Circle Here is an elementary C program that reads in the radius of a circle,
calculates its area and then writes the calculated result.
/* TITLE(COMMENT) */
The comments at the end of each line have been added in order to
Normally a C program will not look like this. Rather, it might appear as
shown below.
#include <stdio.h>
main( )
1. The program is typed in lowercase. Either upper- or lowercase can be used, though it is customary
to type ordinary instructions in lowercase. Most comments are also typed in lowercase, though
comments are Sometimes typed in uppercase for emphasis, or to distinguish certain comments from
the instructions.
2. The first line is a comment that identifies the purpose of the program.
3. The second line contains a reference to a special file (called stdio .h) which contains information
that must be included in the program when it is compiled. The inclusion of this required information
will be handled automatically by the compiler.
4. The third line is a heading for the function main. The empty parentheses following the name of the
function indicate that this function does not include any arguments.
5. The remaining five lines of the program are indented and enclosed within a pair of braces. These
five lines comprise the compound statement within main.
6. The first indented line is a variable declaration. It establishes the symbolic names radius and area as
floating-point variables (more about this in the next chapter).
7. The remaining four indented lines are expression statements. The second indented line ( p r i n t f )
generates a request for information (namely, a value for the radius). This value is entered into the
computer via the third indented line (scanf).
8. The fourth indented line is a particular type of expression statement called an assignment statement.
This statement causes the area to be calculated from the given value of the radius. Within this
statement the asterisks (*) represent multiplication signs.
9. The last indented line ( p r i n t f ) causes the calculated value for the area to be displayed. The
numerical value will be preceded by a brief label.
10. Notice that each expression statement within the compound statement ends with a semicolon. This
is required of all expression statements.
Finally, notice the liberal use of spacing and' indentation, creating whitespace within the program. The
blank lines separate different parts of the program into logically identifiable components, and the
indentation indicates subordinate relationships among the various instructions. These features are not
grammatically essential, but their presence is strongly encouraged as a matter of good programming
practice.
Execution of the program results in an interactive dialog such as that shown below. The user's
response is underlined, for clarity.
Radius = 7 3
Area = 28.274309
PROGRAM STRUCTURE
Hello World Example
#include intmain()
/* my first program in C */
return 0;
1. The first line of the program #include is a preprocessor command, which tells a C compiler to
include stdio.h file before going to actual compilation.
2. The next line intmain() is the main function where the program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments
in the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message "Hello,
World!" to be displayed on the screen.
5. The next line return 0; terminates the main() function and returns the value 0.
Let us see how to save the source code in a file, and how to compile and run it. Following are the
simple steps:
3. Open a command prompt and go to the directory where you have saved the file.
5. If there are no errors in your code, the command prompt will take you to the next line and would
generate a.out executable file.
7. You will see the output "Hello World" printed on the screen.
$ gcchello.c
$ ./a.out
Hello, World!
Make sure the gcc compiler is in your path and that you are running it in the directory containing the
source file hello.c.
THE C CHARACTER SET
C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special
characters as building blocks to form basic program elements (e.g., constants, variables, operators,
expressions, etc.). The special characters are listed below.
Most versions of the language also allow certain other characters, such as @
TABLE
Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants
or variables or any other identifier names.
These are fundamental data types in C namely integer(int), floating(float), charater(char) and void.
Derived data types are like arrays, functions, stuctures and pointers. These are discussed in detail
later.
Data types in c refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage and
how the bit pattern stored is interpreted.
The types in C can be classified as follows −
1
Basic Types
They are arithmetic types and are further classified into: (a) integer types and (b) floating-point types.
2
Enumerated types
They are again arithmetic types and they are used to define variables that can only assign certain
discrete integer values throughout the program.
3
The type void
The type specifier void indicates that no value is available.
4
Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function
types.
The array types and structure types are referred collectively as the aggregate types. The type
of a function specifies the type of the function's return value. We will see the basic types in
the following section, where as other types will be covered in the upcoming chapters.
Integer Types
The following table provides the details of standard integer types with their storage sizes and
value ranges −
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type
in bytes. Given below is an example to get the size of various type on a machine using
different constant defined in limits.h header file −
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
return 0;
}
When you compile and execute the above program, it produces the following result on
Linux −
CHAR_BIT : 8
CHAR_MAX : 127
CHAR_MIN : -128
INT_MAX : 2147483647
INT_MIN : -2147483648
LONG_MAX : 9223372036854775807
LONG_MIN : -9223372036854775808
SCHAR_MAX : 127
SCHAR_MIN : -128
SHRT_MAX : 32767
SHRT_MIN : -32768
UCHAR_MAX : 255
UINT_MAX : 4294967295
ULONG_MAX : 18446744073709551615
USHRT_MAX : 65535
Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes
and value ranges and their precision −
The header file float.h defines macros that allow you to use these values and other details
about the binary representation of real numbers in your programs. The following example
prints the storage space taken by a float type and its range values −
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
return 0;
}
When you compile and execute the above program, it produces the following result on
Linux −
Storage size for float : 4
FLT_MAX : 3.40282e+38
FLT_MIN : 1.17549e-38
-FLT_MAX : -3.40282e+38
-FLT_MIN : -1.17549e-38
DBL_MAX : 1.79769e+308
DBL_MIN : 2.22507e-308
-DBL_MAX : -1.79769e+308
Precision value: 6
1
Function returns as void
There are various functions in C which do not return any value or you can say they return void. A
function with no return value has the return type as void. For example, void exit (int status);
2
Function arguments as void
There are various functions in C which do not accept any parameter. A function with no parameter can
accept a void. For example, int rand(void);
3
Pointers to void
A pointer of type void * represents the address of an object, but not its type. For example, a memory
allocation function void *malloc(size_t size ); returns a pointer to void which can be casted to any data
type.
Constants
Constants are of fixed values that do not change during the execution of a program. There are various
types of constants. The types are illustrated in the following figure.
Integer constants: An integer constant refers to a sequence of digits. There are three types of integer
constants, namely, decimal integer, octal integer and hexadecimal integer.
Decimal integer consists of a set of digits from 0 to 9, preceded by anoptional + or – sign. Examples,
123 -321 0 64932
0Xbcd 0x
Real constants: Real constants are used to represent quantities that are very continuously, such as
distances, temperature etc. These quantities are represented by numbers containing fractional parts.
Examples,
Single character constants: A single character constants contains a single character enclosed within a
pair of single quote marks.
Example, ‗5‘
‗X‘ ‗;‘
String constants : A string constant contains a string of characters enclosed within a pair of double
quote marks. Examples, ―Hello !‖ ―1987‖
VARIABLES
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be applied to
the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-
sensitive.
Based on the basic types explained in the previous chapter, there will be the following basic variable
types:
Type Description
Variable Definition in C :A variable definition tells the compiler where and how much storage to
create for the variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows:
typevariable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-
defined object; and variable_list may consist of one or more identifier names separated by commas.
Some valid declarations are shown here:
inti, j, k;
char c, ch;
float f salary;
double d;
The line int i, j, k; declares and defines the variables i, j and k; which instruct the compiler to create
variables named i, j, and k of type int.
typevariable_name = value;
C - Arrays
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of
the same type. An array is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by
an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows −
typearrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater
than zero and type can be any valid C data type. For example, to declare a 10-element array
called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that
we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example. Following is an
example to assign a single element of the array −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All arrays have
0 as the index of their first element which is also called the base index and the last index of
an array will be total size of the array minus 1. Shown below is the pictorial representation
of the array we discussed above −
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Arrays in Detail
Arrays are important to C and should need a lot more attention. The following important
concepts related to array should be clear to a C programmer −
1 Multi-dimensional arrays
C supports multidimensional arrays. The simplest form of the multidimensional array is the two-
dimensional array.
4 Pointer to an array
You can generate a pointer to the first element of an array by simply specifying the array name, without
any index.
C Expressions
An expression is a formula in which operands are linked to each other by the use of operators to
compute a value. An operand can be a function reference, a variable, an array element or a constant.
1. a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of operators.
Evaluation of a particular expression produces a specific value.
For example:
1. x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal is an expression.
Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic operators. An
arithmetic expression computes a value of type int, float or double.
When an expression contains only integral operands, then it is known as pure integer expression when
it contains only real operands, it is known as pure real expression, and when it contains both integral
and real operands, it is known as mixed mode expression.
The expressions are evaluated by performing one operation at a time. The precedence and
associativity of operators decide the order of the evaluation of individual operations.
When individual operations are performed, the following cases can be happened:
o When both the operands are of type integer, then arithmetic will be performed, and the result
of the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the
fractional part is ignored.
o When both the operands are of type float, then arithmetic will be performed, and the result of
the operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the mixed arithmetic
will be performed. In this case, the first operand is converted into a real operand, and then
arithmetic is performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first
value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.
Relational Expressions
o A relational expression is an expression used to compare two operands.
o It is a condition which is used to decide whether the action should be taken or not.
o In relational expressions, a numeric value cannot be compared with the string value.
o The result of the relational expression can be either zero or non-zero value. Here, the zero
value is equivalent to a false and non-zero value is equivalent to true.
Relational Description
Expression
x%2 = = 0 This condition is used to check whether the x is an even number or not.
The relational expression results in value 1 if x is an even number otherwise results in value 0.
a+b = = x+y It is used to check whether the expression "a+b" is equal to the expression "x+y".
1. #include <stdio.h>
2. int main()
3. {
4.
5. int x=4;
6. if(x%2==0)
7. {
8. printf("The number x is even");
9. }
10. else
11. printf("The number x is not even");
12. return 0;
13. }
Output
Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero value.
o It is a complex test condition to take a decision.
( x > 4 ) && ( x < 6 It is a test condition to check whether the x is greater than 4 and x is less than 6.
) The result of the condition is true only when both the conditions are true.
x > 10 || y <11 It is a test condition used to check whether x is greater than 10 or y is less than 11.
The result of the test condition is true if either of the conditions holds true value.
! ( x > 10 ) && ( y = It is a test condition used to check whether x is not greater than 10 and y is equal to 2.
=2) The result of the condition is true if both the conditions are true.
1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 10;
6. if ( (x <10) && (y>5))
7. {
8. printf("Condition is true");
9. }
10. else
11. printf("Condition is false");
12. return 0;
13. }
Output
Output
Conditional Expressions
o A conditional expression is an expression that returns 1 if the condition is true otherwise 0.
o A conditional operator is also known as a ternary operator.
The above expression is a conditional expression which is evaluated on the basis of the value of the
exp1 expression. If the condition of the expression exp1 holds true, then the final conditional
expression is represented by exp2 otherwise represented by exp3.
1. #include<stdio.h>
2. #include<string.h>
3. int main()
4. {
5. int age = 25;
6. char status;
7. status = (age>22) ? 'M': 'U';
8. if(status == 'M')
9. printf("Married");
10. else
11. printf("Unmarried");
12. return 0;
13. }
Output
STATEMENTS
A statement causes the computer to carry out some action. There are three different classes of
statements in C.
a = 3;
c=a+b;
++i;
The first two expression statements are assignment-type statements. Each causes the value of the
expression on the right of the equal sign to be assigned to the variable on the left. The third expression
statement is an incrementing-type statement, which causes the value of ito increase by 1.
The fourth expression statement causes the printf function to be evaluated. This is a standard C library
function that writes information out of the computer (more about this in Sec. 3.6). In this case, the
message Area = will be displayed, followed by the current value of the variable area. Thus, if area
represents the value loo., the statement will generate the message
Area = 100.
The last expression statement does nothing, since it consists of only a semicolon. It is simply a
mechanism for providing an empty expression statement in places where this type of statement is
required. Consequently, it is called a null statement.
A compound statement consists of several individual statements enclosed within a pair of braces { }.
The individual statements may themselves be expression statements, compound statements or control
statements. Thus, the compound statement provides a capability for embedding statements within
other statements. Unlike an expression statement, a compound statement does not end with a
semicolon.
pi = 3.141593;
circumference = 2. * pi * radius;
This particular compound statement consists of three assignment-type expression statements, though
it is considered a
single entity within the program in which it appears. Note that the compound statement does not end
with a semicolon &er the brace.
SYMBOLIC CONSTANTS IN C LANGUAGE
When a constant is used at many places in a program ,due to some reason if the value of that
constant needs to be changed,then change at every statement where that constant occurs in the
program –so modification of program becomes difficult.
Symbolic constant is defined as below:
#define symbolic_name value
Example :
#define FLAG 1
#define PI 3.1415
Here,FLAG and PI are symbolic constants.For better readability,it is advisable to use uppercase
character in the naming of symbolic constants.see there is no semicolon ‗;‘ at the end.
Program :
/* program illustrating use of declaration,assignment of value to variables.also explains how to use
symbolic constants.
program to calculate area and circumference of a circle */
#include<stdio.h>
#include<conio.h>
#define PI 3.1415 /* NO SEMICOLON HERE */
void main ()
{
float rad = 5; /*DECLARATION AND ASSIGNMENT*/
float area,circum; /* DECLARATION OF VARIABLE*/
area=PI*rad*rad;
circum=2*PI*rad;
printf(―AREA OF CIRCLE = %f\n‖,area);
printf(―CIRCUMFERENCE OF CIRCLE =%f\n‖,circum);
getch();
clrscr();
}
OUTPUT :
We have already seen that individual constants, variables, array elements and function references can
be joined together by various operators to form expressions. We have also mentioned that C includes
a large number of operators which fall into several different categories. In this chapter we examine
certain of these categories in detail. Specifically, we will see how arithmetic operators, unary
operators, relational and logical operators, assignment operators and the conditional operator are used
to form expressions. The data items that operators act upon are called operands. Some operators
require two operands, while others act upon only one operand. Most operators allow the individual
operands to be expressions. A few operators permit only single variables as operands (more about this
later).
ARITHMETIC OPERATORS
There are five arithmetic operators in C. They are
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
There is no exponentiation operator in C. However, there is a library function (POW) to carry out
exponentiation. The operands acted upon by arithmetic operators must represent numeric values.
Thus, the operands can be integer quantities, floating-point quantities or characters (remember that
character constants represent integer values, as determined by the computer’s character set). The
remainder operator (%) requires that both operands be integers and the second operand be nonzero.
Similarly, the division operator (/) requires that the second operand be nonzero.
Division of one integer quantity by another is referred to as integer division. This operation always
results in a truncated quotient (i.e., the decimal portion of the quotient will be dropped). On the other
hand, if a division operation is carried out with two floating-point numbers, or with one floating-point
number and one integer, the result will be a floating-point quotient.
EXAMPLE - Suppose that A and B are integer variables whose values are 10 and 3, respectively.
Several arithmetic
Expression Value
A+B 13
A–B 7
A*B 30
A/B 3
A%B 1
Notice the truncated quotient resulting from the division operation, since both operands represent
integer quantities.
Also, notice the integer remainder resulting from the use of the modulus operator in the last
expression.
Now suppose that A and B are floating-point variables whose values are 12.5 and 2.0, respectively.
Several
- arithmetic expressions involving these variables are shown below, together with their resulting
values.
Expression Value
A+B 14.5
A–B 10.5
A*B 25.0
A/B 6.25
UNARY OPERATORS
C includes a class of operators that act upon a single operand to produce a new value. Such operators
are known as unary operators. Unary operators usually precede their single operands, though some
unary operators are written after their operands.
Perhaps the most common unary operation is unary minus, where a numerical constant, variable or
expression is preceded by a minus sign. (Some programming languages allow a minus sign to be
included as a part of a numeric constant. In C, however, all numeric constants are positive. Thus, a
negative number is actually an expression, consisting of the unary minus operator, followed by a
positive numeric constant.)
Note that the unary minus operation is distinctly different from the arithmetic operator which denotes
subtraction (-). The subtraction operator requires two separate operands.
EXAMPLE 3.10 Here are several examples which illustrate the use of the unary minus operation
In each case the minus sign is followed by a numerical operand which may be an integer constant, a
floating-point constant, a numeric variable or an arithmetic expression.
There are two other commonly used unary operators: The increment operator, ++, and the decrement
operator, --. The increment operator causes its operand to be increased by 1, whereas the decrement
operator causes its operand to be decreased by 1. The operand used with each of these operators must
be a single variable.
Operator Meaning
< less than
<= less than or equal to
> greater than
>= greater than or equal to
These operators all fall within the same precedence group, which is lower than the arithmetic and
unary operators. The associativity of these operators is left to right.
Closely associated with the relational operators are the following two equality operators,
Operator Meaning
== equal to
!= not equal to
The equality operators fall into a separate precedence group, beneath the relational operators. These
operators also have a left-to-right associativity. These six operators are used to form logical
expressions, which represent conditions that are either true or false. The resulting expressions will be
of type integer, since true is represented by the integer value 1 and false is represented by the value 0.
EXAMPLE - Suppose that i, j and k are integer variables whose values are 1, 2 and 3, respectively.
Several logical expressions involving these variables are shown below.
In addition to the relational and equality operators, C contains two logical operators (also called logical
connectives). They are
Operator Meaning
&& And
II Or
These operators are referred to as logical and and logical or, respectively.
The logical operators act upon operands that are themselves logical expressions. The net effect is to
combine the individual logical expressions into more complex conditions that are either true or false.
The result of a logical and operation will be true only if both operands are true, whereas the result of a
logical or operation will be true if either operand is true or if both operands are true. In other words,
the result of a logical or operation will be false only if both operands are false.
In this context it should be pointed out that any nonzero value, not just 1, is interpreted as true.
The first expression is true because both operands are true. In the second expression, both operands
are again true; hence the overall expression is true. The third expression is false because the second
operand is false. And finally, the fourth expression is true because the first operand is true.
ASSIGNMENT OPERATORS
There are several different assignment operators in C. All of them are used to form assignment
expressions, which assign the value of an expression to an identifier. \
Assignment expressions that make use of this operator are written in the form
identifier = expression
where identifier generally represents a variable, and expression represents a constant, a variable or a
more complex expression.
EXAMPLE - Here are some typical assignment expressions that make use of the = operator.
a=3
x=y
delta = 0.001
sum = a + b
The first assignment expression causes the integer value 3 to be assigned to the variable a, and the
second assignment causes the value of y to be assigned to x. In the third assignment, the floating-point
value 0.001 is assigned to delta.
The last two assignments each result in the value of an arithmetic expression being assigned to a
variable (i.e., the value of a + b is assigned to sum, and the value of length * width is assigned to
area).
When evaluating a conditional expression, expression 1 is evaluated first. If expression 1 is true (i.e.,
if its value is nonzero), then expression 2 is evaluated and this becomes the value of the conditional
expression. However, if expression 1 is false (i.e., if its value is zero), then expression 3is evaluated
and this becomes the value of the conditional expression. Note that only one of the embedded
expressions (either expression 2 or expression 3) is evaluated when determining the value of a
conditional expression.
EXAMPLE - In the conditional expression shown below, assume that i is an integer variable.
(i < 0) ? 0 : 100
The expression (i < 0) is evaluated first. If it is true (i.e., if the value of i is less than 0), the entire
conditional expression takes on the value 0. Otherwise (if the value of i is not less than 0),the entire
conditional expression takes on the value 100.
In the following conditional expression, assume that f and g are floating-point variables.
(f<g)?f :g
This conditional expression takes on the value off if f is less than g; otherwise, the conditional
expression takes on the value of g. In other words, the conditional expression returns the value of the
smaller of the two variables.
EXERCISE:
1. What is Operator ? Explain Arithmetic Operators in Detail.
2. What is Operator ? Explain Assignment Operators in Detail.
3. Write program to Create Calculator ( + - * / ) in C
4. Explain conditional operator (? :) with Example.
CHAPTER – 04
Operators and Expressions - II
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 20 and variable B holds 30 then −
== Checks if the values of two operands are equal or not. If yes, then the condition becomes (A == B)
true. is not
true.
!= Checks if the values of two operands are equal or not. If the values are not equal, then the (A != B)
condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right operand. If yes, then (A > B)
the condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right operand. If yes, then the (A < B)
condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand. (A >= B)
If yes, then the condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value of right operand. If (A <= B)
yes, then the condition becomes true. is true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
&& Called Logical AND operator. If both the operands are non-zero, then the condition (A &&
becomes true. B) is
false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition (A || B)
becomes true. is true.
! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a !(A &&
condition is true, then Logical NOT operator will make it false. B) is
true.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ is as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B)
= 12,
i.e., 0000
1100
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B)
= 49,
i.e., 0011
0001
~ (~A ) =
~(60),
Binary One's Complement Operator is unary and has the effect of 'flipping' bits.
i.e,. -
0111101
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits A << 2 =
specified by the right operand. 240 i.e.,
1111
0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits A >> 2 =
specified by the right operand. 15 i.e.,
0000
1111
Assignment Operators
The following table lists the assignment operators supported by the C language −
= Simple assignment operator. Assigns values from right side operands to left side C=A+
operand B will
assign the
value of
A + B to
C
+= Add AND assignment operator. It adds the right operand to the left operand and assign C += A is
the result to the left operand. equivalent
to C = C
+A
-= Subtract AND assignment operator. It subtracts the right operand from the left operand C -= A is
and assigns the result to the left operand. equivalent
to C = C -
A
*= Multiply AND assignment operator. It multiplies the right operand with the left operand C *= A is
and assigns the result to the left operand. equivalent
to C = C
*A
/= Divide AND assignment operator. It divides the left operand with the right operand and C /= A is
assigns the result to the left operand. equivalent
to C = C /
A
%= Modulus AND assignment operator. It takes modulus using two operands and assigns C %= A
the result to the left operand. is
equivalent
to C = C
%A
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the variable.
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Arithmetic Operator
Example
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf(“Value of c is %d\n", c );
c = a - b;
printf("Value of c is %d\n", c );
c = a * b;
printf("Value of c is %d\n", c );
c = a / b;
printf("Value of c is %d\n", c );
c = a % b;
printf("Value of c is %d\n", c );
c = a++;
printf("Value of c is %d\n", c );
c = a--;
printf("Value of c is %d\n", c );
}
result −
Value of c is 31
Value of c is 11
Value of c is 210
Value of c is 2
Value of c is 1
Value of c is 21
Value of c is 22
Relational Operator
Example
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
printf("a is equal to b\n" );
} else {
printf("a is not equal to b\n" );
}
if ( a < b ) {
printf("a is less than b\n" );
} else {
printf("a is not less than b\n" );
}
if ( a > b ) {
printf("a is greater than b\n" );
} else {
printf("a is not greater than b\n" );
}
if ( a <= b ) {
printf("a is either less than or equal to b\n" );
}
if ( b >= a ) {
printf("b is either greater than or equal to b\n" );
}
}
result −
a is not equal to b
a is not less than b
a is greater than b
a is either less than or equal to b
b is either greater than or equal to b
Logical Operator
Example :-
#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf("Condition is true\n" );
}
if ( a || b ) {
printf("Condition is true\n" );
}
if ( a && b ) {
printf("Condition is true\n" );
} else {
printf("Condition is not true\n" );
}
if ( !(a && b) ) {
printf("Condition is true\n" );
}
}
result −
Condition is true
Condition is true
Condition is not true
Condition is true
Bitwise Operator
Example
#include <stdio.h>
main() {
c = a | b; /* 61 = 0011 1101 */
printf("Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Value of c is %d\n", c );
Assignment Operator
Example
#include <stdio.h>
main() {
int a = 21;
int c ;
c = a;
printf("= Operator Example, Value of c = %d\n", c );
c += a;
printf("+= Operator Example, Value of c = %d\n", c );
c -= a;
printf("-= Operator Example, Value of c = %d\n", c );
c *= a;
printf("*= Operator Example, Value of c = %d\n", c );
c /= a;
printf("/= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
printf("%= Operator Example, Value of c = %d\n", c );
c <<= 2;
printf("<<= Operator Example, Value of c = %d\n", c );
c >>= 2;
printf(">>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("&= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf("^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("|= Operator Example, Value of c = %d\n", c );
}
result −
= Operator Example, Value of c = 21
+= Operator Example, Value of c = 42
-= Operator Example, Value of c = 21
*= Operator Example, Value of c = 441
/= Operator Example, Value of c = 21
%= Operator Example, Value of c = 11
<<= Operator Example, Value of c = 44
>>= Operator Example, Value of c = 11
&= Operator Example, Value of c = 2
^= Operator Example, Value of c = 0
|= Operator Example, Value of c = 2
sizeof and ternary operator
Example
#include <stdio.h>
main() {
int a = 4;
short b;
double c;
int* ptr;
Operators Precedence
Example
#include <stdio.h>
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
result −
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
C – Library functions
Library functions in C language are inbuilt functions which are grouped together and placed in a common
place called library.
Each library function in C performs specific operation.
We can make use of these library functions to get the pre-defined output instead of writing our own code
to get those outputs.
These library functions are created by the persons who designed and created C compilers.
All C standard library functions are declared in many header files which are saved as file_name.h.
Actually, function declaration, definition for macros are given in all header files.
We are including these header files in our C program using “#include<file_name.h>” command to make
use of the functions those are declared in the header files.
When we include header files in our C program using “#include<filename.h>” command, all C code of the
header files are included in C program. Then, this C program is compiled by compiler and executed.
string.h All string related functions are defined in this header file
math.h All maths related functions are defined in this header file
time.h This header file contains time and clock related functions
ctype.h All character handling functions are defined in this header file
LIBRARY FUNCTIONS
The C language is accompanied by a number of library functions that carry out various commonly
used operations or calculations. These library functions are not a part of the language per se, though
all implementations of the language include them. Some functions return a data item to their access
point; others indicate whether a condition is true or false by returning a 1 or a 0, respectively; still
others carry out specific operations on data items but do not return anything. Features which tend to
be computer-dependent are generally written as library functions.
For example, there are library functions that carry out standard input/output operations (e.g., read and
write characters, read and write numbers, open and close files, test for end of file, etc.), functions that
perform operations on characters (e.g., convert from lower- to uppercase, test to see if a character is
uppercase, etc.), functions that perform operations on strings (e.g., copy a string, compare strings,
concatenate strings, etc.), and functions that carry out various mathematical calculations (e.g.,
evaluate trigonometric, logarithmic and exponential functions, compute absolute values, square roots,
etc.). Other kinds of library functions are also
available.
Library functions that are functionally similar are usually grouped together as (compiled) object
programs in separate library files. These library files are supplied as a part of each C compiler. All C
compilers contain similar groups of library functions, though they lack precise standardization. Thus
there may be some variation in the library functions that are available in different versions of the
language.
A typical set of library functions will include a fairly large number of functions that are common to
most C compilers, such as those shown in Table 3-2 below. Within this table, the column labeled
“type” refers to the data type of the quantity that is returned by the function. The void entry shown for
function and indicates that nothing is returned by this function.
A library function is accessed simply by writing the function name, followed by a list of arguments
that represent information being passed to the function. The arguments must be enclosed in
parentheses and separated by commas. The arguments can be constants, variable names, or more
complex expressions. The parentheses must be present, even if there are no arguments.
A function that returns a data item can appear anywhere within an expression, in place of a constant or
an identifier (Le., in place of a variable or an array element). A function that carries out operations on
data items but does not return anything can be accessed simply by writing the function name, since
this type of function reference constitutes an expression statement.
EXAMPLE - Lowercase to Uppercase Character Conversion Here is a complete C program that reads
in a
lowercase character, converts it to uppercase and then displays the uppercase equivalent.
#include <stdio.h>
#include <ctype.h>
main ( )
lower = getchar();
upper = toupper(lower);
putchar(upper);
This program contains three library functions: getchar, toupper and putchar. The first two functions
each return a single character (getchar returns a character that is entered from the keyboard, and to
upper returns the uppercase equivalent of its argument). The last function (putchar) causes the value
of the argument to be displayed.
Notice that the last two functions each have one argument but the first function does not have any
arguments, as indicated by the empty parentheses.
Also, notice the preprocessor statements #include <stdio. h> and #include <ctype. h>, which appear at
the start of the program. These statements cause the contents of the files stdio. h and ctype .h to be
inserted into the program the compilation process begins. The information contained in these files is
essential for the proper functioning of the library functions getchar, putchar and toupper.
EXERCISE:
CHAPTER – 05
Data Input and Output
We have already seen that the C language is accompanied by a collection of library functions, which
includes a number of input output functions. In this chapter we will make use of six of these functions:
getchar, putchar, scanf, printf, gets and puts. These six fuctions permit the transfer of information between
the computer and the standard input output devices (e.g., a keyboard and a TV monitor). The first two
functions, getchar and putchar, allow single characters to be transferred into and out of the computer;
scanf and printf are the most complicated, but they permit the transfer of single characters, numerical
values and strings; gets and puts facilitate the input and output of strings. Once we have learned how to
use these functions, we will be able to write a number of complete, though simple, C programs.
An input output function can be accessed from anywhere within a program simply by writing the
function name, followed by a list of arguments enclosed in parentheses. The arguments represent data
items that are sent to the function. Some inputloutput functions do not require arguments, though the
empty parentheses must still appear.
The names of those functions that return data items may appear within expressions, as though each
function reference were an ordinary variable (e.g., c = getchar ( ) ;), or they may be referenced as
separate statements (e.g., scanf ( . . . ) ;). Some functions do not return any data items. Such functions
are referenced as though they were separate statements (e.g., putchar ( . . . ) ;).
EXAMPLE - Here is an outline of a typical C program that makes use of several inputloutput routines
from the standard C library.
#include <stdio.h>
main ( )
float x,y;
int i , j ,0 k ;
Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file.
C programming language provides many built-in functions to read any given input and to
display data on screen when there is a need to output the result.
In this tutorial, we will learn about such functions, which can be used in our program to take
input from user and to output the result on screen.
All these built-in functions are present in C header files, we will also specify the name of
header files in which a particular function is defined while discussing about it.
void main()
{
// defining a variable
int i;
/*
displaying message on the screen
asking the user to input a value
*/
printf("Please enter a value...");
/*
reading the value entered by the user
*/
scanf("%d", &i);
/*
displaying the number as output
*/
printf( "\nYou entered: %d", i);
}
When you will compile the above code, it will ask you to enter a value. When you will enter
the value, it will display the value you have entered on screen.
You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is
known as format string and this informs the scanf() function, what type of input to expect
and in printf() it is used to give a heads up to the compiler, what type of output to expect.
We can also limit the number of digits or characters that can be input or output, by adding
a number with the format string specifier, like "%1d" or "%3s", the first one means a single
numeric digit and the second one means 3 characters, hence if you try to input 42,
while scanf() has "%1d", it will take only 4 as input. Same is the case for output.
In C Language, computer monitor, printer etc output devices are treated as files and the same
process is followed to write output to these devices as would have been followed to write the
output to a file.
NOTE : printf() function returns the number of characters printed by it, and scanf() returns the
number of characters read by it.
int i = printf("studytonight");
In this program printf("studytonight"); will return 12 as result, which will be stored in the
variable i, because studytonight has 12 characters.
void main( )
{
int c;
printf("Enter a character");
/*
Take a character as input and
store it in variable c
*/
c = getchar();
/*
display the character stored
in variable c
*/
putchar(c);
}
When you will compile the above code, it will ask you to enter a value. When you will enter
the value, it will display the value you have entered.
C contains a number of other library functions that permit some form of data transfer into or out of the
computer. the gets and puts functions, which facilitate the transfer of strings between the computer
and the standard input output devices. Each of these functions accepts a single argument. The
argument must be a data item that represents a string. (e.g., a character array). The string may include
whitespace characters. In the case of gets, the string will be entered fiom the keyboard, and will
terminate with a newline character (i.e., the string will end when the user presses the Enter key).
The gets and puts functions offer simple alternatives to the use of scanf and printf for reading and
displaying strings, as illustrated in the following example.
#include <stdio.h>
char line[80];
gets(1ine);
puts(1ine);
This program utilizes gets and puts, rather than scanf and printf, to transfer the line of text into and out
of the computer.
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
When you will compile the above code, it will ask you to enter a string. When you will enter
the string, it will display the value you have entered.
If an end-of-file condition is encountered when reading a character with the getchar function,
the value of the symbolic constant EOF will automatically be returned. (This value will be
assigned within the stdio.h file. Typically, the EOF will be assigned the value -1). The
detection of EOF in this manner offers a convenient way to detect an end of file, whenever
and wherever it may occur. Appropriate corrective action may then be taken.
The getchar function can also be used to read multi-character strings by reading one character
at a time within a multi-pass loop.
The putchar function like getchar is a part of the standard C input/output library. It transmits a
single character to the standard output device (the computer screen). The character being
transmitted will be represented as a character-type variable. It must be expressed as an
argument to the function, enclosed in parentheses, following the word putchar.
putchar(character variable)
A simple example demonstrating the use of getchar and putchar is given below:
#include<stdio.h>
int main()
char c;
c=getchar();
printf("n The character entered is: ");
putchar(c);
return 0;
In the above program, the statement c=getchar(); accepts a character entered by the user and
stores it in the variable c. The character entered by the user can be anything from the C
character set. The statement putchar(c); prints the character stored in the variable c.
The putchar function can be used to output a string constant by storing the string within a one-
dimensional character-type array. Each character can then be written separately within a loop.
The most convenient way to do this is to utilize the for statement, which we will discuss in
future.
where control string refers to a string containing certain required formatting information,
and arg1,arg2,….,argN are arguments that represent the individual data items. (Actually the
arguments represent pointers that indicate the addresses of the data items within the
computer’s memory. We will discuss pointers in greater detail in a future article, but until
then it would be helpful to remember the fact that the arguments in the scanf function actually
represent the addresses of the data items being entered.)
The control string consists of the individual group of characters called format specifiers,
with one character group for each input data item. Each character group must begin with a
per cent sign (%) and be followed by a conversion character which indicates the type of the
data item. Within the control string, multiple character groups can be contiguous, or they can
be separated by whitespace characters (ie, white spaces, tabs or newline characters).
c character
d decimal integer
h short integer
o octal integer
x hexadecimal integer
s string
The arguments to a scanf function are written as variables or arrays whose types match the
corresponding character groups in the control string. Each variable name must be preceded by
an ampersand (&). However, character array names do not begin with an ampersand. The
actual values of the arguments must correspond to the arguments in the scanf function in
number, type and order.
If two or more data items are entered, they must be separated by whitespace characters. The
data items may continue onto two or more lines, since the newline character is considered to
be a whitespace character and can therefore separate consecutive data items.
Example 1:
#include<stdio.h>
int main()
char a[20];
int i;
float b;
return 0;
In the above program, within the scanf function, the control string is "%s %d %f". It denotes
three-character groups or format specifiers. The first format specifier %s denotes that the first
argument a represents a string (character array), the second format specifier %d denotes that
the second argument i is an integer and the third format specifier %f denotes that the third
argument b is a floating point number.
Also note that the only argument not preceded by an ampersand (&) is a since a denotes a
character array.
When the program is executed, successive characters will continue to be read as long as each
input character matches one of the characters enclosed in the square brackets. The order of
the characters in the square brackets need not correspond to the order of the characters being
entered. As soon as an input character is encountered that does not match one of the
characters within the brackets, the scanf function will stop reading any more characters and
will terminate the string. A null character will then automatically be added to the end of the
string.
Example:
#include<stdio.h>
int main()
char line[80];
printf("%s", line);
return 0;
then the entire data will be assigned to the array line. However, if the input is:
then only the letters in uppercase (R, A, S, W, S) will be assigned to line, as all the characters
in the control string are in uppercase.
2. To enter a string that includes whitespaces as well as uppercase and lowercase characters
we can use the circumflex, ie (^), followed by a newline character within the brackets.
Example:
scanf("[^n]", line);
The circumflex causes the subsequent characters within the square brackets to be interpreted
in the opposite manner. Thus, when the program is executed, characters will be read as long
as a newline character is not encountered.
The consecutive non-whitespace characters that define a data item collectively define a field.
To limit the number of such characters for a data item, an unsigned integer indicating
the field width precedes the conversion character. The input data may contain fewer
characters than the specified field width. Extra characters will be ignored.
Example: If a and b are two integer variables and the following statement is being used to
read their values:
If the input is 123 4 56 (space inserted by a typing mistake), then a=123 and b=4. This is
because the space acts as a data item separator.
Example 1: C Output
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}
Output
C Programming
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Output
Number = 5
#include <stdio.h>
int main()
{
float number1 = 13.5;
double number2 = 12.4;
Output
number1 = 13.500000
number2 = 12.400000
Example 4: Print Characters
#include <stdio.h>
int main()
{
char chr = 'a';
printf("character = %c.", chr);
return 0;
}
Output
character = a
#include <stdio.h>
int main()
{
int testInteger;
printf("Enter an integer: ");
scanf("%d", &testInteger);
printf("Number = %d",testInteger);
return 0;
}
Output
Enter an integer: 4
Number = 4
#include <stdio.h>
int main()
{
float num1;
double num2;
return 0;
}
Output
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.", chr);
return 0;
}
Output
Enter a character: g
You entered g.
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);
// When %c is used, a character is displayed
printf("You entered %c.\n",chr);
Output
Enter a character: g
You entered g.
ASCII value is 103.
#include <stdio.h>
int main()
{
int a;
float b;
Output
Here's a list of commonly used C data types and their format specifiers.
Data Type Format Specifier
int %d
char %c
float %f
double %lf
unsigned int %u
signed char %c
unsigned char %c
Many modern computer programs are designed to create an interactive dialog between the computer
and the person using the program (the "user"). These dialogs usually involve some form of question-
answer interaction, where the computer asks the questions and the user provides the answers, or vice
versa. The computer and the user thus appear to be carrying on some limited form of conversation.
In C, such dialogs can be created by alternate use of the scanf and printf functions. The actual
programming is straightforward, though sometimes confusing to beginners, since the printf function is
used both when entering data (to create the computer's questions) and when displaying results. On the
other hand, scanf is used only for actual data entry.
EXAMPLE - Averaging Student Exam Scores This example presents a simple, interactive C program
that reads in a student's name and three exam scores, and then calculates an average score. The data
will be entered interactively, with the computer asking the user for information and the user supplying
the information in a free format, as requested. Each input data item will be entered on a separate line.
Once all of the data have been entered, the computer will compute the desired average and write out
all of the data (both the input data and the calculated average).
#include <stdio.h>
char name[20];
scanf("%f", &score1);
scanf ( "%f",&score2) ;
scanf("%f", &score3);
}
Notice that two statements are associated with each input data item. The first is a printf statement,
which generates a request for the item. The second statement, a scanf function, causes the data item to
be entered from the standard input device (i.e., the keyboard).
After the student's name and all three exam scores have been entered, an average exam score is
calculated. The input data and the calculated average are then displayed, as a result of the group of
printf statements at the end of the program.
A typical interactive session is shown below. To illustrate the nature of the dialog, the user's responses
have been underlined.
Score 1: 88.0
Score 2: 62.5
Score 3: 90.0
Average : 80.2
EXERCISE:
1. Explain scanf() and printf() functions in detail.
2. Explain getchar() & putchar() functions in detail.
3. Write a Difference between scanf() and gets()
4. Enlist most commonly used conversion characters in C
5. What is Format specifiers ? Explain with Example.
6. What is INTERACTIVE (CONVERSATIONAL) PROGRAMMING ? Explain
UNIT III
CHAPTER – 06
Conditional Statements
In most of the C programs we have encountered so far, the instructions were executed in the same
order in which they appeared within the program. Each instruction was executed once and only once.
Programs of this type are unrealistically simple, since they do not include any logical control
structures.
Thus, these programs did not include tests to determine if certain conditions are true or false, they did
not require the repeated execution of groups of statements, and they did not involve the execution of
individual groups of statements on a selective basis.
Most C programs that are of practical interest make extensive use of features such as these.
For example, a realistic C program may require that a logical test be carried out at some particular
point within the program. One of several possible actions will then be carried out, depending on the
outcome of the logical test. This is known as branching. There is also a special kind of branching,
called selection, in which one group of statements is selected from several available groups. In
addition, the program may require that a group of instructions be executed repeatedly, until some
logical condition has been satisfied. This is known as looping. Sometimes the required number of
repetitions is known in advance; and sometimes the computation continues indefinitely until the
logical condition becomes true.
All of these operations can be carried out using the various control statements included in C. We will
see how this is accomplished in this chapter. The use of these statements will open the door to
programming problems that are much broader and more interesting than those considered earlier.
Decision Making
Decision making structures require that the programmer specifies one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed if
the condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Show below is the general form of a typical decision making structure found in most of the
programming languages −
C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.
C programming language provides the following types of decision making statements.
1 if statement
2 if...else statement
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
4 switch statement
A switch statement allows a variable to be tested for equality against a list of values.
You can use one switch statement inside another switch statement(s).
The ? : Operator
We have covered conditional operator ? : in the previous chapter which can be used to
replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this −
Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ?
expression.
If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
Decision making in C
Decision making is about deciding the order of execution of statements based on certain
conditions or repeat a group of statements until certain specified conditions are met. C
language handles decision-making by supporting the following statements,
if statement
switch statement
goto statement
1. Simple if statement
2. if....else statement
The following table shows all the relational operators supported by C. Assume
variable A holds 20 and variable B holds 30 then –
Relational Operators
== Checks if the values of two operands are equal or not. If yes, then the condition becomes (A == B)
true. is not
true.
!= Checks if the values of two operands are equal or not. If the values are not equal, then the (A != B)
condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right operand. If yes, then (A > B)
the condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right operand. If yes, then the (A < B)
condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand. (A >= B)
If yes, then the condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value of right operand. If (A <= B)
yes, then the condition becomes true. is true.
Example
#include <stdio.h>
main() {
int a = 19;
int b = 9;
int c ;
if( a == b ) {
printf("a is equal to b \n" );
} else {
printf("a is not equal to b \n" );
}
if ( a < b ) {
printf("a is less than b \n" );
} else {
printf("a is not less than b \n" );
}
if ( a > b ) {
printf("a is greater than b \n" );
} else {
printf("a is not greater than b \n" );
}
if ( a <= b ) {
printf("a is either less than or equal to b\n" );
}
if ( b >= a ) {
printf("b is either greater than or equal to b\n" );
}
}
result −
a is not equal to b
a is not less than b
a is greater than b
a is either less than or equal to b
b is either greater than or equal to b
Logical Connectives
C contains two logical connectives (also called logical operators), && (AND) and I I (OR), and the unary
negation operator ! . The logical connectives are used to combine logical expressions, thus forming more
complex expressions. The negation operator is used to reverse the meaning of a logical expression (e.g., from
true to false).
EXAMPLE 6.2 Here are some logical expressions that illustrate
operator.
expressions as
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
&& Called Logical AND operator. If both the operands are non-zero, then the condition (A &&
becomes true. B) is
false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition (A || B)
becomes true. is true.
! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a !(A &&
condition is true, then Logical NOT operator will make it false. B) is
true.
Example
#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf(“Condition is true\n" );
}
if ( a || b ) {
printf("Condition is true\n" );
}
if ( a && b ) {
printf("Condition is true\n" );
} else {
printf("Condition is not true\n" );
}
if ( !(a && b) ) {
printf("Condition is true\n" );
}
}
result −
Condition is true
Condition is true
Condition is not true
Condition is true
Simple if statement
if statement is used for branching when a single condition is to be checked. The condition enclosed in
if statement decides the sequence of execution of instruction. If the condition is true, the statements
inside if statement are executed, otherwise they are skipped. In C programming language, any non
zero value is considered as true and zero or null is considered false.
Syntax of if statement
if (condition)
statements;
... ... ...
Example 1 :
#include <stdio.h>
void main( )
int x, y;
x = 15;
y = 13;
if (x > y )
OUTPUT :-
x is greater than y
Flowchart :-
Example 2 :- C program to print the square of a number if it is less than 10.
#include<stdio.h>
int main()
int n;
printf("Enter a number:");
scanf("%d",&n);
if(n<10)
printf("Square = %d\n",n*n);
return 0;
This program is an example of using if statement. A number is asked from user and stored in
variable n. If the value of n is less than 10, then its square is printed on the screen. If the
condition is false the program, execution is terminated.
Output
Enter a number:6
6 is less than 10
Square = 36
if ... else statement
if ... else statement is a two way branching statement. It consists of two blocks of statements
each enclosed inside if block and else block respectively. If the condition inside if statement
is true, statements inside if block are executed, otherwise statements inside else block
are executed. Else block is optional and it may be absent in a program.
if (condition)
statements;
else
statements;
}
Flowchart of if ... else statement
int main()
int n;
printf("Enter a number:");
scanf("%d",&n);
if(n%2 == 0)
printf("%d is even",n);
else
printf("%d is odd",n);
return 0;
}
Here, a number is entered by user which is stored in n. The if statement checks if the
remainder of that number when divided by 2 is zero or not. If the remainder is zero, the
number is even which is printed on the screen. If the remainder is 1, the number is odd.
Note: If there is only one statement inside if block, we don't need to enclose it with curly
brackets { }.
Output
Enter a number:18
18 is even
Enter a number:33
33 is odd
statements;
else if (condition 2)
{
statements;
else if (condition n)
statements;
else
statements;
}
Flowchart of if ... else if ... else statement
int main()
int n;
printf("Enter a number:");
scanf("%d",&n);
if(n<0)
printf("Number is negative");
else if(n>0)
printf("Number is positive");
else
return 0;
In this program, a number is entered by user stored in variable n. The if ... else if ... else
statement tests two conditions:
1. n<0: If it is true, "Number is negative" is printed on the screen.
2. n>0: If it is true, "Number is positive" is printed on the screen.
If both of these conditions are false then the number is zero. So the program will print
"Number is zero".
Output
Enter a number:109
Number is positive
Enter a number:-56
Number is negative
Enter a number:0
C – while loop
Syntax of while loop:
C while loop
#include <stdio.h>
int main()
int count=1;
count++;
return 0;
Output: 1 2 3 4
step1: The variable count is initialized with value 1 and then it has been tested for the condition.
step2: If the condition returns true then the statements inside the body of while loop are executed else
control comes out of the loop.
step3: The value of count is incremented using ++ operator then it has been tested again for the loop
condition.
#include <stdio.h>
int main()
int var=1;
The program is an example of infinite while loop. Since the value of the variable var is same (there is
no ++ or – operator used on this variable, inside the body of loop) the condition var<=2 will be true
forever and the loop would never terminate.
#include <stdio.h>
int main()
int var = 6;
printf("%d", var);
var++;
}
return 0;
Infinite loop: var will always have value >=5 so the loop would never end.
do while loop in C
The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several parts of
the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once.
The do-while loop is mostly used in menu-driven programs where the termination condition depends upon the
end user.
do{
//code to be executed
}while(condition);
Example
#include<stdio.h>
#include<stdlib.h>
void main ()
{
char c;
int choice,dummy;
do{
printf("\n1. Print Hello\n2. Print demo program \n3. Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Hello");
break;
case 2:
printf("demo program");
break;
case 3:
exit(0);
break;
default:
printf("please enter valid choice");
}
printf("do you want to enter more?");
scanf("%d",&dummy);
scanf("%c",&c);
}while(c=='y');
}
Output
Print Hello
Print Demo program
Exit
1
Hello
do you want to enter more?
y
Print Hello
Print demo program
Exit
2
Demo program
do you want to enter more?
N
Program :-
#include<stdio.h>
int main(){
int i=1,number=0;
do{
printf("%d \n",(number*i));
i++;
}while(i<=10);
return 0;
Output
Enter a number: 5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100
for loop in C
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is −
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a 'for' loop −
The init step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and the flow of control jumps to the next statement just after
the 'for' loop.
After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false,
the 'for' loop terminates.
Flowchart :-
Example
#include <stdio.h>
int main () {
int a;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C programmers more commonly use the for(;;)
construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
nested loops in C
C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.
Syntax
statement(s);
statement(s);
}
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#include <stdio.h>
int main () {
int i, j;
return 0;
result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
C switch Statement
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is
much easier to read and write.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
default:
// default statements
The expression is evaluated once and compared with the values of each case label.
If there is a match, the corresponding statements after the matching label are executed. For example, if
the value of the expression is equal to constant2, statements after case constant2: are executed until
break is encountered.
If we do not use break, all statements after the matching label are executed. the default clause inside
the switch statement is optional.
switch Statement Flowchart
Example: -
#include <stdio.h>
int main()
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
break;
default:
printf("Default ");
return 0;
Output:
Case 2
EXERCISE:
4. Draw FlowChart for For loop. Also discuss syntax for same.
6. Write a C program to print prime numbers between 1 to 100 using nested for loop.
CHAPTER – 08
Functions
Function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional
functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is so each function
A function declaration tells the compiler about a function's name, return type, and
The C standard library provides numerous built-in functions that your program can call. For
example, function strcat() to concatenate two strings, function memcpy() to copy one
A function is known with various names like a method or a sub-routine or a procedure, etc.
Defining a Function
The general form of a function definition in C programming language is as follows:
A function definition in C programming language consists of a function header and a function body.
Here are all the parts of a function:
Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
Function Body: The function body contains a collection of statements that define what the function
does.
Example
Following is the source code for a function called max(). This function takes two parameters num1
and num2 and returns the maximum between the two:
int result;
result = num1;
else
result = num2;
return result;
Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
For the above defined function max(), following is the function declaration:
Parameter names are not important in function declaration only their type is required, so following is
also valid declaration:
Function declaration is required when you define a function in one source file and you call
that function in another file. In such case you should declare the function at the top of the
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called
function performs defined task, and when its return statement is executed or when its function-ending
closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example:
#include <stdio.h>
/* function declaration */
int main ()
int a = 100;
int b = 200;
int ret;
return 0;
int result;
result = num1;
else
result = num2;
return result;
Here max() function along with main() function and compiled the source code. While
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function. The formal parameters behave like
other local variables inside the function and are created upon entry into the function and destroyed
upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
In general, this means that code within a function cannot alter the arguments used to call the function.
Consider the function swap() definition as follows.
int temp;
x = y; /* put y into x */
Now, let us call the function swap() by passing actual values as in the following example:
#include <stdio.h>
/* function declaration */
int main ()
int a = 100;
int b = 200;
swap(a, b);
return 0;
Let us put above code in a single C file, compile and execute it, it will produce the following
result:
Which shows that there is no change in the values though they had been changed inside the function.
To pass the value by reference, argument pointers are passed to the functions just like any other value.
So accordingly you need to declare the function parameters as pointer types as in the following
function swap(), which exchanges the values of the two integer variables pointed to by its arguments.
int temp;
return;
Let us call the function swap() by passing values by reference as in the following example:
#include <stdio.h>
/* function declaration */
int main ()
int b = 200;
*/
swap(&a, &b);
return 0;
Let us put above code in a single C file, compile and execute it, it will produce the following
result:
Which shows that there is no change in the values though they had been changed inside
the function.
int main(void) { . . . }
int main(int argc, char *argv[ ]) { . . . })
argc
The number of arguments in the command line that invoked the program. The value of argc is
nonnegative.
argv
Pointer to an array of character strings that contain the arguments, one per string. The
value argv[argc] is a null pointer.
If the value of argc is greater than zero, the array members argv[0] through argv[argc - 1] inclusive
contain pointers to strings, which are given implementation-defined values by the host environment
before program startup. The intent is to supply the program with information determined before
program startup from elsewhere in the host environment. If the host environment cannot supply
strings with letters in both uppercase and lowercase, the host environment ensures that the strings are
received in lowercase.
If the value of argc is greater than zero, the string pointed to by argv[0] represents the program
name; argv[0][0] is the null character if the program name is not available from the host environment.
If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc - 1]
represent the program parameters.
The parameters argc and argv, and the strings pointed to by the argv array, can be modified by the
program and keep their last-stored values between program startup and program termination.
In the main function definition, parameters are optional. However, only the parameters that are
defined can be accessed.
Function Prototype
A function prototype is a function declaration that specifies the data types of its arguments in the
parameter list. The compiler uses the information in a function prototype to ensure that the
corresponding function definition and all corresponding function declarations and calls within the
scope of the prototype contain the correct number of arguments or parameters, and that each argument
or parameter is of the correct data type.
Prototypes are syntactically distinguished from the old style of function declaration. The two styles
can be mixed for any single function, but this is not recommended. The following is a comparison of
the old and the prototype styles of declaration:
Old style:
Prototype style:
Functions are declared explicitly with a prototype before they are called. Multiple
declarations must be compatible; parameter types must agree exactly.
Arguments to functions are converted to the declared types of the parameters.
The number and type of arguments are checked against the prototype and must agree with or
be convertible to the declared types. Empty parameter lists are designated using
the void keyword.
Ellipses are used in the parameter list of a prototype to indicate that a variable number of
parameters are expected.
Prototype Syntax
function-prototype-declaration:
declaration-specifiers(opt) declarator;
The declarator includes a parameter type list, which can consist of a single parameter of type void . In
its simplest form, a function prototype declaration might have the following format:
A prototype is identical to the header of its corresponding function definition specified in the
prototype style, with the addition of a terminating semicolon (;) or comma (,), as appropriate
(depending on whether the prototype is declared alone or in a multiple declaration).
Function prototypes need not use the same parameter identifiers as in the corresponding function
definition because identifiers in a prototype have scope only within the identifier list. Moreover, the
identifiers themselves need not be specified in the prototype declaration; only the types are required.
Though not required, identifiers should be included in prototypes to improve program clarity and
increase the type-checking capability of the compiler.
Variable-length argument lists are specified in function prototypes with ellipses. At least one
parameter must precede the ellipses. For example:
Explanation : -
It is now considered good form to use function prototypes for all functions in your program. A
prototype declares the function name, its parameters, and its return type to the rest of the program
prior to the function's actual declaration. To understand why function prototypes are useful, enter the
following code and run it:
#include <stdio.h>
void main()
{
printf("%d\n",add(3));
}
To solve this problem, C lets you place function prototypes at the beginning of (actually, anywhere in)
a program. If you do so, C checks the types and counts of all parameter lists. Try compiling the
following:
#include <stdio.h>
void main()
{
printf("%d\n",add(3));
}
Place one prototype for each function at the beginning of your program. They can save you a great
deal of debugging time, and they also solve the problem you get when you compile with functions
that you use before they are declared. For example, the following code will not compile:
#include <stdio.h>
void main()
{
printf("%d\n",add(3));
}
C - Recursion
Recursion is the process of repeating items in a self-similar way. In programming languages,
if a program allows you to call a function inside the same function, then it is called a
recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
Number Factorial
#include <stdio.h>
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
result −
Factorial of 12 is 479001600
Fibonacci Series
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
return 0;
}
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34
The prototype and data definitions of these functions are present in their respective
header files. To use these functions we need to include the header file in our
program. For example,
If you want to use the printf() function, the header file <stdio.h> should be included.
#include <stdio.h>
int main()
{
printf("Catch me if you can.");
}
If you try to use printf() without including the stdio.h header file, you will get an
error.
1. They work
One of the most important reasons you should use library functions is simply
because they work. These functions have gone through multiple rigorous testing
and are easy to use.
To can compute the square root of a number, you can use the sqrt() library
function. The function is defined in the math.h header file.
#include <stdio.h>
#include <math.h>
int main()
{
float num, root;
printf("Enter a number: ");
scanf("%f", &num);
Enter a number: 12
Square root of 12.00 = 3.46
Library Functions in Different Header Files
C Header Files
When a line of code in a function that says: "return X;" is executed, the function
"ends" and no more code in the function is executed. The value of X (or the value
in the variable represented by X) becomes the result of the function.
EXERCISE:
7.1.1 Introduction
Storage Classes are used to describe the various features of a variable or function.
These features include the scope, visibility and life-time which help to trace the existence of a
variable during the runtime of a program.
1. auto: This is the default storage class for all variables declared inside a function or a
block. Hense, the keyword auto is rarely used while writing programs in C language.
Auto variables can be only accessed within the block or function they have been
declared and not outside them. These can be accessed within nested blocks within the
parent block or function in which the auto variable was declared. They can be
accessed outside their scope as well using the concept of pointers given here by
pointing to the exact memory location where the variables resides. They are assigned
a garbage value by default whenever they are declared.
2. extern: Extern storage class simply shows that the variable is defined elsewhere and
not within the same block where it is used. The value is assigned to it in a different
block and this can be overwritten or changed in a different block as well. So an extern
variable is a global variable initialized with a legal value where it is declared in order
to be used elsewhere. It can be accessed within any function/block. A normal global
variable can be made extern as well by placing the ‗extern‘ keyword before its
declaration or definition in any function or block. This basically signifies that we are
not initializing a new variable but instead we are using the global variable only. Then
purpose of using extern variables is that they can be accessed between two different
files which are part of a large program.
3. static: This storage class is used to declare static variables which are used while
writing programs in C language. Static variables have a property of preserving their
value even after they are out of their scope. Hense, static variables preserve their
previous value in their previous scope and are not initialized again in the new scope.
we can say that they are initialized only once and exist till the end of the program.
Hence, no new memory is allocated because they are not re-declared. Their scope is
local to the function to which they were defined. Global static variables can be
accessed anywhere in the program. By default, 0 value assigned to them by the
compiler.
4. register: This storage class declares register variables which have the same
functionality as auto variables. Here, the only difference is that the compiler tries to
store these variables in the register of the microprocessor if a free register is available.
This makes the use of register variables to be much faster than that of the variables
stored in the memory during the program runtime. If a free register is unavailable,
these are then stored in the memory only. Normally few variables which are to be
accessed very frequently in a program are declared with the register keyword which
improves the running time of the program. An important point to be noted here is that
we cannot obtain the address of a register variable using pointers.
To specify the storage class for a variable, the following syntax is to be followed:
Syntax:
int a;
void autoStorageClass()
{
printf("--------------------------------");
}
void registerStorageClass()
{
printf("--------------------------------");
}
void externStorageClass()
{
printf("--------------------------------");
}
void staticStorageClass()
{
int i = 0;
printf("\nLoop started:\n");
printf("\nLoop ended:\n");
printf("--------------------------------");
}
int main()
{
// exiting
printf("\n\nStorage Classes demonstrated");
return 0;
}
Output:
Loop started:
Loop ended:
7.2 Multi-file programs
In a program consisting of many different functions, it is convenient to place each function in
a separate file, and then use the make utility to compile each file separately and link them
together to produce an executable.
There are a some rules associated with multi-file programs. As a given file is initially
compiled separately, all symbolic constants which appear in that file must be defined at its
start. All referenced library functions must be accompanied by the appropriate references to
header files. Any referenced user-defined functions must have their prototypes at the start of
the file. all global variables used in the file must be declared at its start. This usually means
that definitions for common symbolic constants, header files for common library functions,
prototypes for common user-defined functions, and declarations for common global variables
will appear in multiple files. Note that a given global variable can only be initialized in one of
its declaration statements, which is regarded as the true declaration of that variable . Indeed,
the other declarations, which we shall term definitions, must be preceded by the keyword
extern to distinguish them from the true declaration.
As an example, the program printfact.c, break it up into multiple files, each containing a
single function. The files in question are called main.c and fact.c. The listings of the two files
which make up the program are as follows:
/* main.c */
/*
Program to print factorials of all integers
between 0 and 20
*/
#include <stdio.h>
int main()
{
/* Print factorials of all integers between 0 and 10 */
for (j = 0; j <= 20; ++j)
{
factorial();
printf("j = %3d factorial(j) = %12.3e\n", j, fact);
}
return 0;
}
and
/* fact.c */
/*
Function to evaluate factorial (in floating point form)
of non-negative integer j. Result stored in variable fact.
*/
#include <stdio.h>
#include <stdlib.h>
void factorial()
{
int count;
/* Calculate factorial */
for (count = j, fact = 1.; count > 0; --count) fact *= (double) count;
return;
}
We can make use of these library functions to get the pre-defined output instead of
writing our own code to get those outputs.
These library functions are created by the persons who designed and created C
compilers.
All C standard library functions are declared in many header files which are saved as
file_name.h.
Actually, function declaration, definition for macros are given in all header files.
We are including these header files in our C program using ―#include<file_name.h>‖
command to make use of the functions those are declared in the header files.
When we include header files in our C program using ―#include<filename.h>‖
command, all C code of the header files are included in C program. Then, this C
program is compiled by compiler and executed.
List of most used header files in C programming language:
Check the below table to know all the C library functions and header files in which they
are declared.
string.h All string related functions are defined in this header file
math.h All maths related functions are defined in this header file
time.h This header file contains time and clock related functions
ctype.h All character handling functions are defined in this header file
8.1Preprocessor
8.1.1 Introduction
8.2 Features
8.3 #define and #include
8.3.1#define
8.3.2 #include
8.4 Directives and Macros
8.1 Preprocessor
8.1.1 introduction
Preprocessor was introduced to C around 1973 at the urging of Alan Snyder and also in
recognition of the usefulness of the file-inclusion mechanisms available in BCPL and PL/I.
Its original version allowed only to include files and perform simple string replacements:
#include and #define of parameterless macros. Soon after that, it was extended, mostly by
Mike Lesk and then by John Reiser, to incorporate macros with arguments and conditional
compilation.[2]
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation.
8.2 Features
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column
Inclusion of header files. These are files of declarations that can be substituted into
your program.
Macro expansion. You can define macros, which are abbreviations for arbitrary
fragments of C code, and then the C preprocessor will replace the macros with their
definitions throughout the program.
Conditional compilation. Using special preprocessing directives, you can include or
exclude parts of the program according to various conditions.
Line control. If you use a program to combine or rearrange source files into an
intermediate file which is then compiled, you can use line control to inform the
compiler of where each source line originally came from.
8.3 #define and #include
Description
In the C Programming Language, the #define directive allows the definition of macros within
your source code. These macro definitions allow constant values to be declared for use
throughout your code.
Macro definitions are not variables and cannot be changed by your program code like
variables. You generally use this syntax when creating constants that represent numbers,
strings or expressions.
Syntax
The syntax for creating a constant using #define in the C language is:
OR
The name of the constant. Most C programmers define their constant names in
uppercase, but it is not a requirement of the C Language.
value
expression
Expression whose value is assigned to the constant. The expression must be enclosed
in parentheses if it contains operators.
Note
Do NOT put a semicolon character at the end of #define statements. This is a common
mistake.
Example
Let's look at how to use #define directives with numbers, strings, and expressions.
Number
The following is an example of how you use the #define directive to define a numeric
constant:
#define AGE 10
In this example, the constant named AGE would contain the value of 10.
String
For example:
In this example, the constant called NAME would contain the value of "TechOnTheNet.com".
#include <stdio.h>
int main()
{
printf("%s is over %d years old.\n", NAME, AGE);
return 0;
}
TechOnTheNet.com
Both user and system header files are included using the preprocessing directive `#include'. It
has three variants:
#include <file>
This variant is used for system header files. It searches for a file named file in a list of
directories specified by you, then in a standard list of system directories. You specify
directories to search for header files with the command option `-I' (see section 1.9
Invoking the C Preprocessor). The option `-nostdinc' inhibits searching the standard
system directories; in this case only the directories you specify are searched.
The parsing of this form of `#include' is slightly special because comments are not
recognized within the `<...>'. Thus, in `#include <x/*y>' the `/*' does not start a
comment and the directive specifies inclusion of a system header file named `x/*y'.
Of course, a header file with such a name is unlikely to exist on Unix, where shell
wildcard features would make it hard to manipulate.
The argument file may not contain a `>' character. It may, however, contain a `<'
character.
#include "file"
This variant is used for header files of your own program. It searches for a file named
file first in the current directory, then in the same directories used for system header
files. The current directory is the directory of the current input file. It is tried first
because it is presumed to be the location of the files that the current input file refers
to. (If the `-I-' option is used, the special treatment of the current directory is
inhibited.)
The argument file may not contain `"' characters. If backslashes occur within file, they
are considered ordinary text characters, not escape characters. None of the character
escape sequences appropriate to string constants in C are processed. Thus, `#include
"x\n\\y"' specifies a filename containing three backslashes. It is not clear why this
behavior is ever useful, but the ANSI standard specifies it.
This variant is called a computed #include. Any `#include' directive whose argument
does not fit the above two forms is a computed include. The text anything else is
checked for macro calls, which are expanded (see section 1.4 Macros). When this is
done, the result must fit one of the above two variants--in particular, the expanded text
must in the end be surrounded by either quotes or angle braces.
This feature allows you to define a macro which controls the file name to be used at a
later point in the program. One application of this is to allow a site-specific
configuration file for your program to specify the names of the system include files to
be used. This can help in porting the program to various operating systems in which
the necessary system header files are found in different places.
The following section lists down all the important preprocessor directives −
#elif
8
#else and #if in one statement.
#endif
9
Ends preprocessor conditional.
#error
10
Prints error message on stderr.
#pragma
11
Issues special commands to the compiler, using a standardized method.
Preprocessors Examples
#define MAX_ARRAY_LENGTH 20
This directive tells to replace instances of MAX_ARRAY_LENGTH with 20. Use #define
for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell to get stdio.h from System Libraries and add the text to the current
source file. The next line tells to get myheader.h from the local directory and add the content
to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 45
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells to process the statements enclosed if DEBUG is defined. This is useful if you pass the
-DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so
you can turn debugging on and off on the fly during compilation.
Predefined Macros
ANSI C defines a number of macros. Although each one is available for use in programming,
the predefined macros should not be directly modified.
__DATE__
1
The current date as a character literal in "MMM DD YYYY" format.
__TIME__
2
The current time as a character literal in "HH:MM:SS" format.
__FILE__
3
This contains the current filename as a string literal.
__LINE__
4
This contains the current line number as a decimal constant.
__STDC__
5
Defined as 1 when the compiler complies with the ANSI standard.
#include <stdio.h>
int main() {
When the above code in a file test.c is compiled and executed, it produces the following
result −
File :test.c
Date :July 5 2018
Time :03:45:25
Line :8
ANSI :1
Preprocessor Operators
A macro is normally confined to a single line. The macro continuation operator (\) is used to
continue a macro that is too long for a single line. For example −
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
The stringize or number-sign operator ( '#' ), when used within a macro definition, converts a
macro parameter into a string constant. This operator may be used only in a macro having a
specified argument or parameter list. For example −
Live Demo
#include <stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
int main(void) {
message_for(C, D);
return 0;
}
When the above code is compiled and executed, it produces the following result −
The token-pasting operator (##) within a macro definition combines two arguments. It
permits two separate tokens in the macro definition to be joined into a single token. For
example −
Live Demo
#include <stdio.h>
int main(void) {
int token35 = 50;
tokenpaster(35);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Token35 = 50
It happened so because this example results in the following actual output from the
preprocessor −
This example shows the concatenation of token##n into token34 and here we have used both
stringize and token-pasting.
Live Demo
#include <stdio.h>
int main(void) {
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Parameterized Macros
One of the powerful functions is the ability to simulate functions using parameterized macros.
For example, we might have some code to square a number as follows −
int square(int y) {
return y * y;
}
Macros with arguments must be defined using the #define directive before they can use. The
argument list is enclosed in parentheses and must immediately follow the macro name.
Spaces are not allowed between the macro name and open parenthesis. For example −
Demo
#include <stdio.h>
int main(void) {
printf("Max between 30 and 20 is %d\n", MAX(20, 30));
return 0;
}
When the above code is compiled and executed, it produces the following result –
9.1Arrays
9.1.1 Introduction
9.2 Definition, processing,
9.3 passing arrays to functions,
9.4 Multidimensional arrays
9.5 arrays and strings
9.1 Arrays:
9.1.1 Introduction
Arrays a type of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is more useful
to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as num0, num1, ..., and num99, you declare
one array variable such as numbers and use num[0], num[1], and ..., num[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows −
This is called a single-dimensional array. The arraySize must be an integer constant greater
than zero and type can be any valid C data type. For example, to declare a 10-element array
called balance of type double, use this statement −
double balance[20];
You can initialize an array in C either one by one or using a single statement as follows −
The number of values between braces { } cannot be larger than the number of elements that
we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −
You will create exactly the same array as you did in the previous example. Following is an
example to assign a single element of the array −
balance[3] = 7.0;
The above statement assigns the 4th element in the array with a value of 7.0. All arrays have 0
as the index of their first element which is also called the base index and the last index of an
array will be total size of the array minus 1. Shown below is the pictorial representation of the
array we discussed above −
An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example −
The above statement will take the 10th element from the array and assign the value to salary
variable. The following example Shows how to use all the three above mentioned concepts
viz. declaration, assignment, and accessing arrays −
Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
t[0] = 100
t[1] = 101
t[2] = 102
t[3] = 103
t[4] = 104
t[5] = 105
t[6] = 106
t[7] = 107
t[8] = 108
t[9] = 109
9.3 How to pass Array to a Function in C
There are two possible ways to do so, one by using call by value and other by using call by
reference.
2. Or, we can have a pointer in the parameter list, to hold the base address of our array.
We don't return an array from functions, rather we return a pointer holding the base address
of the array to be returned. But we must, make sure that the array exists after the function
ends i.e. the array is not local to the function.
We will pass a single array element as argument to a function, a one dimensional array to a
function and a multidimensional array to a function.
We will declare and define an array of integers in main() function and pass one of the array
element to a function, which will just print the value of the element.
#include<stdio.h>
void MyArray(int a)
{
printf("%d", a);
}
Output
let's write a function to find out average of all the elements of the array and print it.
We will only send in the name of the array as argument, which is nothing but the address of
the starting element of the array, or we can say the starting memory address.
#include<stdio.h>
int main()
{
float avg;
int marks[] = {99, 90, 96, 93, 95};
avg = findAverage(marks); // name of the array is passed as argument.
printf("Average marks = %.1f", avg);
return 0;
}
94.6
9.4 Multidimensional Arrays
Multi-dimensional arrays are declared by providing more than one set of square [ ]
brackets after the variable name in the declaration statement.
One dimensional arrays do not require the dimension to be given if the array is to be
completely initialized. By analogy, multi-dimensional arrays do not require the first
dimension to be given if the array is to be completely initialized. All dimensions after
the first must be given in any case.
For two dimensional arrays, the first dimension is commonly considered to be the
number of rows, and the second dimension the number of columns. We will use this
convention when discussing two dimensional arrays.
Two dimensional arrays are considered by C/C++ to be an array of ( single
dimensional arrays ). For example, "int numbers[ 5 ][ 6 ]" would refer to a single
dimensional array of 5 elements, wherein each element is a single dimensional array
of 6 integers. By extension, "int numbers[ 12 ][ 5 ][ 6 ]" would refer to an array of
twelve elements, each of which is a two dimensional array, and so on.
Another way of looking at this is that C stores two dimensional arrays by rows, with
all elements of a row being stored together as a single unit. Knowing this can
sometimes lead to more efficient programs.
Multidimensional arrays may be completely initialized by listing all data elements
within a single pair of curly {} braces, as with single dimensional arrays.
It is better programming practice to enclose each row within a separate subset of curly
{} braces, to make the program more readable. This is required if any row other than
the last is to be partially initialized. When subsets of braces are used, the last item
within braces is not followed by a comma, but the subsets are themselves separated by
commas.
Multidimensional arrays may be partially initialized by not providing complete
initialization data. Individual rows of a multidimensional array may be partially
initialized, provided that subset braces are used.
Individual data items in a multidimensional array are accessed by fully qualifying an
array element. Alternatively, a smaller dimensional array may be accessed by
partially qualifying the array name. For example, if "data" has been declared as a
three dimensional array of floats, then data[ 1 ][ 2 ][ 5 ] would refer to a float,
data[ 1 ][ 2 ] would refer to a one-dimensional array of floats, and data[ 1 ] would
refer to a two-dimensional array of floats. The reasons for this and the incentive to do
this relate to memory-management issues that are beyond the scope of these notes.
#include <stdlib.h>
#include <stdio.h>
return 0;
}
#include<stdio.h>
int main()
{
int arr[3][3], i, j;
printf("Please enter 9 numbers for the array: \n");
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
scanf("%d", &arr[i][j]);
}
}
// passing the array as argument
displayArray(arr);
return 0;
}
Please enter 9 numbers for the array: 1 2 3 4 5 6 7 8 9 The complete array is: 1 2 3 4 5 6 7 8 9
• char s[5];
• Strings can also be declared using pointer.
char *p;
How to initialize strings?
• Here, we are trying to assign 6 characters (the last character is '\0') to a char array
having 5 characters. This is bad and you should never do this.
#include <stdio.h>
int main()
char name[20];
scanf("%s", name);
return 0;
}
• Output
Even though Anita Jaykar was entered in the above program, only ―Anita" was stored in
the name string. It's because there was a space after Anita.
You can use the gets() function to read a line of string. And, you can use puts() to display the
string.
#include <stdio.h>
int main()
char name[30];
printf("Name: ");
return 0;
Output
#include <stdio.h>
int main()
char str[50];
gets(str);
return 0;
puts(str);
string.h
• Note: Though, gets() and puts() function handle strings, both these functions are
defined in "stdio.h" header file.
Strlen ():
• In C, strlen() function calculates the length of string. It takes only one argument, i.e,
string name.
• Syntax of strlen() :
temp_variable = strlen(string_name);
#include <string.h>
int main()
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
char c[20];
gets(c);
return 0;
Strcpy()
• Function strcpy() copies the content of one string to the content of another string.
• Syntax of strcpy() :
strcpy(destination,source);
• Here, source and destination are both the name of the string. This statement, copies
the content of string source to the content of string destination.
Example of strcpy()
#include <stdio.h>
#include <string.h>
int main()
char a[10],b[10];
gets(a);
puts(b);
return 0;
strcat()
• It takes two arguments, i.e, two strings and resultant string is stored in the first string
specified in the argument.
Syntax of strcat()
• strcat(first_string,second_string);
#include <stdio.h>
#include <string.h>
int main()
strcat(str1,str2); //concatenates str1 and str2 and resultant string is stored in str1.
puts(str1);
puts(str2);
return 0;
Output :
My name is Anita.
Anita
Strcmp()
• In C programming, strcmp() compares two string and returns value 0, if the two
strings are equal.
• Function strcmp() takes two arguments, i.e, name of two string to compare.
• strcmp(string1,string2);
• #include <stdio.h>
• #include <string.h>
• int main()
• {
• char str1[30],str2[30];
• gets(str1);
• if(strcmp(str1,str2)==0)
• return 0;
• }
Output:
Exercise:
5. What do you mean by macro? What are the various predefined macros?
12. Write a program to find the largest value that is stored in the array
14. Write a program to arrange n numbers stored in the array in ascending order.-