c lecture 1

163
ALGORITHM An algorithm is any set of detailed instructions which results in a predictable end-state from a known beginning. Algorithms are only as good as the instructions given, however, and the result will be incorrect if the algorithm is not properly defined. To make a computer do anything, you have to write a computer program . To write a computer program, you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal. When you are telling the computer what to do, you also get to choose how it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done. Let's follow an example to help get an understanding of the algorithm concept. Let's say that you have a friend arriving at the airport , and your friend needs to get from the airport to your house. Here are four different algorithms that you might give your friend for getting to your home: The taxi algorithm: Go to the taxi stand. Get in a taxi. Give the driver my address. The call-me algorithm: When your plane arrives, call my cell phone . Meet me outside baggage claim . The rent-a-car algorithm: Take the shuttle to the rental car place. Rent a car. Follow the directions to get to my house. The bus algorithm:

Upload: vempadareddy

Post on 28-Dec-2015

10 views

Category:

Documents


0 download

DESCRIPTION

C language

TRANSCRIPT

Page 1: C Lecture 1

ALGORITHM

An algorithm is any set of detailed instructions which results in a predictable end-state from a known beginning. Algorithms are only as good as the instructions given, however, and the result will be incorrect if the algorithm is not properly defined.

To make a computer do anything, you have to write a computer program. To write a computer program, you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal.

When you are telling the computer what to do, you also get to choose how it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done. Let's follow an example to help get an understanding of the algorithm concept.

Let's say that you have a friend arriving at the airport, and your friend needs to get from the airport to your house. Here are four different algorithms that you might give your friend for getting to your home:

← The taxi algorithm: Go to the taxi stand. Get in a taxi. Give the driver my address.

← The call-me algorithm: When your plane arrives, call my cell phone. Meet me outside baggage claim.

← The rent-a-car algorithm: Take the shuttle to the rental car place. Rent a car. Follow the directions to get to my house.

← The bus algorithm: Outside baggage claim, catch bus number 70. Transfer to bus 14 on Main Street. Get off on Elm street. Walk two blocks north to my house.

All four of these algorithms accomplish exactly the same goal, but each algorithm does it in completely different way.

Each algorithm also has a different cost and a different travel time. Taking a taxi, for example, is probably the fastest way, but also the most expensive. Taking the

Page 2: C Lecture 1

bus is definitely less expensive, but a whole lot slower. You choose the algorithm based on the circumstances.

In computer programming, there are often many different ways -- algorithms -- to accomplish any given task. Each algorithm has advantages and disadvantages in different situations.

PSEUDOCODE

An outline of a program, written in a form that can easily be converted into real programming statements .

For example, the pseudocode

If student's grade is greater than or equal to 60 Print "passed"

else Print "failed"

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

initialize passes to zero initialize failures to zero initialize student to one while student counter is less than or equal to ten

input the next exam result if the student passed

add one to passes else

add one to failures add one to student counter print the number of passes print the number of failures if eight or more students passed

print "raise tuition"------------------------------------------------

Some Keywords that should be used

For looping and selection, The keywords that are to be used include Do While...EndDo; Do Until...Enddo; Case...EndCase; If...Endif; Call ... with (parameters); Call; Return ....; Return; When; Always use scope terminators for loops and iteration.

As verbs, use the words Generate, Compute, Process, etc. Words such as set, reset, increment, compute, calculate, add, sum, multiply, ... print, display, input,

Page 3: C Lecture 1

output, edit, test , etc. with careful indentation tend to foster desirable pseudocode.

Do not include data declarations in your pseudocode.

Pseudocode (pronounced SOO-doh-kohd) is a detailed yet readable description of what a computer program or algorithm must do, expressed in a formally-styled natural language rather than in a programming language. Pseudocode is sometimes used as a detailed step in the process of developing a program. It allows designers or lead programmers to express the design in great detail and provides programmers a detailed template for the next step of writing code in a specific programming language.

Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules. It is simply one step - an important one - in producing the final code. The benefit of pseudocode is that it enables the programmer to concentrate on the algorithms without worrying about all the syntactic details of a particular programming language. In fact, you can write pseudocode without even knowing what programming language

Because pseudocode is detailed yet readable, it can be inspected by the team of designers and programmers as a way to ensure that actual programming is likely to match design specifications. Catching errors at the pseudocode stage is less costly than catching them later in the development process. Once the pseudocode is accepted, it is rewritten using the vocabulary and syntax of a programming language.

FLOWCHART

The flowchart is a means of visually presenting the flow of data through an information processing systems, the operations performed within the system and the sequence in which they are performed.

The program flowchart can be likened to the blueprint of a building. As we know a designer draws a blueprint before starting construction on a building. Similarly, a programmer prefers to draw a flowchart prior to writing a computer program. As in the case of the drawing of a blueprint, the flowchart is drawn according to defined rules and using standard flowchart symbols

A flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem. Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts facilitate communication between programmers and business people. These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the

Page 4: C Lecture 1

flowchart is drawn, it becomes easy to write the program in any high level language. Often we see how flowcharts are helpful in explaining the program to others. Hence, it is correct to say that a flowchart is a must for the better documentation of a complex program.

Flowcharts are usually drawn using some standard symbols; however, some special symbols can also be developed when required. Some standard symbols, which are frequently required for flowcharting many computer programs are shown in Fig. 25.1

Start or end of the program

Computational steps or processing function of a programInput or output operation

Decision making and branching

Connector or joining of two parts of program

Magnetic TapeMagnetic Disk

Off-page connector

Flow line

Annotation

Display

The following are some guidelines in flowcharting:

a. In drawing a proper flowchart, all necessary requirements should be listed out in logical order.

Page 5: C Lecture 1

b. The flowchart should be clear, neat and easy to follow. There should not be any room for ambiguity in understanding the flowchart.

c. The usual direction of the flow of a procedure or system is from left to right or top to bottom.

d. Only one flow line should come out from a process symbol.

  or       

e. Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible answer, should leave the decision symbol.

             

f. Only one flow line is used in conjunction with terminal symbol.

                

g. Write within standard symbols briefly. As necessary, you can use the annotation symbol to describe data or computational steps more clearly.

h. If the flowchart becomes complex, it is better to use connector symbols to reduce the number of flow lines. Avoid the intersection of flow lines if you want to make it more effective and better way of communication.

i. Ensure that the flowchart has a logical start and finish. j. It is useful to test the validity of the flowchart by passing through it with a

simple test data.

ADVANTAGES OF USING FLOWCHARTS

The benefits of flowcharts are as follows:

Page 6: C Lecture 1

1. Communication: Flowcharts are better way of communicating the logic of a system to all concerned.

2. Effective analysis: With the help of flowchart, problem can be analysed in more effective way.

3. Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes.

4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase.

5. Proper Debugging: The flowchart helps in debugging process. 6. Efficient Program Maintenance: The maintenance of operating program

becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part

LIMITATIONS OF USING FLOWCHARTS

1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and clumsy.

2. Alterations and Modifications: If alterations are required the flowchart may require re-drawing completely.

3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.

4. The essentials of what is done can easily be lost in the technical details of how it is done.

Examples:

Draw a flowchart to find the sum of first 50 natural numbers.

Page 7: C Lecture 1

Draw a flowchart to find the largest of three numbers A,B, and C.

Page 8: C Lecture 1

Example 3

Draw a flowchart for computing factorial N (N!)

Where N! = 1 ´ 2 ´ 3 ´ …… N .

Page 9: C Lecture 1

Assignment :

Algorithm and flowchart to find the roots of quadratic equation ax2+bx+c=0 for all cases

Algorithm and flowchart for finding maximum and minimum of given n numbers

Algorithm and flowchart to generate Fibonacci numbers up to n

In mathematics, the Fibonacci numbers are the numbers in the following sequence:

By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two.

Page 10: C Lecture 1

COMPILERS and INTERPRETERS

A compiler is a special program that processes statements written in a particular programming language and turns them into machine language or "code" that a computer's processor uses.

Typically, a programmer writes language statements in a language such as Pascal or C one line at a time using an editor. The file that is created contains what are called the source statements . The programmer then runs the appropriate language compiler, specifying the name of the file that contains the source statements.

When executing (running), the compiler first parses (or analyzes) all of the language statements syntactically one after the other and then, in one or more successive stages or "passes", builds the output code, making sure that statements that refer to other statements are referred to correctly in the final code.

Traditionally, the output of the compilation has been called object code or sometimes an object module . (Note that the term "object" here is not related to object-oriented programming .) The object code is machine code that the processor can process or "execute" one instruction at a time.

More recently, the Java programming language, a language used in object-oriented programming ,has introduced the possibility of compiling output (called bytecode ) that can run on any computer system platform for which a Java virtual machine or bytecode interpreter is provided to convert the bytecode into instructions that can be executed by the actual hardware processor. Using this virtual machine, the bytecode can optionally be recompiled at the execution platform by a just-in-time compiler .

Thus, a compiler differs from an interpreter, which analyzes and executes each line of source code in succession, without looking at the entire program. The advantage of interpreters is that they can execute a program immediately. Compilers require some time before an executable program emerges. However, programs produced by compilers run much faster than the same programs executed by an interpreter.

An interpreter translates high-level instructions into an intermediate form, which it then executes. In contrast, a compiler translates high-level instructions directly into machine language. Compiled programs generally run faster than interpreted programs. The advantage of an interpreter, however, is that it does not need to go through the compilation stage during which machine instructions are

Page 11: C Lecture 1

generated. This process can be time-consuming if the program is long. The interpreter, on the other hand, can immediately execute high-level programs. For this reason, interpreters are sometimes used during the development of a program, when a programmer wants to add small sections at a time and test them quickly. In addition, interpreters are often used in education because they allow students to program interactively.

C COMPILERS

Compiler   Windows  UNIX-like  

Other OSs  License type  

IDE?  

AMPC Yes Yes Yes Proprietary YesAmsterdam Compiler Kit

No Yes YesOpen Source (BSD)

No

Clang Yes Yes YesOpen Source (BSD)

No

GCC C Yes Yes

Yes IBM mainfraime, AmigaOS, VAX/VMS,

RTEMS

Open source No

LabWindows/CVI Yes Yes Yes Proprietary Yes

lcc Yes Yes YesProprietary (open-source freeware)

Windows

Nwcc Yes Yes Yes Open source NoOpen64 Yes Yes Yes Open source NoPelles C Yes No No Freeware YesPortable C Compiler

Yes Yes YesOpen source (BSD)

No

SAS/C Yes Yes

Yes IBM mainframe,

AmigaOS, 68K, 88K, Unix

Proprietary Yes

Tiny C Compiler Yes Yes No Open source NoCCS C Compiler Yes Yes No Proprietary Yesups debugger [1] (includes C interpreter)

No YesYes Solaris,

SunOSOpen source Yes

VBCC Yes Yes Yes Open Source No

C/C++ compilers

Compiler   Windows   UNIX- Other License type   IDE?  

Page 12: C Lecture 1

like   OSs  C++ Builder Yes No No Proprietary YesAMD x86 Open64 Compiler Suite

 ?  ?  ?  ?  ?

Turbo C++ Explorer

Yes No No Freeware Yes

C++ Compiler Yes No No Freeware NoCh interpreter Yes Yes  ? Freeware YesCode::Block[2] Yes Yes Yes Open-Source Yes

CINT Yes Yes

Yes Solaris, BeBox, MS-

DOS, Convex, etc.

X11/MIT license Yes

Borland C++ Yes No DOS Proprietary YesTurbo C++ for DOS

No No DOS Proprietary Yes

Clang Yes Yes Yes Open source NoCodeWarrior Yes Yes Yes  ? YesComeau C/C++ Yes Yes Yes Proprietary  ?CoSy compiler development system

Yes Yes No Proprietary No

Digital Mars Yes No DOS Proprietary YesDjgpp No No DOS Open source NoEDGE ARM C/C++

Yes Yes Yes Proprietary Yes

MinGW Yes No No Open source No

GCC Yes Yes Yes Open source

Yes Apple Xcode for

Mac OS X, Eclipse

HP aC++ No Yes No Proprietary NoIAR C/C++ Compilers

Yes No No Proprietary Yes

Intel C++ Compiler

Yes Yes Yes Proprietary Yes

KAI C++ Compiler

 ?  ?  ?  ?  ?

Microtec Yes Yes Yes Proprietary YesMULTI Yes Yes Yes Proprietary YesOpen Watcom Yes No Yes Open source YesOpen64 Yes Yes Yes Open source No

Page 13: C Lecture 1

PathScale No Yes NoProprietary/Open source

No

PGI Workstation Yes Yes No Proprietary YesProDev WorkShop

No No Yes Proprietary Yes

RealView C/C++ Compiler (armcc)

Yes Yes  ? Proprietary Yes

SAS/C C++  ?  ?IBM mainframe

Proprietary  ?

Sun Studio No Yes Yes Proprietary YesTenDRA No Yes No Open source NoVectorC Yes No No Proprietary NoVisual C++ Yes No No Proprietary YesVisual C++ Express

Yes No No Freeware Yes

VisualAge C++ Yes AIX OS/2 Proprietary YesXL C/C++ No Yes Yes Proprietary NoWind River (Diab) Compiler

Yes Yes Yes Proprietary Yes

Linker (computing)

In computer science, a linker or link editor is a program that takes one or more objects generated by a compiler and combines them into a single executable program.

Computer programs typically comprise several parts or modules; all these parts/modules need not be contained within a single object file, and in such case refer to each other by means of symbols. Typically, an object file can contain three kinds of symbols:

defined symbols, which allow it to be called by other modules, undefined symbols, which call the other modules where these symbols are

defined, and local symbols, used internally within the object file to facilitate relocation.

When a program comprises multiple object files, the linker combines these files into a unified executable program, resolving the symbols as it goes along.

Linkers can take objects from a collection called a library. Some linkers do not include the whole library in the output; they only include its symbols that are referenced from other object files or libraries. Libraries exist for diverse purposes, and one or more system libraries are usually linked in by default.

Page 14: C Lecture 1

The linker also takes care of arranging the objects in a program's address space. This may involve relocating code that assumes a specific base address to another base. Since a compiler seldom knows where an object will reside, it often assumes a fixed base location (for example, zero). Relocating machine code may involve re-targeting of absolute jumps, loads and stores.

The executable output by the linker may need another relocation pass when it is finally loaded into memory (just before execution). This pass is usually omitted on hardware offering virtual memory — every program is put into its own address space, so there is no conflict even if all programs load at the same base address. This pass may also be omitted if the executable is a position independent executable.

The GNU Compiler Collection (usually shortened to GCC) ,Originally named the GNU C Compiler, because it only handled the C programming language, GCC 1.0 was released in 1987, and the compiler was extended to compile C++ in December of that year

TURBO C COMPILER

Turbo C++ was a C++ compiler and integrated development environment (IDE) originally from Borland. Most recently it was distributed by Embarcadero Technologies, which acquired all of Borland's compiler tools

Turbo C++ v1.01 and Turbo C v2.0 can be downloaded, free of charge, from Borland's Antique Software website

C PROGRAMMING LANGUAGE HISTORY

The development of Unix in the C language made it uniquely portable and improvable.

The first version of Unix was written in the low-level PDP-7 assembler language. Soon after, a language called TMG was created for the PDP-7 by R. M. McClure. Using TMG to develop a FORTRAN compiler, Ken Thompson instead ended up developing a compiler for a new high-level language he called B, based on the earlier BCPL language developed by Martin Richard.

When the PDP-11 computer arrived at Bell Labs, Dennis Ritchie built on B to create a new language called C which inherited Thompson's taste for concise syntax, and had a powerful mix of high-level functionality and the detailed features required to program an operating system. Most of the components of Unix were eventually rewritten in C, culminating with the kernel itself in 1973. Because of its convenience and power, C went on to become the most popular programming language in the world over the next quarter century.

Page 15: C Lecture 1

This development of Unix in C had two important consequences:

Portability . It made it much easier to port Unix to newly developed computers, because it eliminated the need to translate the entire operating system to the new assemble language by hand:

o First, write a C-to-assembly language compiler for the new machine.

o Then use the new compiler to automatically translate the Unix C language source code into the new machine's assembly language.

o Finally, write only a small amount of new code where absolutely required by hardware differences with the new machine.

Improvability . It made Unix easy to customize and improve by any programmer that could learn the high-level C programming language. Many did learn C, and went on to experiment with modifications to the operating system, producing many useful new extensions and enhancements.

What is the advantages of c language?

Speed of the resulting application. C source code can be optimized much more than higher-level languages because the language set is relatively small and very efficient .It is about as close as you can get to programming in assembly language, without programming in assembly language .Heck you can even use assembly and C together!

That leads to a second advantage that C has which is its application in Firmware programming (hardware). That is due to its ability to use/work with assembly and communicate directly with controllers, processors and other devices.

C is a building bock for many other currently known languages. Look up the history of C and you will find that it has been around for some time . Take a look at Python for example a fully Object-Oriented High-Level programming language. It is written in C (perhaps C++ too). That tells you if you ever want to know what is going on under the hood in other languages; understanding C and how it works is essential.

C is a compiled language versus an interpreted language. Explained simply, this means that the code is compacted into executable instruction (in the case of windows anyway) rather than being "translated" on the fly at run time. This feature also lends heavily to the speed of C programs.

Page 16: C Lecture 1

DISADVANTAGES OF C ARE:

1. There is no runtime checking.

2.There is no strict type checking(for ex:we can pass an integer value for the floating data type).

3. As the program extends it is very difficult to fix the bugs.

FEATURES OF C

C has facilities for structured programming and allows lexical variable scope and recursion, while a static type system prevents many unintended operations. In C, all executable code is contained within functions. Function parameters are always passed by value. Pass-by-reference is simulated in C by explicitly passing pointer values. C also exhibits the following more specific characteristics:

variables may be hidden in nested blocks partially weak typing; for instance, characters can be used as integers low-level access to computer memory by converting machine addresses

to typed pointers function and data pointers supporting ad hoc run-time polymorphism array indexing as a secondary notion, defined in terms of pointer

arithmetic a preprocessor for macro definition, source code file inclusion, and

conditional compilation complex functionality such as I/O, string manipulation, and mathematical

functions consistently delegated to library routines A relatively small set of reserved keywords

o A lexical structure that resembles B more than ALGOL

Absent features

The relatively low-level nature of the language affords the programmer close control over what the computer does, while allowing special tailoring and aggressive optimization for a particular platform. This allows the code to run efficiently on very limited hardware, such as embedded systems.

C does not have some features that are available in some other programming languages:

No nested function definitions No direct assignment of arrays or strings (copying can be done via

standard functions; assignment of objects having struct or union type is supported)

No automatic garbage collection

Page 17: C Lecture 1

No requirement for bounds checking of arrays No operations on whole arrays No syntax for ranges, such as the A..B notation used in several languages Prior to C99, no separate Boolean type (zero/nonzero is used instead)[6] No formal closures or functions as parameters (only function and variable

pointers) No generators or coroutines; intra-thread control flow consists of nested

function calls, except for the use of the longjmp or setcontext library functions

No exception handling; standard library functions signify error conditions with the global errno variable and/or special return values, and library functions provide non-local gotos

Only rudimentary support for modular programming No compile-time polymorphism in the form of function or operator

overloading Very limited support for object-oriented programming with regard to

polymorphism and inheritance Limited support for encapsulation No native support for multithreading and networking No standard libraries for computer graphics and several other application

programming needs

STRUCTURE OF A C PROGRAM

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

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

A C program basically has the following form:

← Preprocessor Commands← Functions

← Variables

← Statements & Expressions

← Comments

Basic structure of a C program is:

Page 18: C Lecture 1

/* Documentation section *//* Link section *//* Definition section *//* Global declaretion section *//* Function section */(return type) (function name) (arguments...)void main() { Declaration partExecutable part (statements) }/* Sub-program section */(return type) (function name 1) (arguments...)(return type) (function name 2) (arguments...). . .(return type) (function name n) (arguments...)

________________________________________________________________

The following program is written in the C programming language. Open a text file hello.c using vi editor and put the following lines inside that file.

#include <stdio.h>

int main(){ /* My first program */ printf("Hello, World! \n"); return 0;// return interger value zero}

NOTE: In computer programming, a return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called — known as its return address. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.

If a function does not have a return type (i.e., its return type is void), the return statement can be used without a value, in which case the program just breaks out of the current function and returns to the calling one.

Page 19: C Lecture 1

exit(0)

This causes the program to exit with a successful termination.

exit(1)

This causes the program to exit with a system-specific meaning.

On many systems, exit(1) signals some sort of failure, however thereis no guarantee.

As I recall, the C standard only recognizes three standard exitvalues:

EXIT_SUCCESS -- successful terminationEXIT_FAILURE -- unsuccessful termination0 -- same as EXIT_SUCCESS

_____________________________________________________________

Preprocessor Commands: These commands tells the compiler to do preprocessing before doing actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. You will learn more about C Preprocessors in C Preprocessors session.

Functions: are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. This function is prefixed with keyword int which means this function returns an integer value when it exits. This integer value is retured using return statement.

The C Programming language provides a set of built-in functions. In the above example printf() is a C built-in function which is used to print anything on the screen.

Variables: are used to hold numbers, strings and complex data for manipulation..

Statements & Expressions : Expressions combine variables and constants to create new values. Statements are expressions,

Page 20: C Lecture 1

assignments, function calls, or control flow statements which make up C programs

Comments: are used to give additional useful information inside a C Program. All the comments will be put inside /*...*/ as given in the example above. A comment can span through multiple lines.

Note the followings

C is a case sensitive programming language. It means in C printf and Printf will have different meanings.

C has a free-form line structure. End of each C statement must be marked with a semicolon.

Multiple statements can be one the same line.

White Spaces (ie tab space and space bar ) are ignored.

Statements can continue over multiple lines.

C Program Compilation

To compile a C program you would have to Compiler name and program files name. Assuming your compiler's name is cc and program file name is hello.c, give following command at Unix prompt.

$cc hello.c

This will produce a binary file called a.out and an object file hello.o in your current directory.

Here a.out is your first program which you will run at Unix prompt like any other system program. If you don't like the name a.out then you can produce a binary file with your own name by using -o option while compiling C program. See an example below

$cc -o hello hello.c

Now you will get a binary with name hello. Execute this program at Unix prompt but before executing / running this program make sure that it has execute permission set. If you don't know what is execute permission then just follow these two steps

$chmod 755 hello$./hello

Page 21: C Lecture 1

This will produce following resultHello, World

The skeleton of a simple C program is given below :

main() {

statement 1 ; statement 2 ;

} function1() {

variable declarations; statement 1; statement 2;

}

·         A C program is nothing but a collection of one or more functions. A function name is always followed by a pair of parenthesis, as in case of main().

·         Every program must have a special function named main(). The program execution starts from this function.

·         The group of statements within main() are executed sequentially. The closing brace of the main() function signals the end of the program. When this brace is reached, the program execution stops and the control is handed over to the operating system.

·         There should be a main() function somewhere in the program so that the computer can determine where to start the execution.

·         The main() function can be located anywhere in the program, but the general practice is to place it as the first function for better readability.

WRITING YOUR FIRST C PROGRAM  

The following is a simple C program that prints a message ‘Hello, world’ on the screen.

Page 22: C Lecture 1

/*

Author: JNTUDate: 13/10/2009Purpose: This program prints a message

*/

1.#include<stdio.h>2.main()3.{4.  printf(“Hello, world”);5.}

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

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

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

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

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

Page 23: C Lecture 1

UNDERSTANDING THE PROGRAM

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

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

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

Thus, the statement ‘#include<stdio.h>’ effectively inserts the file ‘stdio.h’ into the file hello.c making functions contained in the ‘stdio.h’ file available to the programmer.

For example, one of the statements in the file ‘stdio.h’ provides the information that a function printf() exists, and can accept a string (a set of characters enclosed within the double quotes).

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

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

The statement printf() enclosed within the braces‘{}’ informs the compiler to print (on the screen) the message enclosed between the pair of double quotes.

In this case, ‘Hello, world’ is printed. As mentioned earlier, the statement printf() is a built-in function shipped along with the C compiler. Many other built-in functions are available that perform specific tasks. The power of C lies in these functions. 

Be cautious about errors! 

Errors/bugs are very common while developing a program. If you don't detect them and correct them, they cause a program to produce wrong results.

There are three types of errors — syntax, logical, and run-time errors. Let us look at them: 

Page 24: C Lecture 1

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

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

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

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

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

a. when you instruct your computer to divide a number by zero. b. when you instruct your computer to find logarithm of a

negative number. c. when you instruct your computer to find the square root of a

negative integer.

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

Assignment

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

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

Every C program must contain a main function , since the main function is the rst function called when you run your program at the command line.

In its simplest form, a C program is given byint main(void) {printf(‘‘Hello world!\n’’);}The int stands for the \return type", which says that the main function returns an integer if you tell it to do so. We will get into more detail with functions and return types, but you can return a number to the command line with the return function in C, as in

Page 25: C Lecture 1

int main(void) {printf(‘‘Hello world!\n’’);return 2;}

When you compile and run your program, it will return a 2 to the command line, that you can access with the $? character, which stores the value returned by the last command executed, as in

$ ./a.outHello world!$ echo $?2

Just as in shell scripts, you can specify exit codes in C as well, which perform the same function as the return function in the previous example:

int main(void) {printf(‘‘Hello world!\n’’);exit(2);}

Compiling and running this example yields the same result as the previous example. The void statement in main(void) tells the main function that there are no arguments being supplied to it at the command line. Note that all statements in C programs end with the semicolon ; except for the prepro-cessor directives that begin with #.

How C program works

The jump to the object oriented C++ language becomes much easier. C++ is an extension of C, and it is nearly impossible to learn C++ without learning C first.

What is C?

Page 26: C Lecture 1

C is what is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an executable that the computer can run (execute).

The C program is the human-readable form, while the executable that comes out of the compiler is the machine-readable and executable form. What this means is that to write and run a C program, you must have access to a C compiler.

If you are using a UNIX machine (for example, if you are writing CGI scripts in C on your host's UNIX computer, or if you are a student working on a lab's UNIX machine), the C compiler is available for free. It is called either "cc" or "gcc" and is available on the command line.

If you are a student, then the school will likely provide you with a compiler -- find out what the school is using and learn about it. If you are working at home on a Windows machine, you are going to need to download a free C compiler or purchase a commercial compiler.

On a UNIX machine, type gcc samp.c -o samp (if gcc does not work, try cc). This line invokes the C compiler called gcc, asks it to compile samp.c and asks it

Page 27: C Lecture 1

to place the executable file it creates under the name samp. To run the program, type samp (or, on some UNIX machines, ./samp).

←← On a DOS or Windows machine using DJGPP, at an MS-DOS prompt

type gcc samp.c -o samp.exe. This line invokes the C compiler called gcc, asks it to compile samp.c and asks it to place the executable file it creates under the name samp.exe. To run the program, type samp.

←← If you are working with some other compiler or development system, read

and follow the directions for the compiler you are using to compile and execute the program.

If you mistype the program, it either will not compile or it will not run. If the program does not compile or does not run correctly, edit it again and see where you went wrong in your typing. Fix the error and try again.

← This C program starts with #include <stdio.h>. This line includes the "standard I/O library" into your program. The standard I/O library lets you read input from the keyboard (called "standard in"), write output to the screen (called "standard out"), process text files stored on the disk, and so on. It is an extremely useful library. C has a large number of standard libraries like stdio, including string, time and math libraries.

←← A library is simply a package of code that someone else has written to

make your life easier (we'll discuss libraries a bit later). ←← The line int main() declares the main function. Every C program must

have a function named main somewhere in the code. We will learn more about functions shortly. At run time, program execution starts at the first line of the main function.

← In C, the { and } symbols mark the beginning and end of a block of code. In this case, the block of code making up the main function contains two lines.

←← The printf statement in C allows you to send output to standard out (for

us, the screen). The portion in quotes is called the format string and describes how the data is to be formatted when printed. The format string can contain string literals such as "This is output from my first program!," symbols for carriage returns (\n), and operators as placeholders for variables (see below).

←← If you are using UNIX, you can type man 3 printf to get complete

documentation for the printf function. If not, see the documentation included with your compiler for details about the printf function.

← The return 0; line causes the function to return an error code of 0 (no error) to the shell that started execution.

Page 28: C Lecture 1

Header file

In computing, header files are a feature of some programming languages (most famously C and C++) that allows programmers to separate certain elements of a program's source code into reusable files.

Header files commonly contain forward declarations of classes, subroutines, variables, and other identifiers. Programmers who wish to declare standardized identifiers in more than one source file can place such identifiers in a single header file, which other code can then include whenever the header contents are required. The C standard library traditionally declare their standard functions in header files.

Newer compiled languages (such as Java, C#) do not use forward declarations; identifiers are recognized automatically from source files and read directly from dynamic library symbols. This means header files are not needed.

In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, or a function) for which the programmer has not yet given a complete definition. but at some point the programmer would still have to provide definitions for the declared entities.

struct person; int elements[]; void print(int);

After processing these declarations, the compiler would allow the programmer to refer to the entities person, elements and print in the rest of the program

struct person{ const char *name; char sex; int age;}; int elements[10]; void print(int x) { printf("%d\n", x);}

the following are some of the header files in c:

Page 29: C Lecture 1

#include<stdio.h>#include<string.h>#include<math.h>#include<stdlib.h>#include<floats.h>#include<conio.h>#include<time.h>

#include<limits.h>#include<graphic.h>#include<ctype.h>

#include<malloc.h>#include<calloc.h>#include<sound.h>

there are about 32 header files in c

A header file is used to define constants, variables, macro's and functions that may be common to several applications. When a system consists of multiple applications that all access the same data it becomes essential that each application uses identical definitions and it is safer for all of those applications to use the same methods to read that data. updating data should only be performed by a single function, from a single application, but reading data can be safely performed by using the common defintions found in header files.

A header file is a file containing C declarations and macro definitions to be shared between several source files. You request the use of a header file in your program by including it, with the C preprocessing directive `#include'.

Header files serve two purposes.

System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries.

Your own header files contain declarations for interfaces between the source files of your program. Each time you have a group of related declarations and macro definitions all or most of which are needed in several different source files, it is a good idea to create a header file for them.

Including a header file produces the same results as copying the header file into each source file that needs it. Such copying would be time-consuming and error-prone. With a header file, the related declarations appear in only one place. If they need to be changed, they can be changed in one place, and programs that include the header file will automatically use the new version when next recompiled.

Page 30: C Lecture 1

The header file eliminates the labor of finding and changing all the copies as well as the risk that a failure to find one copy will result in inconsistencies within a program.

In C, the usual convention is to give header files names that end with .h. It is most portable to use only letters, digits, dashes, and underscores in header file names, and at most one dot.

Both user and system header files are included using the preprocessing directive `#include'. It has two variants:

#include <file> This variant is used for system header files. It searches for a file named file in a standard list of system directories. You can prepend directories to this list with the -I option.

#include "file" This variant is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. You can prepend directories to the list of quote directories with the -iquote option.

The argument of `#include', whether delimited with quote marks or angle brackets, behaves like a string constant in that comments are not recognized, and macro names are not expanded. Thus, #include <x/*y> specifies inclusion of a system header file named x/*y.

C library headers

Name Description

<assert.h>Contains the assert macro, used to assist with detecting logical errors and other types of bug in debugging versions of a program.

<complex.h> A set of functions for manipulating complex numbers.

<ctype.h>

Contains functions used to classify characters by their types or to convert between upper and lower case in a way that is independent of the used character set (typically ASCII or one of its extensions, although implementations utilizing EBCDIC are also known).

Page 31: C Lecture 1

<errno.h> For testing error codes reported by library functions.

<fenv.h> For controlling floating-point environment.

<float.h>

Contains defined constants specifying the implementation-specific properties of the floating-point library, such as the minimum difference between two different floating-point numbers (_EPSILON), the maximum number of digits of accuracy (_DIG) and the range of numbers which can be represented (_MIN, _MAX).

<inttypes.h> For precise conversion between integer types.

<iso646.h> For programming in ISO 646 variant character sets.

<limits.h>Contains defined constants specifying the implementation-specific properties of the integer types, such as the range of numbers which can be represented (_MIN, _MAX).

<locale.h>For setlocale and related constants. This is used to choose an appropriate locale.

<math.h> For computing common mathematical functions.

<setjmp.h>Declares the macros setjmp and longjmp, which are used for non-local exits.

<signal.h> For controlling various exceptional conditions.

<stdarg.h> For accessing a varying number of arguments passed to functions.

<stdbool.h> For a boolean data type.

Page 32: C Lecture 1

<stdint.h> For defining various integer types.

<stddef.h> For defining several useful types and macros.

<stdio.h>Provides the core input and output capabilities of the C language. This file includes the venerable printf function.

<stdlib.h>For performing a variety of operations, including conversion, pseudo-random numbers, memory allocation, process control, environment, signalling, searching, and sorting.

<string.h> For manipulating several kinds of strings.

<tgmath.h> For type-generic mathematical functions.

<time.h> For converting between various time and date formats.

<wchar.h>For manipulating wide streams and several kinds of strings using wide characters - key to supporting a range of languages.

<wctype.h> For classifying wide characters.

C standard library

The C standard library consists of a set of sections of the ISO C standard which describe a collection of header files and library routines used to implement common operations, such as input/output and string handling, in the C programming language.

The C standard library is an interface standard described by a document; it is not an actual library of software routines available for linkage to C programs. No such implementation is properly called C standard library.

Page 33: C Lecture 1

The term C runtime library is used on some platforms to refer to a set of base libraries, which may be distributed in dynamically linkable form with an operating system (with or without header files), or distributed with a C compiler.

Another term sometimes used is libc. Not just any library is called the run-time library; run time in this context means the run-time support package associated with a compiler which is understood to make a language complete. The run-time support provides not only the C standard library functions, but possibly other material needed to create an environment for the C program, such as initialization prior to the invocation of the main function, or subroutines to provide arithmetic operations missing from the CPU that are needed by code generated by the C compiler.

WHAT IS A GLOBAL DECLARATION?

A global declaration of a function or variable is a declaration that is at the global scope of the program, not inside another function. This means that the name will be visible within all functions in the program.

THE MAIN FUNCTION AND PROGRAM EXECUTION

Every C program has a primary (main) function that must be named main. If your code adheres to the Unicode programming model, you can use the wide-character version of main, wmain. The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program. A program usually stops executing at the end of main, although it can terminate at other points in the program for a variety of reasons. At times, perhaps when a certain error is detected, you may want to force the termination of a program. To do so, use the exit function.

MAIN FUNCTION IN C IS A USER-DEFINED FUNCTION. No doubt it is a rule that without main function C program can not be compiled means that Main function is just to inform compiler about starting of program which is pre-defined in C.

DON'T BE CONFUSED BETWEEN THE PRE-DEFINED STATEMENT AND PRE-DEFINED FUNCTION.

PRE-DEFINED STATEMENT IS PROGRAM STARTS WITH MAIN FUNCTION AND PRE-DEFINED FUNCTIONS ARE THE FUNCTIONS WHICH ARE TOTALLY DEFINED IN LIBRARY/HEADER FILE.

Functions within the source program perform one or more specific tasks. The main function can call these functions to perform their respective tasks. When main calls another function, it passes execution control to the function, so that execution begins at the first statement in the function. A function returns control

Page 34: C Lecture 1

to main when a return statement is executed or when the end of the function is reached.

You can declare any function, including main, to have parameters. The term "parameter" or "formal parameter" refers to the identifier that receives a value passed to a function. When one function calls another, the called function receives values for its parameters from the calling function. These values are called "arguments." You can declare formal parameters to main so that it can receive arguments from the command line using this format

When you want to pass information to the main function, the parameters are traditionally named argc and argv, although the C compiler does not require these names. The types for argc and argv are defined by the C language. Traditionally, if a third parameter is passed to main, that parameter is named envp.

******In C, main() cannot return anything other than an int.Something likevoid main() is illegal. There are only three valid return values from main() - 0, EXIT_SUCCESS, and EXIT_FAILURE

The C preprocessor (cpp) is the preprocessor for the C programming language. In many C implementations, it is a separate program invoked by the compiler as the first part of translation. The preprocessor handles directives for source file inclusion (#include), macro definitions (#define), and conditional inclusion (#if).

WHAT ARE MACROS?

Macros, which are special lines/fragments of code, differ from any other code written in the source files in the aspect that it's not passed to the compiler (either for the purpose of encoding into machine instructions, or some intermediate form instructions). Instead, macros perform textual manipulations on the source code before passing it to the compiler, where this process preliminary to compiling the source files is called "preprocessing", and the software component responsible of doing it is called the "preprocessor". Henceforth, macros are usually defined as "preprocessor directives", where a segment of code is replaced by the results of the macro processing before passing the source code to the compiler. A very valuable technique to gain a thorough understanding of the operation of macros in any environment is to learn how to obtained the preprocessed source code, and see how the macro directives are expanded.

In C and C++, a Macro is a piece of text that is expanded by the preprocessor part of the compiler. This is used in to expand text before compiling.

#define VALUE 10

Page 35: C Lecture 1

Everywhere that VALUE is used the number of 10 will be used instead.

int fred[VALUE];

#define A 2#define B 3#define C A + B

It is better to use constants with const instead of the #define macro.

NESTED COMMENTS

In the following program, the second printf() is a comment:

#include <stdio.h> int main(void) { printf("This program has a comment.\n"); /* printf("This is a comment line and will not print.\n"); */ return 0; }

Because the second printf() is equivalent to a space, the output of this program is:

This program has a comment.

Because the comment delimiters are inside a string literal, printf() in the following program is not a comment.

#include <stdio.h> int main(void)  { printf("This program does not have \ /* NOT A COMMENT */ a comment.\n"); return 0;  }

The output of the program is:

This program does not have/* NOT A COMMENT */ a comment.

Page 36: C Lecture 1

You can nest single line comments within C-style comments. For example, the following program will not output anything:

#include <stdio.h> int main(void)  { /* printf("This line will not print.\n"); // This is a single line comment // This is another single line comment printf("This line will also not print.\n"); */ return 0;\\  }

RULES IN C PROGRAMMING LANGUAGE

Here are some of the syntax rules in C Programming

that must be familiarize:

a.  Put semicolon at the end of variable declaration.

b.  Commas should be used to separate variables.

c.  Variables should be declared first before it can be used.

d.  An identifier must not begin with a digit.

e.  An identifier must consist only of letters, digits, or underscores.

f.  An identifier defined in a C standard library must not be redefined.

g. C reserved words cannot be used as an identifier.

h. In using the scanf function the order of the placeholders must correspond to the order of the variables in the input list.

C PROGRAM COMPILATION STEPS?

Page 37: C Lecture 1

There are 6 steps

1. Pre-processor - which replaces macros 2. Code will be separated from comments 3. syntax error will be given - types of parsing 4. compilation - will convert high level language to assembly 5. assembler - will convert assembly to machine language 6. linker - will generate final executable.

THE C CHARACTER SET

The character set in C Language can be grouped into the following categories.

1. Letters2. Digits3. Special Characters4. White Spaces

White Spaces are ignored by the compiler until they are a part of string constant. White Space may be used to separate words, but are strictly prohibited while using between characters of keywords or identifiers.

C Character-Set Table

Letters Digits

Upper Case A to Z 0 to 9

Lower Case a to z.

A character denotes any alphabet ,digit or symbols to represent

information.The following are the valid alphabets, numbers and special

symbols permitted in C 

Numerals: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 

Alphabets: a, b, ….z

                  A, B, ……...Z 

Page 38: C Lecture 1

Arithmetic Operations: +, -, *, /, %(Mod) 

Special Characters:

                               

( ) { } [ ] < >

= ! $ ? . , : ;

‘ “ & | ^ ~ ` #

\ blank - _ / * % @

 

CONSTANTS, VARIABLES AND KEYWORDS

A ‘constant’ is an entity that does not change, but a ‘variable’ as the name

suggests may change.

We do  a number of calculations in a computer and the computed values are

stored in some memory spaces. Inorder to retrieve and re-use those values

from the computer’s memory locations they are given names. Since the

value stored in each location may change, the names given to these

locations are called as ‘variable names’.

Constants:

There are mainly three types of constants namely: integer, real and

character constants.

Integer Constants:

The integer constants

Whole Numbers

Eg. 25, 35, -25, -46

Computer allocates only 2 bytes in memory.

16th bit is sign bit. (if 0 then +ve value, if 1 then –ve value)

Page 39: C Lecture 1

                 

       (i) Decimal Integer Constant:

0 to 9

E.g: 49, 58, -62, … (40000 cannot come bcoz it is > 32767)

        (ii) Octal Integer Constant:

0 to 7

Add “0” before the value.

Eg.: 045, 056, 067

        (iii) Hexadecimal Integer:

0 to 9 and A to F

Add 0x before the value

E.g: 0x42, 0x56, 0x67

REAL CONSTANTS:

The real or floating point constants are in two forms namely fractional form

and the exponential form.

A real constant in fractional form must:

Have at least one digit

It must have a decimal point

Could have positive or negative sign(default sign is positive)

Must not have commas or spaces within it

Allots 4 bytes in memory

Ex:  +867.9, -26.9876, 654.0 

In exponential form, the real constant is represented as two parts. The part

lying before the ‘e’ is the ‘mantissa’, and the one following ‘e’ is the

‘exponent’.

The real constant in exponential form must follow the following rules:

Page 40: C Lecture 1

The mantissa part and the exponential part should be separated by

the letter ‘e’

The mantissa may have a positive or negative sign(default sign is

positive)

The exponent must have at least one digit

The exponent must be a positive or negative integer(default sign is

positive)

The range of real constants in exponential form is -3.4e38 and -

3.4e38

Ex:  +3.2e-4,  4.1e8,  -0.2e+4,  -3.2e-4 

CHARACTER CONSTANTS

A character constant is an alphabet, a single digit or a single special symbol

enclosed within inverted commas. The maximum length of a character

constant can be 1 character. Allots 1 byte of memory

Ex:  ’B’,  ’l’,    ’#’ 

STRING CONSTANTS

Strings in C are represented by arrays of characters. The end of the string is marked with a special character, the null character, which is simply the character with the value 0. The null or string-terminating character is represented by another character escape sequence, \0.

In fact, C's only truly built-in string-handling is that it allows us to use string constants (also called string literals) in our code. Whenever we write a string, enclosed in double quotes, C automatically creates an array of characters for us, containing that string, terminated by the \0 character. For example, we can declare and define an array of characters, and initialize it with a string constant:

char string[] = "Hello, world!";

To do anything else with strings, we must typically call functions. The C library contains a few basic string manipulation functions, and to learn more about strings, we'll be looking at how these functions might be implemented.

Since C never lets us assign entire arrays, we use the strcpy function to copy one string to another:

#include <string.h>

Page 41: C Lecture 1

char string1[] = "Hello, world!";char string2[20];

strcpy(string2, string1);

TOKENS IN C

In a C source program, the basic element recognized by the compiler is the "token." A token is source-program text that the compiler does not break down into component elements.

There are 6 types of Tokens in C which are as follows:-

1. Keyword2. Identifier3. Constants/Literals4. Variable5. Operator6. Punctuator

TYPES OF C VARIABLES

Variable names are names given to locations in the memory. These

locations can contain integer, real or character constants. An integer variable

can hold only an integer constant, a real variable can hold only a real

constant and a character variable can hold only a character constant.  

Rules for Constructing Variable Names

A variable name is any combination of 1 to 31 alphabets, digits or

underscores. Some compilers allow variable names whose length could be

up to 247 characters.

The first character in the variable name must be an alphabet

No commas or blanks are allowed within a variable name.

No special symbol other than an underscore (as in net_sal) can be

used in a variable name.

Ex.: si_int

e_hra

Page 42: C Lecture 1

pod_e_81

C compiler makes it compulsory for the user to declare the type of any

variable name that he wishes to use in a program. This type declaration is

done at the beginning of the program. Following are the examples of type

declaration statements:

Ex.: int si, e_hra ;

float bas_sal ;

char code ;

Since, the maximum allowable length of a variable name is 31

characters, an enormous number of variable names can be constructed

using the above-mentioned rules. It is a good practice to exploit this

enormous choice in naming variables by using meaningful variable names.  

C Keywords

C makes use of only 32 keywords or reserved words which combine with the

formal syntax to the form the C programming language. Note that all

keywords in C are written in lower case. A keyword may not be used as a

variable name.

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if 

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while 

 

 

Page 43: C Lecture 1

As a programmer, you will frequently want your program to "remember" a value. For example, if your program requests a value from the user, or if it calculates a value, you will want to remember it somewhere so you can use it later. The way your program remembers things is by using variables. For example:

int b;

This line says, "I want to create a space called b that is able to hold one integer value." A variable has a name (in this case, b) and a type (in this case, int, an integer). You can store a value in b by saying something like:

b = 5;

You can use the value in b by saying something like:

printf("%d", b);

In C, there are several standard types for variables:

← int - integer (whole number) values ← float - floating point values ← char - single character values (such as "m" or "Z")

A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.

The Programming language C has two main variable types

LOCAL VARIABLES GLOBAL VARIABLES

Local Variables

← Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block.

← When a local variable is defined - it is not initalised by the system, you must initalise it yourself.

Page 44: C Lecture 1

← When execution of the block starts the variable is available, and when the block ends the variable 'dies'.

Check following example's output

main() { int i=4; int j=10; i++; if (j > 0) { /* i defined in 'main' can be seen */ printf("i is %d\n",i); } if (j > 0) { /* 'i' is defined and so local to this block */ int i=100; printf("i is %d\n",i); }/* 'i' (value 100) dies here */ printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/ } This will generate following output i is 5 i is 100 i is 5

Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1;

You will see -- operator also which is called decremental operator and it decreases the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1;

Global Variables

Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.

Global variables are initalised automatically by the system when you define them!

Page 45: C Lecture 1

Data Type Initialser int 0 char '\0' float 0 pointer NULL

If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.

int i=4; /* Global definition */ main() { i++; /* Global variable */ func(); printf( "Value of i = %d -- main function\n", i ); }

func() { int i=10; /* Local definition */ i++; /* Local variable */ printf( "Value of i = %d -- func() function\n", i ); }

This will produce following result Value of i = 11 -- func() function Value of i = 5 -- main function

i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global.

DATA TYPES IN C

A programming language is proposed to help programmer to process certain kinds of data and to provide useful output. The task of data processing is accomplished by executing series of commands called program. A program usually contains different types of data types (integer, float, character etc.) and need to store the values being used in the program. C language is rich of data types. A C programmer has to employ proper data type as per his requirement.

C has different data types for different types of data and can be broadly classified as :

Page 46: C Lecture 1

1. Primary data types 2. Secondary data types

Primary data types consist following data types.

Data Types in C

Integer types:

Integers are whole numbers with a range of values, range of values are machine dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32768 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for number. To control the range of numbers and storage space, C has three classes of integer storage namely short int, int and long int. All three data types have signed and unsigned forms. A short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned integers are always positive and use all the bits for the magnitude of the number. Therefore the range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a longer range of values and it occupies 4 bytes of storage space.

Syntax:        int <variable name>; likeint num1;

Page 47: C Lecture 1

short int num2;long int num3;

Example:      5, 6, 100, 2500.

Integer Data Type Memory Allocation

Floating Point Types:

The float data type is used to store fractional numbers (real numbers) with 6 digits of precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision and takes double space (8 bytes) than float. To extend the precision further we can use long double which occupies 10 bytes of memory space.

Syntax:          float <variable name>; likefloat num1;double num2;long double num3;

Example:      9.125, 3.1254.

Floating Point Data Type Memory Allocation

Character Type:

Character type variable can hold a single character. As there are singed and unsigned int (either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have values between 0 and 255, signed characters have values from

Page 48: C Lecture 1

–128 to 127.

Syntax: char <variable name>; likechar ch = ‘a’;

Example:      a, b, g, S, j.

VOID TYPE:

The void type has no values therefore we cannot declare it as variable as we did in case of integer and float.

The void data type is usually used with function to specify its type. Like in our first C program we declared “main()” as void type because it does not return any value.

User defined type declaration

C language supports a feature where user can define an identifier that characterizes an existing data type. This user defined data type identifier can later be used to declare variables. In short its purpose is to redefine the name of an existing data type.

Syntax: typedef <type> <identifier>; liketypedef int number;

Now we can use number in lieu of int to declare integer variable. For example: “int x1” or “number x1” both statements declaring an integer variable. We have just changed the default keyword “int” to declare integer variable to “number”.

Page 49: C Lecture 1

DIFFERENCE BETWEEN THE DEFINITION AND DECLARATION OF A VARIABLE IN C?

definition defines the memory area ( allocates the memory ) for the variable and the declaration tells about the signature of the variable ( type and size to be considered). definition occures once through the program( memory is allocated once ), but the declaration can occur many times.

OR For a variable, the definition is the statement that actually allocates memory. For example, the statement:

long int var;

is a definition. On the other hand, an extern reference to the same variable:

extern long int var;

is a declaration, since this statement doesn?t cause any memory to be allocated. Here?s another example of a declaration:

typedef MyType short;

INITIALIZE VARIABLES IN C

C does not initialize variables automatically, so if you do not initialize them properly, you can get unexpected results. Fortunately, C makes it easy to initialize variables when you declare them.

Page 50: C Lecture 1

Initialize Variables at Declaration

Initialize a variable in C to assign it a starting value. Without this, you will get whatever happened to be in memory at that moment, which leads to inconsistent behavior and irreproducible bugs that can be exceedingly difficult to track down.

Add an initialization to the declaration. Just tack on an assignment right to the end of the declaration, like so:

int x = 5;

Know that initializing arrays works similarly, save that you must put multiple comma-separated values inside curly brackets. When doing this, you can leave off the array's size, and it will be filled in automatically:

int month_lengths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

Take advantage of character strings. Character strings, which are really arrays of characters, also support a simpler format for initialization:

char title[] = "My Program";

Express either kind of array initialization in pointer format (since arrays are really pointers):

int *month_lengths = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};char *title = "My Program";

Remember that structures in C are initialized in the same way as arrays:

struct role = { "Hamlet", 7, FALSE, "Prince of Denmark", "Kenneth Branagh"};

Initialize Variables Manually

Wait to initialize a variable at another place in the program if this will be clearer. For instance, a variable that will be the index of a for loop is usually best initialized in the for loop. This makes it easier for another programmer to read, since the initialization is near where it will be used.

Page 51: C Lecture 1

Initialize the data structure at the right time. If a data structure is going to be dynamically allocated with malloc() or a similar function, you can't initialize it until after it's allocated. However, in this case, what you're declaring is actually a pointer, which should still be initialized to NULL as a matter of course.

TYPE CONVERSION

type conversion or typecasting refers to changing an entity of one data type into another. This is done to take advantage of certain features of type hierarchies

There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. The most common form of explicit type conversion is known as casting. Explicit type conversion can also be achieved with separately defined conversion routines such as an overloaded object constructor.

Implicit conversion

Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:

123

short a=2000;int b;b=a;

Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

Explicit conversion

C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:

1234

short a=2000;int b;b = (int) a; // c-like cast notationb = int (a); // functional notation

Page 52: C Lecture 1

CONSTANT AND VOLATILE VARIABLE

Volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time-without any action being taken by the nearby code. The implications of this are quite serious. Let's take a look at the syntax.

A variable should be declared volatile whenever its value could change unexpectedly. In practice, only three types of variables could change:

Memory-mapped peripheral registers Global variables modified by an interrupt service routine Global variables within a multi-threaded application

If we do not use volatile qualifier the following problems may arise:

Code that works fine-until you turn optimization on Code that works fine-as long as interrupts are disabled Flaky hardware drivers Tasks that work fine in isolation-yet crash when another task is enabled

Example:

static int var; void test(void) { var = 0; while (var  !=  255) continue; }

The above code sets the value in var to 0. It then starts to poll that value in a loop until the value of var becomes 255.

An optimizing compiler will notice that no other code can possibly change the value stored in 'var', and therefore assume that it will remain equal to 0 at all times. The compiler will then replace the function body with an infinite loop, similar to this:

void test_opt(void) { var = 0; while (TRUE) continue; }

Page 53: C Lecture 1

Declaration of Volatile variable

Include the keyword volatile before or after the data type in the variable. volatile int var;int volatile var;

Pointer to a volatile variable

volatile int * var; 

int volatile * var;

Above statements implicate 'var' is a pointer to a volatile integer.   

CONSTANT VARIABLE

const

const is used with a datatype declaration or definition to specify an unchanging value

Examples:

const int five = 5;const double pi = 3.141593;

const objects may not be changed

The following are illegal:

const int five = 5;const double pi = 3.141593;

pi = 3.2;five = 6;

EXTERNAL VARIABLES

Where a global variable is declared in one file, but used by functions from another, then the variable is called an external variable in these functions, and must be declared as such. The declaration must be preceeded by the word extern. The declaration is required so the compiler can find the type of the variable without having to search through several source files for the declaration.

Global and external variables can be of any legal type. They can be initialised, but the initialisation takes place when the program starts up, before entry to the main function.

Page 54: C Lecture 1

STATIC VARIABLES

Another class of local variable is the static type. A static can only be accessed from the function in which it was declared, like a local variable. The static variable is not destroyed on exit from the function, instead its value is preserved, and becomes available again when the function is next called. Static variables are declared as local variables, but the declaration is preceeded by the word static.

static int counter;

Static variables can be initialised as normal, the initialisation is performed once only, when the program starts up.

Can a variable be both const and volatile?

Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. For instance, the timer structure was accessed through a

volatile const pointer. The function itself did not change the value of the timer, so it was declared const. However, the value was changed by hardware on the

computer, so it was declared volatile. If a variable is both const and volatile, the two modifiers can appear in either order.

WRITE A C PROGRAM TO FIND THE SUM OF TWO NUMBERS AND THEIR AVERAGE?

#include <stdio.h>

int main (void) // main(){ int x=3, y=5; //int x,y,ave; x=10;y=20;ave=(x+y)/2;printf ("sum=%d, average=%d\n", x+y, (x+y)/2);

//printf(“Average of two numbers %dand %d=%d”/n,x,y,ave);

return 0; // no need if no return type}

USER DEFINED DATA TYPES IN C

user can create his own data type for handling data that does not fit in one of the existing data types

Page 55: C Lecture 1

USING TYPEDEF

The type definition statement is used to allow user defined data types to be defined using other already available data types.Basic Format:typedef existing_data_type new_user_define_data_type;

Examples:typedef int Integer;

The example above simply creates an alternative data type name or “alias” called Integer for the built in data type called “int”. This is generally not a recommended use of the typedef statement.

typedef char Characters [ WORDSIZE ]; /* #define WORDSIZE 20 */The example above creates a user defined data type called Characters. Characters is a data type that supports a list of “char” values. The fact that this user defined data type is an array of WORDSIZE is now built into the data type.Characters One_String; /* [ ] and WORDSIZE are not specified *//* this also applies to argument list use */

The first keyword we shall explore is typedef. With this keyword we can define a new type, and give it a user-friendly name. For example:

typedef int Boolean;

This code tells the compiler that we want to define a type Boolean, that is equivalent to an integer. In order to use this new type, we could use code similar to:

Boolean bResult;// ... Some code ...if (bResult == 0) { printf ("False\n"); }

This is not, however, very user friendly, but can be made more so by using the #define keyword to define values for true and false:

#define FALSE 0;#define TRUE 1;// ... Some code ...Boolean bResult;// ... Some code ...if (bResult == FALSE) { printf ("False\n"); }

Page 56: C Lecture 1

This is fine, but there is en even more elegant way to achieve this.

ENUMERATED TYPES (ENUM)

Enumerated data types are a user defined ordinal data type. The main purpose of the enumerated data type is to allow numbers to be replaced by words. This is intended to improve the readability of programs.

Basic Format:enum data_type_name { word1, word2, …, word(n-1), word(n) };ORenum data_type_name { word1 = integer1, word2 = integer2, etc… };

Examples:

enum Boolean { FALSE, TRUE };

In the example above a user defined data type called Boolean has been defined.The new data type has two values: FALSE and TRUE. The word FALSE has the integer value of 0. The word TRUE has the integer value of 1.

If no integer values are specified then the left most word has integer value 0 and each one after that is incremented by one from that point. (0, 1, 2, 3, etc…) This also means that the left-most word is generally the smallest and the right-most word is generally the largest.

enum Boolean { FALSE = 0, TRUE = 1 };

enum Weekdays { Monday = 1, Tuesday, Wednesday, Thursday, Friday };

In the example above a user defined data type called Weekdays has been defined.

The new data type has five values: Monday, Tuesday, Wednesday, Thursday, and Friday. Monday is 1, Tuesday is 2, Wednesday is 3, Thursday is 4, and Friday is 5.Notice that the starting value is 1 in this example instead of 0.

enum Boolean Positive; /* uninitialized variable declaration */enum Weekdays Day = Wednesday; /* initialized variable declaration */if ( Number > 0 )Positive = TRUE;else

Page 57: C Lecture 1

Positive = FALSE;for ( Day = Monday; Day <= Friday; ++ Day ){/* execute the body of loop */}

The disadvantage of enumerated data types is that normal input and outputoperations are not supported.scanf ( “%d%c”, &Day, &Enter_Key );/* integer based */

The defined values for the variable Day are: Monday, Tuesday, Wednesday,Thursday, and Friday. None of these values can be type in from the keyboard.

Any integer value can be typed in even though the only defined values are 1 through 5.printf ( “%d\n”, Monday ); /* integer based */

The word Monday will not be displayed on the screen for output. Instead the integer value 1 will be displayed.

An enumerated data type is a list of possible values, each of which is assigned a sequential number. This allows us to write code that can compare values easily. So, for our Boolean example:

typedef enum {FALSE, TRUE} Boolean;

This tells the compiler that we would like a Boolean type that evaluates to FALSE, or TRUE. The compiler will assign the values 0 and 1 to these new types, enabling comparisons such as:

Boolean bResult;// ... Some code ...if (bResult == FALSE) { printf ("False\n"); }

We can also define more complex lists:

typedef enum {Mon, Tue, Wed, Thu, Fri} Workdays;Workdays Today;// ... Some code ...if (Today == Mon) { printf("Monday\n"); }

However, in order to define complex data types which can contain data beyond the basic types, we need two more keywords.

ENUM is closely related to the #define preprocessor.

Page 58: C Lecture 1

It allows you to define a list of aliases which represent integer numbers. For example if you find yourself coding something like:

#define MON 1 #define TUE 2 #define WED 3 You could use enum as below. enum week { Mon=1, Tue, Wed, Thu, Fri Sat, Sun} days; or enum escapes { BELL = '\a', BACKSPACE = '\b', HTAB = '\t', RETURN = '\r', NEWLINE = '\n', VTAB = '\v' }; or enum boolean { FALSE = 0, TRUE };

An advantage of enum over #define is that it has scope This means that the variable (just like any other) is only visable within the block it was declared within.

Notes:

If a variable is defined with enum it is considered by the compiler to be an integer, and can have ANY integer value assigned to it, it is not restericted to the values in the enum statement.

STRING CONSTANTS

String constants are sequences of characters enclosed in double quotes. The same backslash sequences that are used in character constants can be used in string constants. E.g., "hello there", "a newline: \n", "a string\nwith multiple\nlines". If a string is long and you want to break it up across several lines of code, you can put a backslash just before a (real) newline and the C compiler will throw away both the backslash and the newline, e.g.,

printf("A very long help message\nthat is more readable if it is broken up over\n\several lines.\n");

this string contains one real newline (the \n).

Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some characters can't be represented in this way, so we use a 2 character sequence as follows. '\n' newline'\t' tab'\\' backslash'\'' single quote'\0' null ( Usedautomatically to terminate character string )

Page 59: C Lecture 1

OPERATORS IN C

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator.

C language supports following type of operators.

Arithmetic Operators Logical (or Relational) Operators

Bitwise Operators

Assignment Operators

Misc Operators

Arithmetic Operators:

There are following arithmetic operators supported by C language:

Assume variable A holds 10 and variable holds 20 then:

Operator Description Example

+ Adds two operands A + B will give 30

-Subtracts second operand from the first

A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by denominator B / A will give 2

%Modulus Operator and remainder of after an integer division

B % A will give 0

++Increment operator, increases integer value by one

A++ will give 11

--Decrement operator, decreases integer value by one

A-- will give 9

Try following example to understand all the arithmetic operators. Copy and paste following C program in test.c file and compile and run this program.

Page 60: C Lecture 1

main(){ int a = 21; int b = 10; int c ;

c = a + b; printf("Line 1 - Value of c is %d\n", c ); c = a - b; printf("Line 2 - Value of c is %d\n", c ); c = a * b; printf("Line 3 - Value of c is %d\n", c ); c = a / b; printf("Line 4 - Value of c is %d\n", c ); c = a % b; printf("Line 5 - Value of c is %d\n", c ); c = a++; printf("Line 6 - Value of c is %d\n", c ); c = a--; printf("Line 7 - Value of c is %d\n", c );

}

This will produce following result

Line 1 - Value of c is 31Line 2 - Value of c is 11Line 3 - Value of c is 210Line 4 - Value of c is 2Line 5 - Value of c is 1Line 6 - Value of c is 21Line 7 - Value of c is 22

Logical (or Relational) Operators:

There are following logical operators supported by C language

Assume variable A holds 10 and variable holds 20 then:

Operator Description Example

== Checks if the value of two operands is equal or not, if yes

(A == B) is not true.

Page 61: C Lecture 1

then condition becomes true.

!=

Checks if the value of two operands is equal or not, if values are not equal then condition becomes true.

(A != B) is true.

>

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

<

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

&&

Called Logical AND operator. If both the operands are non zero then then condition becomes true.

(A && B) is true.

||

Called Logical OR Operator. If any of the two operands is non zero then then condition becomes true.

(A || B) is true.

!

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is false.

Try following example to understand all the Logical operators. Copy and paste following C program in test.c file and compile and run this program.

main()

Page 62: C Lecture 1

{ int a = 21; int b = 10; int c ;

if( a == b ) { printf("Line 1 - a is equal to b\n" ); } else { printf("Line 1 - a is not equal to b\n" ); } if ( a < b ) { printf("Line 2 - a is less than b\n" ); } else { printf("Line 2 - a is not less than b\n" ); } if ( a > b ) { printf("Line 3 - a is greater than b\n" ); } else { printf("Line 3 - a is not greater than b\n" ); } /* Lets change value of a and b */ a = 5; b = 20; if ( a <= b ) { printf("Line 4 - a is either less than or euqal to b\n" ); } if ( b >= a ) { printf("Line 5 - b is either greater than or equal to b\n" ); } if ( a && b ) { printf("Line 6 - Condition is true\n" ); } if ( a || b ) {

Page 63: C Lecture 1

printf("Line 7 - Condition is true\n" ); } /* Again lets change the value of a and b */ a = 0; b = 10; if ( a && b ) { printf("Line 8 - Condition is true\n" ); } else { printf("Line 8 - Condition is not true\n" ); } if ( !(a && b) ) { printf("Line 9 - Condition is true\n" ); }}

This will produce following result

Line 1 - a is not equal to bLine 2 - a is not less than bLine 3 - a is greater than bLine 4 - a is either less than or equal to bLine 5 - b is either greater than or equal to bLine 6 - Condition is trueLine 7 - Condition is trueLine 8 - Condition is not trueLine 9 - Condition is true

Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation.

Assume if A = 60; and B = 13; Now in binary format they will be as follows:

A = 0011 1100

B = 0000 1101

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

A&B = 0000 1000

Page 64: C Lecture 1

A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

Note: convert decimal 49 to binary:

49/2 = 24 r 1 24/2 = 12 r 0 12/2 = 6 r 0 6/2 = 3 r 0 3/2 = 1 r 1 1/2 = 0 r 1 Now read the remainders from bottom to top: the binary equivalent is 110001

convert binary 1101001 to decimal: 1 + 8 + 32 + 64 = 105

convert decimal 0.7 to binary: 0.7 * 2 = 1.4 0.4 * 2 = 0.8 0.8 * 2 = 1.6 0.6 * 2 = 1.2 0.2 * 2 = 0.4 0.4 * 2 = 0.8 0.8 * 2 = 1.6 0.6 * 2 = 1.2 etc. Note that we have started to repeat previous results. Now read the integer parts occurring on the right side, from the top down: the binary representation of decimal 0.7 is 0.1011001100... where the "1100" repeats forever.

The bit on the far right, in this case a 0, is known as the Least significant bit (LSB).

The bit on the far left, in this case a 1, is known as the Most significant bit (MSB)

There are following Bitwise operators supported by C language

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both

(A & B) will give 12 which is 0000 1100

Page 65: C Lecture 1

operands.

|Binary OR Operator copies a bit if it exists in either operand.

(A | B) will give 61 which is 0011 1101

^Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

~Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.

(~A ) will give -60 which is 1100 0011

<<

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

>>

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

A >> 2 will give 15 which is 0000 1111

Try following example to understand all the Bitwise operators. Copy and paste following C program in test.c file and compile and run this program.

main(){

unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0;

c = a & b; /* 12 = 0000 1100 */ printf("Line 1 - Value of c is %d\n", c );

c = a | b; /* 61 = 0011 1101 */ printf("Line 2 - Value of c is %d\n", c );

c = a ^ b; /* 49 = 0011 0001 */ printf("Line 3 - Value of c is %d\n", c );

c = ~a; /*-61 = 1100 0011 */ printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */

Page 66: C Lecture 1

printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */ printf("Line 6 - Value of c is %d\n", c );}

This will produce following result

Line 1 - Value of c is 12Line 2 - Value of c is 61Line 3 - Value of c is 49Line 4 - Value of c is -61Line 5 - Value of c is 240Line 6 - Value of c is 15

Assignment Operators:

There are following assignment operators supported by C language:

Operator Description Example

=

Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B will assign value of A + B into C

+=

Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

C += A is equivalent to C = C + A

-=

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C -= A is equivalent to C = C - A

*=

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

C *= A is equivalent to C = C * A

Page 67: C Lecture 1

/=

Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

C /= A is equivalent to C = C / A

%=

Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

C %= A is equivalent to C = C % A

<<=Left shift AND assignment operator

C <<= 2 is same as C = C << 2

>>=Right shift AND assignment operator

C >>= 2 is same as C = C >> 2

&=Bitwise AND assignment operator

C &= 2 is same as C = C & 2

^=bitwise exclusive OR and assignment operator

C ^= 2 is same as C = C ^ 2

|=bitwise inclusive OR and assignment operator

C |= 2 is same as C = C | 2

Try following example to understand all the Assignment Operators. Copy and paste following C program in test.c file and compile and run this program.

main(){ int a = 21; int c ;

c = a; printf("Line 1 - = Operator Example, Value of c = %d\n", c );

c += a; printf("Line 2 - += Operator Example, Value of c = %d\n", c );

c -= a; printf("Line 3 - -= Operator Example, Value of c = %d\n", c );

c *= a; printf("Line 4 - *= Operator Example, Value of c = %d\n", c );

Page 68: C Lecture 1

c /= a; printf("Line 5 - /= Operator Example, Value of c = %d\n", c );

c = 200; c %= a; printf("Line 6 - %= Operator Example, Value of c = %d\n", c );

c <<= 2; printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );

c >>= 2; printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );

c &= 2; printf("Line 9 - &= Operator Example, Value of c = %d\n", c );

c ^= 2; printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );

c |= 2; printf("Line 11 - |= Operator Example, Value of c = %d\n", c );

}

This will produce following result

Line 1 - = Operator Example, Value of c = 21Line 2 - += Operator Example, Value of c = 42Line 3 - -= Operator Example, Value of c = 21Line 4 - *= Operator Example, Value of c = 441Line 5 - /= Operator Example, Value of c = 21Line 6 - %= Operator Example, Value of c = 11Line 7 - <<= Operator Example, Value of c = 44Line 8 - >>= Operator Example, Value of c = 11Line 9 - &= Operator Example, Value of c = 2Line 10 - ^= Operator Example, Value of c = 0Line 11 - |= Operator Example, Value of c = 2

Page 69: C Lecture 1

Short Notes on L-VALUE and R-VALUE:

x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x. Here x and 1 are known as L-VALUES and R-VALUES respectively L-values can be on either side of the assignment operator where as R-values only appear on the right.

So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y = x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is invalid.

Misc Operators

There are few other operators supported by C Language.

Operator Description Example

sizeof()Returns the size of an variable.

sizeof(a), where a is interger, will return 4.

&Returns the address of an variable.

&a; will give actaul address of the variable.

* Pointer to a variable. *a; will pointer to a variable.

? : Conditional ExpressionIf Condition is true? Then value X : Otherwise value Y

sizeof Operator:

Try following example to understand sizeof operators. Copy and paste following C program in test.c file and compile and run this program.

main(){ int a; short b; double double c; char d[10];

printf("Line 1 - Size of variable a = %d\n", sizeof(a) ); printf("Line 2 - Size of variable b = %d\n", sizeof(b) ); printf("Line 3 - Size of variable c= %d\n", sizeof(c) ); printf("Line 4 - Size of variable d= %d\n", sizeof(d) );

Page 70: C Lecture 1

/* For character string strlen should be used instead of sizeof */ printf("Line 5 - Size of variable d= %d\n", strlen(d) );}

This will produce following result

Line 1 - Size of variable a = 4Line 2 - Size of variable b = 2Line 3 - Size of variable c= 8Line 4 - Size of variable d= 10Line 5 - Size of variable d= 10

& and * Operators:

Try following example to understand & operators. Copy and paste following C program in test.c file and compile and run this program.

main(){ int i=4; /* variable declaration */ int* ptr; /* int pointer */

ptr = &i; /* 'ptr' now contains the address of 'i' */

printf(" i is %d.\n", i); printf("*ptr is %d.\n", *ptr);}

This will produce following result

i is 4.*ptr is 4.

? : Operator

Try following example to understand ? : operators. Copy and paste following C program in test.c file and compile and run this program.

main(){ int a , b;

Page 71: C Lecture 1

a = 10; b = (a == 1) ? 20: 30; printf( "Value of b is %d\n", b );

b = (a == 10) ? 20: 30; printf( "Value of b is %d\n", b );}

This will produce following result

Value of b is 30Value of b is 20

Note : 1's and 2's complement

Generally negative numbers can be represented usingeither 1's complement or 2's complement representation.

1's complement ---reverse all the bits2's complement ---reverse all the bits + 1

i.e 1's complement of 2 ( 0000 0010 ) is -2 ( 1111 1101 )2's complement of 2 ( 0000 0010 ) is -2 ( 1111 1110 )

Binary numbers do not have signs. So 2's complement is used to represent a negative nos. 2's complement is found in following way :Step I) If we have a binary no 00001100(decimal 12) then we have to invert it by replacing all the 1s by 0 and 0s by 1.So we get 00001100 ---> 11110011

Step II)Now we have to add 1 to the no which we found in (I)So we get ,11110011 + 00000001 = 11110100

So the no 11110100 represents -12 .

Page 72: C Lecture 1

Operators Categories:

All the operators we have discussed above can be categorised into following categories:

Postfix operators, which follow a single operand. Unary prefix operators, which precede a single operand.

Binary operators, which take two operands and perform a variety of arithmetic and logical operations.

The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.

Assignment operators, which assign a value to a variable.

The comma operator, which guarantees left-to-right evaluation of comma-separated expressions.

C Operator Precedence and Associativity

C operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied.

Operator Description Associativity

()[].

->++  --

Parentheses (function call) (see Note 1)Brackets (array subscript)

Member selection via object nameMember selection via pointer

Postfix increment/decrement (see Note 2)

left-to-right

++  --+  -!  ~

(type)*&

sizeof  

Prefix increment/decrementUnary plus/minus

Logical negation/bitwise complementCast (change type)

Dereference/pointer Address

Determine size in bytes

right-to-left

*  /  % Multiplication/division/modulus left-to-right

+  - Addition/subtraction left-to-right

<<  >> Bitwise shift left, Bitwise shift right left-to-right

<  <=>  >=

Relational less than/less than or equal toRelational greater than/greater than or

equal to

left-to-right

Page 73: C Lecture 1

==  != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

=+=  -=*=  /=

%=  &=^=  |=

<<=  >>=

AssignmentAddition/subtraction assignment

Multiplication/division assignmentModulus/bitwise AND assignment

Bitwise exclusive/inclusive OR assignment

Bitwise shift left/right assignment

right-to-left

, Comma (separate expressions) left-to-right

Note 1: Parentheses are also used to group sub-expressions to

force a different precedence; such parenthetical expressions can be nested and are evaluated from inner to

outer. Note 2:

Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the

statement completes execution). So in the statement  y = x * z++; the current value of z is used to evaluate the

expression (i.e., z++ evaluates to z) and z only incremented after all else is done.

C Ternary Operator

C ternary operator is a shorthand of combination of if and return statement. Syntax of ternary operator are as follows:(expression1 ) ? expression2: expression3If expression1 is true it returns expression2 otherwise it returns expression3. This operator is a shorthand version of this if and return statement:if(expression1) return expression2; else return expression3;

Page 74: C Lecture 1

Increment operator ++

Prefix: the value is incremented/decremented first and then applied.Postfix: the value is applied and the value is incremented/decremented.

#include<stdio.h>

main( ){    int i = 3,j = 4,k;    k = i++ + --j;    printf("i = %d, j = %d, k = %d",i,j,k);}

Out put : i = 4, j = 3, k = 6

The decrement operator: --

#include <stdio.h>#include <stdlib.h> int main(){    char weight[4];    int w;     printf("Enter your weight:");    gets(weight);    w=atoi(weight);     printf("Here is what you weigh now: %i\n",w);    w--;    printf("w++: %i\n",w);    w--;    printf("w++: %i\n",w);

    return(0);}

Enter your weight:123 Here is what you weigh now: 123 w++: 122

1's complement and 2's complement

Page 75: C Lecture 1

Generally negative numbers can be represented usingeither 1's complement or 2's complement representation.

1's complement ---reverse all the bits2's complement ---reverse all the bits + 1

i.e 1's complement of 2 ( 0000 0010 ) is -2 ( 1111 1101 )

ExamplesOriginal number: 01110111's complement: 10001002's complement: 1000101

Original number: 11111111's complement: 00000002's complement: 0000001

Original number: 11110001's complement: 00001112's complement: 0001000

Use of clrscr

Usually you want to clear the screen prior to writng to the terminal.

Use;

#include < conio.h> /* as in console I/O */...

main(){ ... clrscr();

Note that as this is a command, it must appear after your variable declarations.

requires the header file conio.h i.e #include <conio.h>

clrscr();  :- This is use to clear the output screen i.e console

suppose you run a program and then alter it and run it again you may find that the previous output is still stucked there itself, at this time clrscr(); would clean the previous screen.

Page 76: C Lecture 1

One more thing to remember always use clrscr(); after the declaration like

int a,b,c;

float total;

clrscr();

getch()/ getche()

getch(); :- getch is used to hold the screen in simple language, if u dont write this the screen

will just flash and go away....

getch() takes one char from keyboard but it will be invisible to us. in other words we can say that it waits until press any key from keyboard.

getch() is a function which has its protype defined in conio.h header file.

it is basically used to take input a single characterfrom keyboard. and this char is not displayed at the screen.

it waits untill itn gets a input thats why it can be used as a screen stopper.

getch() returns to the program after hitting any key.

getche() waits for the character, read it and then returns to the program

getch() waits for the user to input a character and displays the output till the user enters a character.As soon as the user enters a character it transfers the control back to the main function, without displaying what character was entered.

getche() does the same thin but it displays the chacter entered.here e stands for echo.

Use of getch(),getche() and getchar() in C

Most of the program is ending with getch(),and so we think that getch() is used to display the output...but it is wrong.It is used to get a single character from the console.

Just see the behaviors of various single character input functions in c.

Page 77: C Lecture 1

getchar() getche() getch()

getchar() is used to get or read the input (i.e a single character) at run time.

Library:

<CONIO.H>

Example Declaration:

char ch;ch = getchar();

This function return the character read from the keyboard.

Example Program:

void main(){char ch;ch = getchar();printf("Input Char Is :%c",ch);}

Here,declare the  variable ch as  char data type, and then get a value through getchar() library function and store it in the variable ch.And then,print the value of variable ch.During the program execution, a single character is get or read through the getchar(). The given value is displayed on the screen and the compiler wait for another character to be typed. If you press the enter key/any other characters and then only the given character is  printed through the printf function.

getche() is used to get a character from console, and echoes to the screen.

Library:

<CONIO.H>

Example Declaration:

char ch;ch = getche();

getche reads a single character from the keyboard and echoes it to the current text window, using direct video or BIOS.

This function return the character read from the keyboard.

Page 78: C Lecture 1

Example Program:

void main(){char ch;ch = getche();printf("Input Char Is :%c",ch);}

Here,declare the  variable ch as  char data type, and then get a value through getche() library function and store it in the variable ch.And then,print the value of variable ch.During the program execution, a single character is get or read through the getche(). The given value is displayed on the screen and the compiler does not wait for another character to be typed. Then,after wards the character is  printed  through the  printf function.

getch() is used to get a character from console but does not echo to the screen.

Library:

<CONIO.H>

Example Declaration:

char ch;ch = getch(); (or ) getch();

getch reads a single character directly from the keyboard, without echoing to the screen.

This function return the character read from the keyboard.

Example Program:

void main(){char ch;ch = getch();printf("Input Char Is :%c",ch);}

Here,declare the  variable ch as  char data type, and then get a value through getch() library function and store it in the variable ch.And then,print the value of variable ch.During the program execution, a single character is get or read through the getch(). The given value is not displayed on the screen and the compiler does not wait for another character to be typed.And then,the given character is  printed through the printf function.

Page 79: C Lecture 1

# C Tips:

3>2 ? printf(“True”):printf(“False”); // prints True z=x*++y // it will increment first then multiplies

The sizeof Operator

The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.

The sizeof program uses the C sizeof() call to display the size (in bytes) of the standard C data types (char, int, long,...).

Int x=12;float y=2;

Printf(sizeof(x)); // prints 2 (bytes)

Printf(sizeof(y)); // prints 4(bytes)

& operator

Page 80: C Lecture 1

Prints the address of the variable in the memory

#include <stdio.h> int main() { int x = 0; printf("Address of x "); printf("= 0x%p \n", &x); return 0;}

Output: Address of x = 0x0065FDF4

int a;        /* a is an integer */printf( "The address of a is %p”, &a )//prints address of variable a -8907

TIP

printf(“\n10==10 :%5d”,10==10);// prints 1 for true printf(“\n10==10 :%5d”,10>=10); // prints 1

printf(“\n10==10 :%5d”,10!=10);//prints 0

b=(a==5 ? 3:4); // prints value of b

TIP

printf(“%5d”,5>3 && 5<10 ); //prints 1 for true printf(“%5d”,8>5 || 8<2); // prints 0 for false

y=(x>=65 && x<=90? 1:0); // is correct

C - STORAGE CLASSES

A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.

There are following storage classes which can be used in a C Program

auto register

static

extern

Page 81: C Lecture 1

auto - Storage Class

auto is the default storage class for all local variables.

{ int Count; auto int Month;

}

The example above defines two variables with the same storage class.

auto can only be used within functions, i.e. local variables.

register - Storage Class

register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location).

{ register int Miles;

}

Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implementation restrictions.

static - Storage Class

static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.

static int Count; int Road;

{ printf("%d\n", Road); }

static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.

Page 82: C Lecture 1

static can also be defined within a function. If this is done the variable is initialized at run time but is not reinitialized when the function is called. This inside a function static variable retains its value during various calls.

void func(void); static count=10; /* Global variable - static is the default */ main() { while (count--) { func(); } } void func( void ) { static i = 5; i++; printf("i is %d and count is %d\n", i, count); } This will produce following result i is 6 and count is 9 i is 7 and count is 8 i is 8 and count is 7 i is 9 and count is 6 i is 10 and count is 5 i is 11 and count is 4 i is 12 and count is 3 i is 13 and count is 2 i is 14 and count is 1 i is 15 and count is 0

NOTE : Here keyword void means function does not return anything and it does not take any parameter. You can memorizes void as nothing. static variables are initialized to 0 automatically.

Definition vs Declaration : Before proceeding, let us understand the difference between defintion and declaration of a variable or function. Definition means where a variable or function is defined in reality and actual memory is allocated for variable or function. Declaration means just giving a reference

Page 83: C Lecture 1

of a variable and function. Through declaration we assure to the complier that this variable or function has been defined somewhere else in the program and will be provided at the time of linking. In the above examples char *func(void) has been put at the top which is a declaration of this function where as this function has been defined below to main() function.

There is one more very important use for 'static'. Consider this bit of code.

char *func(void);

main() { char *Text1; Text1 = func(); }

char *func(void) { char Text2[10]="martin"; return(Text2); }

Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify

static char Text[10]="martin";

The storage assigned to 'text2' will remain reserved for the duration if the program.

extern - Storage Class

extern is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.

When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another files.

File 1: main.c

int count=5;

Page 84: C Lecture 1

main() { write_extern(); }

File 2: write.c

void write_extern(void);

extern int count;

void write_extern(void) { printf("count is %i\n", count); }

Here extern keyword is being used to declare count in another file.

Now compile these two files as follows

gcc main.c write.c -o write

This fill produce write program which can be executed to produce result.

Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c will see the new value

C - INPUT AND OUTPUT

Input : In any programming language input means to feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of built-in functions to read given input and feed it to the program as per requirement.

Output : In any programming language output means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to output required data.

Here we will discuss only one input function and one output function just to understand the meaning of input and output. Rest of the functions are given into C - Built-in Functions

Page 85: C Lecture 1

printf() function

This is one of the most frequently used functions in C for output. Try following program to understand printf() function.

#include <stdio.h>

main(){ int dec = 5; char str[] = "abc"; char ch = 's'; float pi = 3.14;

printf("%d %s %f %c\n", dec, str, pi, ch);}

The output of the above would be:

5 abc 3.140000 c

Here %d is being used to print an integer, %s is being used to print a string, %f is being used to print a float and %c is being used to print a character.

scanf() function

This is the function which can be used to to read an input from the command line.

Try following program to understand scanf() function.

#include <stdio.h>

main(){ int x; int args;

printf("Enter an integer: "); if (( args = scanf("%d", &x)) == 0) { printf("Error: not an integer\n"); } else { printf("Read in %d\n", x); }

Page 86: C Lecture 1

}

Here %d is being used to read an integer value and we are passing &x to store the value read input. Here &indicates the address of variable x.

This program will prompt you to enter a value. Whatever value you will enter at command prompt that will be output at the screen using printf() function. If you enter a non-integer value then it will display an error message.

Enter an integer: 20Read in 20

Here is another program that will help you learn more about printf:

#include <stdio.h>

int main(){ int a, b, c; a = 5; b = 7; c = a + b; printf("%d + %d = %d\n", a, b, c); return 0;}

You will see the line "5 + 7 = 12" as output.

The computer adds the value in a (5) to the value in b (7) to form the result 12, and then places that new value (12) into the variable c. The variable c is assigned the value 12. For this reason, the = in this line is called "the assignment operator."

← The printf statement then prints the line "5 + 7 = 12." The %d placeholders in the printf statement act as placeholders for values. There are three %d placeholders, and at the end of the printf line there are the three variable names: a, b and c. C matches up the first %d with a and substitutes 5 there. It matches the second %d with b and substitutes 7. It matches the third %d with c and substitutes 12. Then it prints the completed line to the screen: 5 + 7 = 12. The +, the = and the spacing are a part of the format line and get embedded automatically between the %d operators as specified by the programmer.

C Errors to Avoid:

Using the wrong character case - Case matters in C, so you cannot type

Page 87: C Lecture 1

Printf or PRINTF. It must be printf. Forgetting to use the & in scanf Too many or too few parameters following the format statement in printf

or scanf Forgetting to declare a variable name before using it

The previous program is good, but it would be better if it read in the values 5 and 7 from the user instead of using constants. Try this program instead:

#include <stdio.h>

int main(){ int a, b, c; printf("Enter the first value:"); scanf("%d", &a); printf("Enter the second value:"); scanf("%d", &b); c = a + b; printf("%d + %d = %d\n", a, b, c); return 0;}

Here's how this program works when you execute it:

Make the changes, then compile and run the program to make sure it works. Note that scanf uses the same sort of format string as printf (type man scanf for more info).

Also note the & in front of a and b. This is the address operator in C: It returns the address of the variable (this will not make sense until we discuss pointers). You must use the & operator in scanf on any variable of type char, int, or float, as well as structure types (which we will get to shortly). If you leave out the & operator, you will get an error when you run the program. Try it so that you can see what that sort of run-time error looks like.

Let's look at some variations to understand printf completely. Here is the simplest printf statement:

printf("Hello");

This call to printf has a format string that tells printf to send the word "Hello" to standard out. Contrast it with this:

printf("Hello\n");

Page 88: C Lecture 1

The difference between the two is that the second version sends the word "Hello" followed by a carriage return to standard out.

The following line shows how to output the value of a variable using printf.

printf("%d", b);

The %d is a placeholder that will be replaced by the value of the variable b when the printf statement is executed. Often, you will want to embed the value within some other words. One way to accomplish that is like this:

printf("The temperature is "); printf("%d", b); printf(" degrees\n");

An easier way is to say this:

printf("The temperature is %d degrees\n", b);

You can also use multiple %d placeholders in one printf statement:

printf("%d + %d = %d\n", a, b, c);

In the printf statement, it is extremely important that the number of operators in the format string corresponds exactly with the number and type of the variables following it . For example, if the format string contains three %d operators, then it must be followed by exactly three parameters and they must have the same types in the same order as those specified by the operators.

You can print all of the normal C types with printf by using different placeholders:

int (integer values) uses %d float (floating point values) uses %f char (single character values) uses %c character strings (arrays of characters, discussed later) use %s

You can learn more about the nuances of printf on a UNIX machine by typing man 3 printf. Any other C compiler you are using will probably come with a manual or a help file that contains a description of printf.

Scanf

Modify this program so that it accepts three values instead of two and adds all three together:

Page 89: C Lecture 1

#include <stdio.h>

int main(){ int a, b, c; printf("Enter the first value:"); scanf("%d", &a); printf("Enter the second value:"); scanf("%d", &b); c = a + b; printf("%d + %d = %d\n", a, b, c); return 0;}

The scanf function allows you to accept input from standard in, which for us is generally the keyboard. The scanf function can do a lot of different things, but it is generally unreliable unless used in the simplest ways. It is unreliable because it does not handle human errors very well. But for simple programs it is good enough and easy-to-use.

The simplest application of scanf looks like this:

scanf("%d", &b);

The program will read in an integer value that the user enters on the keyboard (%d is for integers, as is printf, so b must be declared as an int) and place that value into b.

The scanf function uses the same placeholders as printf:

← int uses %d ← float uses %f ← char uses %c ← character strings (discussed later) use %s

You MUST put & in front of the variable used in scanf. The reason why will become clear once you learn about pointers. It is easy to forget the & sign, and when you forget it your program will almost always crash when you run it.

In general, it is best to use scanf as shown here -- to read a single value from the keyboard. Use multiple calls to scanf to read multiple values. In any real program, you will use the gets or fgets functions instead to read text a line at a time. Then you will "parse" the line to read its values. The reason that

Page 90: C Lecture 1

you do that is so you can detect errors in the input and handle them as you see fit.

Char a;

Printf(“enter value for a”);

Scanf(“%d”,&a);

Printf(“%d”,a); // prints 255 if entered 255

// prints 0 if entered 256 coz char range is from 0 to 255 so after that range it considers as beginning so 0 is printed.

The printf and scanf functions will take a bit of practice to be completely understood, but once mastered they are extremely useful.

To use a placeholder, you write %datatype replacing datatype with a value corresponding to the type of the variable to be displayed. Finally, the name of the variable to be displayed is added after the last quotation mark, but before the semi-colon.

The values for variable placeholders are as follows:

format string input type

 %c character

 %d digit (integer)

 %f float

 %lf double

 %u unsigned

 %s string

printf("The value of my variable is %d",integer_var);

printf("Here is an integer: %d, a float: %f, and a character: %c",int_var, float_var, char_var);

One commonly used escape code is \n, which is used to add a line feed to the output. Escape characters always start with a backslash "\".

printf("the number is %d\n\n",number);

will output:the number is 6 (followed by two blank lines).

Page 91: C Lecture 1

ESCAPE SEQUENCES

Escape Sequence Description

\' Single quote

\" Double quote

\\ Backslash

\nnn Octal number (nnn)

\0 Null character (really just the octal number zero)

\a Audible bell

\b Backspace

\f Formfeed

\n Newline

\r Carriage return

\t Horizontal tab

\v Vertical tab

\xnnn Hexadecimal number (nnn)

\? Question mark

C has no built-in statements for input or output.  

A library of functions is supplied to perform these operations.  The I/O library functions are listed the “header” file <stdio.h>. 

  All input and output is performed with streams.

  A "stream" is a sequence of characters organized into lines.

  Each line consists of zero or more characters and ends with the

"newline" character. ANSI C standards specify that the system must support lines that are

at least 254 characters in length (including the newline character).

Types of Streams in C  

Standard input stream is called "stdin" and is normally connected to the keyboard

  Standard output stream is called "stdout" and is normally connected

to the display screen.  

Page 92: C Lecture 1

Standard error stream is called "stderr" and is also normally connected to the screen.

Formatted Output with printf  

printf ( ) ;   This function provides for formatted output to the screen.  The

syntax is: printf ( “format”, var1, var2, … ) ;

The “format” includes a listing of the data types of the variables to be output and, optionally, some text and control character(s).

Example:           float a ;  int b ;          scanf ( “%f%d”, &a, &b ) ;          printf ( “You entered %f and %d \n”, a, b ) ;

getchar ( ) ;  

This function provides for getting exactly one character from the keyboard.

Example:

char ch;

ch = getchar ( ) ; 

putchar (char) ;  

This function provides for printing exactly one character to the screen.

Example:

    char ch;

    ch = getchar ( ) ;  /* input a character from kbd*/

    putchar (ch) ;       /* display it on the screen */

getc ( *file ) ;  

This function is similar to getchar( ) except the input can be from the keyboard or a file.

Example:

Page 93: C Lecture 1

          char ch;

          ch = getc (stdin) ; /* input from keyboard */

          ch = getc (fileptr) ; /* input from a file */

putc ( char, *file ) ;  

This function is similar to putchar ( ) except the output can be to the screen or a file.

Example:

          char ch;

          ch = getc (stdin) ; /* input from keyboard */

          putc (ch, stdout) ;  /* output to the screen */

putc (ch, outfileptr) ;  /*output to a file */

FORMATTED AND UNFORMATTED FUNCTIONS

There are numerous library functions available for I/O. These can be classified into three broad categories:

a. Console I/O functions - functions to receive input from keyboard and write output to VDU.

b. Disk I/O functions - functions to perform I/O operations on a floppy disk or hard disk.

c. Port I/O functions - functions to perform I/O operations on various ports.

Console I/O Functions:

Console I/O functions can be further classified.

Console Input/Output functions

     

   Formatted functions     Unformatted functions

Type  Input Output   Type  Input Output

char  scanf() printf()   char  getch() putch()

           getchar() putchar()

Page 94: C Lecture 1

          getche( )  

int  scanf() printf()   int - -

float   scanf() printf()   float - -

string     scanf() printf()   string gets() puts()

The basic difference between formatted and unformatted I/O functions is that the formatted functions allow the input read from the keyboard or the output displayed on the VDU to be formatted as per our requirements. For example, if values of average marks and percentage marks are to be displayed on the screen, then the details like where this output would appear on the screen, how many spaces would be present between the two values, the number of places after the decimal points etc., can be controlled using formatted functions.

The library implements a simple model of text input and output. A text consists of a sequence of lines, each ending with a newline character. If the system doesn't operate that way, the library does whatever is necessary to make it appear as if it does. For instance, the library might convert carriage return and linefeed to newline on input and back again on output.

getchar( ):

The simplest input mechanism is to read one character at a time from the standard input, normally the keyboard, with getchar( ).

int getchar(void);

getchar( ) returns the next input character each time it is called, or EOF when it encounters, end of file. The symbolic constant EOF is defined in . The value is typically -1, but tests should be written in terms of EOF so as to be independent of the specific value.

putchar( ):

The function :

int putchar(void);

is used for output. Putchar(c) puts the character c on the standard output, which is by default, the screen. Putchar() returns the character written, or EOF if an error occurs.

#include <stdio.h> #include<ctype.h> main() /* Convert input to lower case */

Page 95: C Lecture 1

{ int c; while ((c = getchar()) != EOF) putchar(tolower(c )); return 0; }

printf( ):

The output function printf() translates internal values to character.

printf(char format, arg1, arg2, ... )

The format string can contain:

Characters that are simply printed as they are. Conversion specification that begins with a % sign. Escape sequences that begins with a \ sign.

Printf() converts, formats, and prints its arguments on the standard output under the control of the format. It returns the number of characters printed. The format string contains two types of objects - ordinary characters, which are copied to the output stream, and conversion specifications, each of which causes conversion and printing of the next successive argument to printf(). Each conversion specification begins with % and ends with a conversion character. Between the % and the conversion character there may be, in order:

A minus sign, which specifies left adjustment of the converted argument.

         A number that specifies the minimum field width. The converted arguments will be printed in a field at least as wide as the specified minimum. If necessary, it will be padded on the left (or right, if left adjustment is called for) to make up the field width.

A period (.) separates the field width from the precision.

         A number, i.e., the precision that specifies the maximum number of characters to be printed from a string, or the number of digits after the decimal point of a floating-point value, or the minimum number of digits for an integer.

If the character after the % is not a conversion specification, the behavior is undefined.

sprintf( ):

Page 96: C Lecture 1

This function works similar to the printf( ) function except for one small difference. Instead of sending the output to the screen as printf( ) does, this function writes the output to an array of characters. For example, look at the following problem:

#include<stdio.h>main( ) {

int i = 10 ; char ch = 'A' ; float a = 3.14 ; char str[20] ; /* Array of characters */ printf ( "%d %c %f", i, ch, a) ; sprintf ( str, "%d %c %f", i, ch, a) ; printf ( "%s", str ) ;

}

In this program, the printf( ) prints out the values of i, ch and a on the screen, whereas sprintf( ) stores these values in the character array str. Since the string str is present in memory, what is written into str using sprintf( ) doesn't get displayed on the screen. Once str has been built, its contents can be displayed on the screen. In our program this is achieved by the second printf( ) statement.

scanf( ):

scanf( ) allows us to enter data from the keyboard that will be formatted in a certain way. The general form of scanf( ) statement is as follows:

scanf("%d %f %c",&c,&a,&ch);

Note that we are sending the addresses of variables (addresses are obtained by using & - 'address of' operator) to scanf( ) function. This is necessary because the values received from keyboard must be dropped into variables corresponding to these addresses. The values that are supplied through the keyboard must be separated by either blank(s), tab(s), or newline(s). Do not include these escape sequences in the format string.

Following is the list of conversion characters that can used with printf( ) and scanf( ) function.

Data type    Conversion character

Integer   short signed %d or %i

Page 97: C Lecture 1

   short unsigned

%u

    long signed %ld

   long unsigned

%lu

   unsigned hexadecimal

%x

   unsigned octal

%o

Real   float %f or %g

    double %lf

Characters   signed char %c

   unsigned char

%c

string     %s  Aborts program with error - %n

Hexadecimal number is small case

%hxHexadecimal number is upper case %p

pow() function – include <math.h>

int x=2,y=3;

printf(x,y,pow(x,y));// gives third power of two

main(void) { } //correct void main() //correct

gets( ):

The gets( ) function receives a string from the keyboard. The scanf( ) function has some limitations while receiving a string of characters because the moment a blank character is typed, scanf( ) assumes that the end of the data is being entered. So it is possible to enter only one word string using scanf( ). To enter multiple words in to the string, the gets( ) function can be used. Spaces and tabs are perfectly accepted as part of the string. It is terminated when the enter key is hit.

gets(variable name);

Page 98: C Lecture 1

For example:

gets(name);

puts( ):

The puts( ) function works exactly opposite to gets( ) function. It outputs a string to the screen. Puts( ) can output a single string at a time.

puts(variable name);

For example :

#include<stdio.h>main( )

{

char name[40]; puts("Enter your name"); gets(name); puts("Your name is"); puts(name);

}

Useful functions include:

printf() Print a formatted string to stdout. scanf() Read formatted data from stdin. putchar() Print a single character to stdout. getchar() Read a single character from stdin. puts() Print a string to stdout. gets() Read a line from stdin.

The three most useful PC console I/O functions are:

getch() Get a character from the keyboard (no need to press Enter). getche() Get a character from the keyboard and echo it. kbhit() Check to see if a key has been pressed.

Page 99: C Lecture 1

Using the wrong format code for a particular data type can lead to bizarre output. Further control can be obtained with modifier codes; for example, a numeric prefix can be included to specify the minimum field width: %10d

This specifies a minimum field width of ten characters. If the field width is too small, a wider field will be used. Adding a minus sign: %-10d

- causes the text to be left-justified. A numeric precision can also be specified: %6.3f

This specifies three digits of precision in a field six characters wide. A string precision can be specified as well, to indicate the maximum number of characters to be printed. For example: /* prtint.c */

#include <stdio.h>

void main() { printf( "<%d>\n", 336 ); printf( "<%2d>\n", 336 ); printf( "<%10d>\n", 336 ); printf( "<%-10d>\n", 336 ); }

This prints: <336> <336> < 336> <336 >

Similarly: /* prfloat.c */

#include <stdio.h>

void main() { printf( "<%f>\n", 1234.56 ); printf( "<%e>\n", 1234.56 ); printf( "<%4.2f>\n", 1234.56 ); printf( "<%3.1f>\n", 1234.56 ); printf( "<%10.3f>\n", 1234.56 ); printf( "<%10.3e>\n", 1234.56 );

Page 100: C Lecture 1

}

-- prints: <1234.560000> <1.234560e+03> <1234.56> <1234.6> < 1234.560> < 1.234e+03>

And finally: /* prtstr.c */

#include <stdio.h>

void main() { printf( "<%2s>\n", "Barney must die!" ); printf( "<%22s>\n", "Barney must die!" ); printf( "<%22.5s>\n", "Barney must die!" ); printf( "<%-22.5s>\n", "Barney must die!" ); }

-- prints: <Barney must die!> < Barney must die!> < Barne> <Barne >

C - BUILT-IN LIBRARY FUNCTIONS

String Manipulation Functions

← char *strcpy (char *dest, char *src); Copy src string into dest string.

← char *strncpy(char *string1, char *string2, int n); Copy first n characters of string2 to stringl .

← int strcmp(char *string1, char *string2); Compare string1 and string2 to determine alphabetic order.

Page 101: C Lecture 1

← int strncmp(char *string1, char *string2, int n); Compare first n characters of two strings.

← int strlen(char *string); Determine the length of a string.

← char *strcat(char *dest, const char *src); Concatenate string src to the string dest.

← char *strncat(char *dest, const char *src, int n); Concatenate n chracters from string src to the string dest.

← char *strchr(char *string, int c); Find first occurrence of character c in string.

← char *strrchr(char *string, int c); Find last occurrence of character c in string.

← char *strstr(char *string2, char string*1); Find first occurrence of string string1 in string2.

← char *strtok(char *s, const char *delim) ;Parse the string s into tokens using delim as delimiter.

Memory Management Functions

← void *calloc(int num elems, int elem_size); Allocate an array and initialise all elements to zero .

← void free(void *mem address); Free a block of memory.

Page 102: C Lecture 1

← void *malloc(int num bytes); Allocate a block of memory.

← void *realloc(void *mem address, int newsize); Reallocate (adjust size) a block of memory.

Buffer Manipulation

← void* memcpy(void* s, const void* ct, int n); Copies n characters from ct to s and returns s. s may be corrupted if objects overlap.

← int memcmp(const void* cs, const void* ct, int n); Compares at most (the first) n characters of cs and ct, returning negative value if cs<ct, zero if cs==ct, positive value if cs>ct.

← void* memchr(const void* cs, int c, int n); Returns pointer to first occurrence of c in first n characters of cs, or NULL if not found.

← void* memset(void* s, int c, int n); Replaces each of the first n characters of s by c and returns s.

← void* memmove(void* s, const void* ct, int n); Copies n characters from ct to s and returns s. s will not be corrupted if objects overlap.

Character Functions

← int isalnum(int c); The function returns nonzero if c is alphanumeric

← int isalpha(int c); The function returns nonzero if c is alphabetic only

Page 103: C Lecture 1

← int iscntrl(int c); The function returns nonzero if c is a control chracter

← int isdigit(int c); The function returns nonzero if c is a numeric digit

← int isgraph(int c); The function returns nonzero if c is any character for which either isalnum or ispunct returns nonzero.

← int islower(int c); The function returns nonzero if c is a lower case character.

← int isprint(int c); The function returns nonzero if c is space or a character for which isgraph returns nonzero.

← int ispunct(int c); The function returns nonzero if c is punctuation

← int isspace(int c); The function returns nonzero if c is space character

← int isupper(int c); The function returns nonzero if c is upper case character

← int isxdigit(int c); The function returns nonzero if c is hexa digit

Page 104: C Lecture 1

← int tolower(int c); The function returns the corresponding lowercase letter if one exists and if isupper(c); otherwise, it returns c.

← int toupper(int c); The function returns the corresponding uppercase letter if one exists and if islower(c); otherwise, it returns c.

Error Handling Functions

← void perror(const char *s); produces a message on standard error output describing the last error encountered.

← char *strerror(int errnum ); returns a string describing the error code passed in the argument errnum.

C LIBRARY FUNCTIONS :

C MATH LIBRARY

* The math library requires the declaration:

#include <math.h>The math functions consist of: sin( x ) Sine of x. cos( x ) Cosine of x. tan( x ) Tangent of x. asin( x ) Inverse sine of x. acos( x ) Inverse cosine of x. atan( x ) Inverse tangent of x. sinh( x ) Hyperbolic sine of x. cosh( x ) Hyperbolic cosine of x. tanh( x ) Hyperbolic tangent of x. exp( x ) Exponential function -- e^x. log( x ) Natural log of x. log10( x ) Base 10 log of x. pow( x, y ) Power function -- x^y. sqrt( x ) Square root of x. ceil( x ) Smallest integer not less than x, returned as double. floor( x ) Greatest integer not greater than x, returned as double.

Page 105: C Lecture 1

fabs( x ) Absolute value of x.All values are "doubles", and trig values are expressed in radians.

C STANDARD UTILITY LIBRARY & TIME LIBRARY

* The utility functions library features a grab-bag of functions. It requires the declaration:

#include <stdlib.h>Useful functions include: atof( <string> ) Convert numeric string to double value. atoi( <string> ) Convert numeric string to int value. atol( <string> ) Convert numeric string to long value. rand() Generates pseudorandom integer. srand( <seed> ) Seed random-number generator -- "seed" is an "int". exit( <status> ) Exits program -- "status" is an "int". system( <string> ) Tells system to execute program given by the seed. abs( n ) Absolute value of "int" argument. labs( n ) Absolute value of long-int argument.

The functions "atof()", "atoi()", and "atol()" will return 0 if they can't convert the string given them into a value.

The time and date library includes a wide variety of functions, some of them obscure and nonstandard. This library requires the declaration:

#include <time.h>The most essential function is "time()", which returns the number of seconds since some long-ago date. It returns a value as "time_t" (a "long") as defined in the header file.

The following function uses "time()" to implement a program delay with resolution in seconds:

/* delay.c */

#include <stdio.h> #include <time.h>

void sleep( time_t delay );

void main() { puts( "Delaying for 3 seconds." ); sleep( 3 ); puts( "Done!" ); }

Page 106: C Lecture 1

void sleep( time_t delay ) { time_t t0, t1; time( &t0 ); do { time( &t1 ); } while (( t1 - t0 ) < delay ); }

The "ctime()" function converts the time value returned by "time()" into a time-and-date string. The following little program prints the current time and date: /* time.c */

#include <stdio.h> #include <time.h>

void main() { time_t *t; time( t ); puts( ctime( t )); }This program prints a string of the form: Tue Dec 27 15:18:16 1994

THE C "SPRINTF()" FUNCTION

* The "sprintf" function creates strings with formatted data. Technically speaking, this is part of the standard-I/O library, and requires the declaration:

#include <stdio.h>However, it is really a string function and needs to be discussed along with the other string functions. The syntax of "sprintf()" is exactly the same as it is for "printf()", with the notable exception that the first parameter is a pointer to a string. For example: /* csprntf.c */

#include <stdio.h>

void main() { char b[100]; int i = 42;

Page 107: C Lecture 1

float f = 1.1234f; sprintf( b, "Formatted data: %d / %f", i, f ); puts( b ); }

-- prints the string: Formatted data: 42 / 1.1234

There is also an "sscanf()" function that similarly mirrors "scanf()" functionality.

C STRING FUNCTION LIBRARY

* The string-function library requires the declaration:

#include <string.h>The most important string functions are as follows: strlen() Get length of a string. strcpy() Copy one string to another. strcat() Link together (concatenate) two strings. strcmp() Compare two strings. strchr() Find character in string. strstr() Find string in string. strlwr() Convert string to lowercase. strupr() Convert string to uppercase.* The "strlen()" function gives the length of a string, not including the NULL character at the end:

#include <stdio.h> #include <string.h>

void main() { char *t = "XXX"; printf( "Length of <%s> is %d.\n", t, strlen( t )); }

This prints: Length of <XXX> is 3.

* The "strcpy" function copies one string from another. For example:

#include <stdio.h> #include <string.h>

void main() {

Page 108: C Lecture 1

char s1[100], s2[100]; strcpy( s1, "string 2" ); strcpy( s2, "string 1" );

puts( "Original strings: " ); puts( "" ); puts( s1 ); puts( s2 ); puts( "" );

strcpy( s2, s1 );

puts( "New strings: " ); puts( "" ); puts( s1 ); puts( s2 ); }

This will print: Original strings:

string 1 string 2

New strings:

string 1 string 1

Please be aware of two features of this program: This program assumes that "s1" has enough space to store the final

string. The "strcpy()" function won't bother to check, and will give erroneous results if that is not the case.

A string constant can be used as the source string instead of a string variable. Using a string constant for the destination, of course, makes no sense.

These comments are applicable to most of the other string functions.

There is a variant form of "strcpy" named "strncpy" that will copy "n" characters of the source string to the destination string, presuming there are that many characters available in the source string. For example, if the following change is made in the example program:

strncpy( s2, s1, 5 );

Page 109: C Lecture 1

-- then the results change to: New strings:

string 1 stringNotice that the parameter "n" is declared "size_t", which is defined in "string.h".

* The "strcat()" function joins two strings:

#include <stdio.h> #include <string.h>

void main() { char s1[50], s2[50]; strcpy( s1, "Tweedledee " ); strcpy( s2, "Tweedledum" ); strcat( s1, s2 ); puts( s1 ); }

This prints: Tweedledee TweedledumThere is a variant version of "strcat()" named "strncat()" that will append "n" characters of the source string to the destination string. If the example above used "strncat()" with a length of 7: strncat( s1, s2, 7 );-- the result would be: Tweedledee TweedleAgain, the length parameter is of type "size_t".

* The "strcmp()" function compares two strings:

#include <stdio.h> #include <string.h>

#define ANSWER "blue"

void main() { char t[100]; puts( "What is the secret color?" ); gets( t );

Page 110: C Lecture 1

while ( strcmp( t, ANSWER ) != 0 ) { puts( "Wrong, try again." ); gets( t ); } puts( "Right!" ); }

The "strcmp()" function returns a 0 for a successful comparison, and nonzero otherwise. The comparison is case-sensitive, so answering "BLUE" or "Blue" won't work.

There are three alternate forms for "strcmp()":

A "strncmp()" function which, as might be guessed, compares "n" characters in the source string with the destination string: "strncmp( s1, s2, 6 )".

A "stricmp()" function that ignores case in comparisons. A case-insensitive version of "strncmp" called "strnicmp".

* The "strchr" function finds the first occurrence of a character in a string. It returns a pointer to the character if it finds it, and null if not. For example:

#include <stdio.h> #include <string.h>

void main() { char *t = "MEAS:VOLT:DC?"; char *p; p = t; puts( p ); while(( p = strchr( p, ':' )) != NULL ) { puts( ++p ); } }

This prints: MEAS:VOLT:DC? VOLT:DC? DC?The character is defined as a character constant, which C regards as an "int". Notice how the example program increments the pointer before using it ("++p") so that it doesn't point to the ":" but to the character following it.

Page 111: C Lecture 1

The "strrchr()" function is almost the same as "strchr()", except that it searches for the last occurrence of the character in the string.

* The "strstr()" function is similar to "strchr()" except that it searches for a string, instead of a character. It also returns a pointer:

char *s = "Black White Brown Blue Green"; ... puts( strstr( s, "Blue" ) );

* The "strlwr()" and "strupr()" functions simply perform lowercase or uppercase conversion on the source string. For example:

#include <stdio.h> #include <string.h>

void main() { char *t = "Die Barney die!"; puts( strlwr( t ) ); puts( strupr( t ) ); }

-- prints: die barney die! DIE BARNEY DIE!These two functions only implemented in some compilers and are not part of ANSI C.

C CHARACTER CLASS TEST LIBRARY

* These functions perform various tests on characters. They require the declaration:

#include <ctype.h>The character is represented as an "int" and the functions return an "int". They return 0 if the test is false and non-0 if the test is true: isalnum( c ) Character is alpha or digit. isalpha( c ) Character is alpha. iscntrl( c ) Character is control character. isdigit( c ) Character is decimal digit. isgraph( c ) Character is printing character (except space). islower( c ) Character is lower-case. isprint( c ) Character is printing character (including space). ispunct( c ) Character is printing character but not space/alpha-digit. isspace( c ) Character is space, FF, LF, CR, HT, VT. isupper( c ) Character is upper-case.

Page 112: C Lecture 1

isxdigit( c ) Character is hex digit.The library also contains two conversion functions that also accept and return an "int": tolower( c ) Convert to lower case. toupper( c ) Convert to upper case.

C COMMAND LINE ARGUMENTS

* C allows a program to obtain the command line arguments provided when the executable is called, using two optional parameters of "main()" named "argc (argument count)" and "argv (argument vector)".

The "argc" variable gives the count of the number of command-line parameters provided to the program. This count includes the name of the program itself, so it will always have a value of at least one. The "argv" variable is a pointer to an array of strings, with each element containing one of the command-line arguments.

The following example program demonstrates:

/* cmdline.c */

#include <stdio.h>

void main( int argc, char *argv[] ) { int ctr; for( ctr=0; ctr < argc; ctr++ ) { puts( argv[ctr] ); } }If this program is run from the command line as follows: stooges moe larry curley -- the output is: stooges moe larry curley

In practice, the command line will probably take a number of arguments, some of which will indicate options or switches, designated by a leading "-" or "/". Some of the switches may be specified separately or together, and some may accept an associated parameter. Other arguments will be text strings, giving numbers, file names, or other data.

Page 113: C Lecture 1

The following example program demonstrates parsing the command-line arguments for an arbitrary program. It assumes that the legal option characters are "A", "B", "C", and "S", in either upper- or lower-case. The "S" option must be followed by some string representing a parameter.

/* cparse.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> main( int argc, char *argv[] ) { int m, n, /* Loop counters. */ l, /* String length. */ x, /* Exit code. */ ch; /* Character buffer. */ char s[256]; /* String buffer. */ for( n = 1; n < argc; n++ ) /* Scan through args. */ { switch( (int)argv[n][0] ) /* Check for option character. */ { case '-': case '/': x = 0; /* Bail out if 1. */ l = strlen( argv[n] ); for( m = 1; m < l; ++m ) /* Scan through options. */ { ch = (int)argv[n][m]; switch( ch ) { case 'a': /* Legal options. */ case 'A': case 'b': case 'B': case 'C': case 'd': case 'D': printf( "Option code = %c\n", ch ); break; case 's': /* String parameter. */ case 'S': if( m + 1 >= l ) { puts( "Illegal syntax -- no string!" ); exit( 1 ); } else

Page 114: C Lecture 1

{ strcpy( s, &argv[n][m+1] ); printf( "String = %s\n", s ); } x = 1; break; default: printf( "Illegal option code = %c\n", ch ); x = 1; /* Not legal option. */ exit( 1 ); break; } if( x == 1 ) { break; } } break; default: printf( "Text = %s\n", argv[n] ); /* Not option -- text. */ break; } } puts( "DONE!" ); }

For a more practical example, here's a simple program, based on an example from the previous chapter, that attempts to read the names of an input and output file from the command line. If no files are present, it uses standard input and standard output instead. If one file is present, it is assumed to be the input file and opens up standard output. This is a useful template for simple file-processing programs. /* cpfile.c */

#include <stdio.h> #include <stdlib.h> #define MAX 256

void main( unsigned int argc, unsigned char *argv[] ) { FILE *src, *dst; char b[MAX]; /* Try to open source and destination files. */ switch (argc) {

Page 115: C Lecture 1

case 1: /* No parameters, use stdin-stdout. */ src = stdin; dst = stdout; break;

case 2: /* One parameter -- use input file & stdout. */ if ( ( src = fopen( argv[1], "r" )) == NULL ) { puts( "Can't open input file.\n" ); exit( 0 ); } dst = stdout; break;

case 3: /* Two parameters -- use input and output files. */ if ( ( src = fopen( argv[1], "r" )) == NULL ) { puts( "Can't open input file.\n" ); exit( 0 ); } if ( ( dst = fopen( argv[2], "w" )) == NULL ) { puts( "Can't open output file.\n" ); exit( 0 ); } break;

default: /* Too many parameters. */ puts( "Wrong parameters.\n" ); exit( 0 );

} /* Copy one file to the next. */ while( ( fgets( b, MAX, src ) ) != NULL ) { fputs( b, dst ); } /* All done, close up shop. */ fclose( src ); fclose( dst ); }

Page 116: C Lecture 1

POINTERS TO C FUNCTIONS

* This document has explained how to declare pointers to variables, arrays, and structures in C. It is also possible to define pointers to functions. This feature allows functions to be passed as arguments to other functions. This is useful for, say, building a function that determines solutions to a range of math functions.

The syntax for declaring pointers to functions is obscure, and so let's start with an idiot example: declaring a pointer to the standard library function "printf()":

/* ptrprt.c */

#include <stdio.h>

void main() { int (*func_ptr) (); /* Declare the pointer. */ func_ptr = printf; /* Assign it a function. */ (*func_ptr) ( "Printf is here!\n" ); /* Execute the function. */ }The function pointer has to be declared as the same type ("int" in this case) as the function it represents.

Next, let's pass function pointers to another function. This function will assume the functions passed to it are math functions that accept double and return double values:

/* ptrroot.c */

#include <stdio.h> #include <math.h> void testfunc ( char *name, double (*func_ptr) () ); void main() { testfunc( "square root", sqrt ); } void testfunc ( char *name, double (*func_ptr) () ) { double x, xinc; int c; printf( "Testing function %s:\n\n", name ); for( c=0; c < 20; ++c )

Page 117: C Lecture 1

{ printf( "%d: %f\n", c,(*func_ptr)( (double)c )); } }It is obvious that not all functions can be passed to "testfunc()". The function being passed must agree with the expected number and type of parameters, as well as with the value returned.

C DYNAMIC MEMORY ALLOCATION & DEALLOCATION

* For simple programs, it is OK to just declare an array of a given size:

char buffer[1024]In more sophisticated programs, this leads to trouble. There may be no way of knowing how big an array needs to be for the specific task the program is performing, and so allocating an array in a fixed size will either result in wasted memory or in not having enough to do the job.

The answer to this problem is to have the program allocate the memory at runtime, and that's what the "malloc()" library function does. For example, let's use "malloc()" to allocate an array of "char":

/* malloc.c */

#include <malloc.h> #include <stdio.h> #include <stdlib.h> /* For "exit" function. */

void main() { char *p; /* Pointer to array. */ unsigned count; /* Size of array. */ puts( "Size of array?" ); scanf( "%d", count ); /* Get size in bytes. */ p = (char *)malloc( (size_t)count ); /* Allocate array. */ if( p == NULL ) /* Check for failure. */ { puts( "Can't allocate memory!" ); exit( 0 ); } puts( "Allocated array!" ); free( p ); /* Release memory. */ }The header file "malloc.h" must be included, and a pointer to the memory block to be allocated must be declared. The "malloc()" function sets the pointer to the allocated memory block with:

Page 118: C Lecture 1

p = (char *)malloc( (size_t)count );The count is in bytes and it is "cast" to the type of "size_t", which is defined in "malloc.h". The pointer returned by "malloc()" is "cast" to type "char *", that is, a pointer to type "char". By default, in ANSI C, "malloc()" returns a pointer of type "void", which allows the pointer to be cast to any other type.

If the "malloc()" fails because it can't allocate the memory, it returns the value null (as defined in "stdio.h").

It is simple to allocate other data types by changing the "cast" operations:

int *buf; ... buf = (int *)malloc( (size_t)sizeof( int ) * count );The "sizeof()" function is used to determine the number of bytes in the "int" data type.

When the programs finished using the memory block, it get rids of it using the "free" function:

free( p );C also contains two other memory-allocation functions closely related to "malloc()": the "calloc()" function, which performs the same function as "malloc()" but allows the block allocated to be specified in terms of number of elements: void *calloc( size_t <number_elements>, size_t <sizeof_element_type> );-- and the "realloc()" function, which reallocates the size of an array that's already been allocated: void *realloc( void *<block_pointer>, size_t <size_in_bytes> );

COMMON PROGRAMMING PROBLEMS IN C

* There are a number of common programming pitfalls in C that even trap experienced programmers:

1: Confusing "=" (assignment operator) with "==" (equality operator). For example:

if ( x = 1 ) { }-- is bogus, and so is: for ( x == 1; ...2: Confusing precedence of operations in expressions. When in doubt, use parentheses to enforce precedence.

Page 119: C Lecture 1

3: Confusing structure-member operators. If "struct_val" is a structure and "struct_ptr" is a pointer to a structure, then:

struct_val->myname-- is wrong and so is: struct_ptr.myname4: Using incorrect formatting codes for "printf()" and "scanf()". Using a "%f" to print an "int", for example, can lead to bizarre output.

5: Remember that the actual base index of an array is 0, and the final index is 1 less than the declared size. For example:

int data[20]; ... for ( x = 1; x <= 20; ++x ) { printf( "%d\n", data[x] ); }-- will give invalid results when "x" is 20. Since C does not do bounds checking, this one might be hard to catch.

6: Muddling syntax for multidimensional arrays. If:

data[10][10]-- is a two-dimensional array, then: data[2][7]-- will select an element in that array. However: data[ 2, 7 ]-- will give invalid results but not be flagged as an error by C.

7: Confusing strings and character constants. The following is a string:

"Y"-- as opposed to the character constant: 'Y'This can cause troubles in comparisons of strings against character constants.

8: Forgetting that strings end in a null character ('\0'). This means that a string will always be one character bigger than the text it stores. It can also cause trouble if a string is being created on a character-by-character basis, and the program doesn't tack the null character onto the end of it.

9: Failing to allocate enough memory for a string -- or, if pointers are declared, to allocate any memory for it at all.

10: Declaring a string with a fixed size and then assigning it to a string literal:

Page 120: C Lecture 1

char a[256] = "This doesn't work!";11: Failing to check return values from library functions. Most library functions return an error code; while it may not be desireable to check every invocation of "printf()", be careful not to ignore error codes in critical operations.

Of course, forgetting to store the value returned by a function when that's the only way to get the value out of it is a bonehead move, but people do things like that every now and then.

12: Having duplicate library-function names. The compiler will not always catch such bugs.

13: Forgetting to specify header files for library functions.

14: Specifying variables as parameters to functions when pointers are supposed to be specified, and the reverse. If the function returns a value through a parameter, that means it must be specified as a pointer:

myfunc( &myvar );The following will not do the job: myfunc( myvar );Remember that a function may require a pointer as a parameter even if it doesn't return a value, though as a rule this is not a good programming practice.

15: Getting mixed up when using nested "if" and "else" statements. The best way to avoid problems with this is to always use brackets. Avoiding complicated "if" constructs is also a good idea; use "switch" if there's any choice in the matter. Using "switch" is also useful even for simple "if" statements, since it makes it easier to expand the construct if that is necessary.

16: Forgetting semicolons -- though the compiler usually catches this -- or adding one where it isn't supposed to be -- which it usually doesn't. For example:

for( x = 1; x < 10; ++x ); { printf( "%d\n", x ) }-- never prints anything.

17: Forgetting "break" statements in "switch" constructs. As commented earlier, doing so will simply cause execution to flow from one clause of the "switch" to the next.

18: Careless mixing and misuse of signed and unsigned values, or of different data types. This can lead to some insanely subtle bugs. One particular problem to watch out for is declaring single character variables as "unsigned char". Many

Page 121: C Lecture 1

I/O functions will expect values of "unsigned int" and fail to properly flag EOF. It is recommended to cast function arguments to the proper type even if it appears that type conversion will take care of it on its own.

19: Confusion of variable names. It is recommended that such identifiers be unique in the first 6 characters to ensure portability of code.

20: In general, excessively tricky and clever code. Programs are nasty beasts and even if it works, it will have to be modified and even ported to different languages. Maintain a clean structure and do the simple straightforward thing, unless it imposes an unacceptable penalty.

STDIO.H

stdio.h, which stands for "standard input/output header", is the header in the C standard library that contains macro definitions, constants, and declarations of functions and types used for various standard input and output operations. Functions declared in stdio.h are extremely popular, since as a part of the C standard library, they are guaranteed to work on any platform that supports C

Functions declared in stdio.h can generally be divided into two categories: the functions for file manipulation and the functions for input-output manipulation.

Name Notes

File manipulation functions

fclose closes a file associated with the FILE * value passed to it

fopen, freopen opens a file for certain types of reading or writing

remove removes a file (deletes it)

rename renames a file

rewindacts as if fseek(stream, 0L, SEEK_SET) was called for the stream passed, and then its error indicator cleared

Page 122: C Lecture 1

tmpfilecreates and open a temporary file, which is deleted when closed with fclose()

Input-output manipulation functions

clearerr clears end-of-file and error indicators for a given stream

feofchecks whether an end-of-file indicator has been set for a given stream

ferrorchecks whether an error indicator has been set for a given stream

fflushforces any pending buffered output to be written to the file associated with a given stream

fgetposstores the file position indicator of the stream associated by its first argument (a FILE *) to its second argument (a fpos_t *)

fgetc returns one character from a file

fgets gets a string from the file (ending at newline or end-of-file)

fputc writes one character to a file

fputs writes a string to a file

ftellreturns a file-position indicator which can then be passed to fseek

fseek seeks through a file

Page 123: C Lecture 1

fsetpossets the file position indicator of a stream associated by its first argument (a FILE *) as stored in its second argument (a fpos_t *)

fread reads data from a file

fwrite writes data to a file

getc

reads and returns a character from a given stream and advances the file position indicator; it is allowed to be a macro with the same effects as fgetc, except that it may evaluate the stream more than once

getchar has the same effects as getc(stdin)

getsreads characters from stdin until a newline is encountered and stores them in its only argument

printf, vprintf used to print to the standard output stream

fprintf, vfprintf used to print to a file

sprintf, snprintf, vsprintf, vsnprintf

used to print to a char array (C string)

perror writes an error message to stderr

putcwrites and returns a character to a stream and advances the file position indicator for it; equivalent to fputc, except that a macro version may evaluate the stream more than once

putchar, has the same effects as putc(stdout)

Page 124: C Lecture 1

fputchar

scanf, vscanf used to input from the standard input stream

fscanf, vfscanf used to input from a file

sscanf, vsscanf

used to input from a char array (e.g., a C string)

setbuf, setvbuf sets the buffering mode for a given stream

tmpnam creates a temporary filename

ungetc pushes a character back onto a stream

puts outputs a character string to stdout

conio.h

conio.h is a C header file used in old MS-DOS compilers to create text user interfaces. It is not described in The C Programming Language book , and it is not part of the C standard library, ISO C nor is it required by POSIX.

Member functions

int kbhit(void) Determines if a keyboard key was pressed.

int getch(void)Reads a character directly from the console without buffer, and without echo.

int getche(void)Reads a character directly from the console without buffer, but with echo.

Page 125: C Lecture 1

int ungetch(int c)Puts the character c back into the keyboard buffer.

char *cgets(char *buffer) Reads a string directly from the console.

int cscanf(char *format, arg0,... argn)

Reads formated values directly from the console.

int putch(int c) Writes a character directly to the console.

int cputs(const char *string) Writes a string directly to the console.

int cprintf(const char *format, arg0,... argn)

Formats values and writes them directly to the console.

string.h

string.h is the header in the C standard library for the C programming language which contains macro definitions, constants, and declarations of functions and types used not only for string handling but also various memory handling functions; the name is thus something of a misnomer.

Functions declared in string.h are extremely popular, since as a part of the C standard library, they are guaranteed to work on any platform which supports C. However, some security issues exist with these functions, such as buffer overflows, leading programmers to prefer safer, possibly less portable variants.

Functions

Name Notes

void *memcpy(void *dest, const void *src, size_t n);

copies n bytes between two memory areas, which must not overlap

Page 126: C Lecture 1

void *memmove(void *dest, const void *src, size_t n);

copies n bytes between two memory areas; unlike with memcpy the areas may overlap

void *memchr(const void *s, char c, size_t n);

returns a pointer to the first occurrence of c in the first n bytes of s, or NULL if not found

int memcmp(const void *s1, const void *s2, size_t n);

compares the first n characters of two memory areas

void *memset(void *, int, size_t);

overwrites a memory area with a byte pattern

char *strcat(char *dest, const char *src);

appends the string src to dest

char *strncat(char *, const char *, size_t);

appends at most n characters of the string src to dest

char *strchr(const char *, int);

locates a character in a string, searching from the beginning

char *strrchr(const char *, int);

locates a character in a string, searching from the end

int strcmp(const char *, const char *);

compares two strings lexicographically

int strncmp(const char *, const char *, size_t);

compares up to the first n bytes of two strings lexicographically

int strcoll(const char *, const char *);

compares two strings using the current locale's collating order

Page 127: C Lecture 1

char *strcpy(char *toHere, const char *fromHere);

copies a string from one location to another

char *strncpy(char *toHere, const char *fromHere, size_t);

copies up to n bytes of a string from one location to another

char *strerror(int);returns the string representation of an error number e.g. errno (not thread-safe)

size_t strlen(const char *); finds the length of a C string

size_t strspn(const char *s, const char *accept);

determines the length of the maximal initial substring of s consisting entirely of characters in accept

size_t strcspn(const char *s, const char *reject);

determines the length of the maximal initial substring of s consisting entirely of characters not in reject

char *strpbrk(const char *s, const char *accept);

finds the first occurrence of any character in accept in s

char *strstr(const char *haystack, const char *needle);

finds the first occurrence of the string "needle" in the longer string "haystack".

char *strtok(char *, const char *);

parses a string into a sequence of tokens; non-thread safe in the spec, non-reentrant

size_t strxfrm(char *dest, const char *src, size_t n);

transforms src into a collating form, such that the numerical sort order of the transformed string is equivalent to the collating order of src.

Page 128: C Lecture 1