C Lecture 1

Share Embed Donate


Short Description

C language...

Description

ALGORITHM An algorithm is any set of detailed instructions which results in a predictable endstate from a known beginning. Algorithms are only as good as the instructions given, however, and the result will be incorrect if the algorithm is not properly defined. To make a computer do anything, you have to write a computer program. To write a computer program, you have to tell the computer, step by step, exactly what you want it to do. The computer then "executes" the program, following each step mechanically, to accomplish the end goal. When you are telling the computer what to do, you also get to choose how it's going to do it. That's where computer algorithms come in. The algorithm is the basic technique used to get the job done. Let's follow an example to help get an understanding of the algorithm concept. Let's say that you have a friend arriving at the airport, and your friend needs to get from the airport to your house. Here are four different algorithms that you might give your friend for getting to your home: •

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



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



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



The bus algorithm:  Outside baggage claim, catch bus number 70.  Transfer to bus 14 on Main Street.  Get off on Elm street.  Walk two blocks north to my house. All four of these algorithms accomplish exactly the same goal, but each algorithm does it in completely different way. Each algorithm also has a different cost and a different travel time. Taking a taxi, for example, is probably the fastest way, but also the most expensive. Taking the

bus is definitely less expensive, but a whole lot slower. You choose the algorithm based on the circumstances. In computer programming, there are often many different ways -- algorithms -- to accomplish any given task. Each algorithm has advantages and disadvantages in different situations. PSEUDOCODE An outline of a program, written in a form that can easily be converted into real programming statements. For example, the pseudocode If student's grade is greater than or equal to 60 Print "passed" else Print "failed" ----------------------------------------------initialize passes to zero initialize failures to zero initialize student to one while student counter is less than or equal to ten input the next exam result if the student passed add one to passes else add one to failures add one to student counter print the number of passes print the number of failures if eight or more students passed print "raise tuition" -----------------------------------------------Some Keywords that should be used For looping and selection, The keywords that are to be used include Do While...EndDo; Do Until...Enddo; Case...EndCase; If...Endif; Call ... with (parameters); Call; Return ....; Return; When; Always use scope terminators for loops and iteration. As verbs, use the words Generate, Compute, Process, etc. Words such as set, reset, increment, compute, calculate, add, sum, multiply, ... print, display, input,

output, edit, test , etc. with careful indentation tend to foster desirable pseudocode. Do not include data declarations in your pseudocode. Pseudocode (pronounced SOO-doh-kohd) is a detailed yet readable description of what a computer program or algorithm must do, expressed in a formally-styled natural language rather than in a programming language. Pseudocode is sometimes used as a detailed step in the process of developing a program. It allows designers or lead programmers to express the design in great detail and provides programmers a detailed template for the next step of writing code in a specific programming language. Pseudocode cannot be compiled nor executed, and there are no real formatting or syntax rules. It is simply one step - an important one - in producing the final code. The benefit of pseudocode is that it enables the programmer to concentrate on the algorithms without worrying about all the syntactic details of a particular programming language. In fact, you can write pseudocode without even knowing what programming language Because pseudocode is detailed yet readable, it can be inspected by the team of designers and programmers as a way to ensure that actual programming is likely to match design specifications. Catching errors at the pseudocode stage is less costly than catching them later in the development process. Once the pseudocode is accepted, it is rewritten using the vocabulary and syntax of a programming language. FLOWCHART The flowchart is a means of visually presenting the flow of data through an information processing systems, the operations performed within the system and the sequence in which they are performed. The program flowchart can be likened to the blueprint of a building. As we know a designer draws a blueprint before starting construction on a building. Similarly, a programmer prefers to draw a flowchart prior to writing a computer program. As in the case of the drawing of a blueprint, the flowchart is drawn according to defined rules and using standard flowchart symbols A flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem. Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts facilitate communication between programmers and business people. These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the

flowchart is drawn, it becomes easy to write the program in any high level language. Often we see how flowcharts are helpful in explaining the program to others. Hence, it is correct to say that a flowchart is a must for the better documentation of a complex program. Flowcharts are usually drawn using some standard symbols; however, some special symbols can also be developed when required. Some standard symbols, which are frequently required for flowcharting many computer programs are shown in Fig. 25.1 Start or end of the program Computational steps or processing function of a program Input or output operation Decision making and branching

Connector or joining of two parts of program Magnetic Tape Magnetic Disk

Off-page connector Flow line Annotation

Display

The following are some guidelines in flowcharting:

a. In drawing a proper flowchart, all necessary requirements should be listed out in logical order. b. The flowchart should be clear, neat and easy to follow. There should not be any room for ambiguity in understanding the flowchart. c. The usual direction of the flow of a procedure or system is from left to right or top to bottom. d. Only one flow line should come out from a process symbol.

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

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

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

h. If the flowchart becomes complex, it is better to use connector symbols to reduce the number of flow lines. Avoid the intersection of flow lines if you want to make it more effective and better way of communication. i. Ensure that the flowchart has a logical start and finish. j. It is useful to test the validity of the flowchart by passing through it with a simple test data. ADVANTAGES OF USING FLOWCHARTS

The benefits of flowcharts are as follows: 1. Communication: Flowcharts are better way of communicating the logic of a system to all concerned. 2. Effective analysis: With the help of flowchart, problem can be analysed in more effective way. 3. Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes. 4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase. 5. Proper Debugging: The flowchart helps in debugging process. 6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part LIMITATIONS OF USING FLOWCHARTS 1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex and clumsy. 2. Alterations and Modifications: If alterations are required the flowchart may require re-drawing completely. 3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem. 4. The essentials of what is done can easily be lost in the technical details of how it is done. Examples: Draw a flowchart to find the sum of first 50 natural numbers.

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

Example 3 Draw a flowchart for computing factorial N (N!) Where N! = 1 ´ 2 ´ 3 ´ …… N .

Assignment :  Algorithm and flowchart to find the roots of quadratic equation ax2+bx+c=0 for all cases  Algorithm and flowchart for finding maximum and minimum of given n numbers  Algorithm and flowchart to generate Fibonacci numbers up to n In mathematics, the Fibonacci numbers are the numbers in the following sequence:

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

COMPILERS and INTERPRETERS A compiler is a special program that processes statements written in a particular programming language and turns them into machine language or "code" that a computer's processor uses. Typically, a programmer writes language statements in a language such as Pascal or C one line at a time using an editor. The file that is created contains what are called the source statements . The programmer then runs the appropriate language compiler, specifying the name of the file that contains the source statements. When executing (running), the compiler first parses (or analyzes) all of the language statements syntactically one after the other and then, in one or more successive stages or "passes", builds the output code, making sure that statements that refer to other statements are referred to correctly in the final code. Traditionally, the output of the compilation has been called object code or sometimes an object module . (Note that the term "object" here is not related to object-oriented programming .) The object code is machine code that the processor can process or "execute" one instruction at a time. More recently, the Java programming language, a language used in objectoriented programming ,has introduced the possibility of compiling output (called bytecode ) that can run on any computer system platform for which a Java virtual machine or bytecode interpreter is provided to convert the bytecode into instructions that can be executed by the actual hardware processor. Using this virtual machine, the bytecode can optionally be recompiled at the execution platform by a just-in-time compiler . Thus, a compiler differs from an interpreter, which analyzes and executes each line of source code in succession, without looking at the entire program. The advantage of interpreters is that they can execute a program immediately. Compilers require some time before an executable program emerges. However, programs produced by compilers run much faster than the same programs executed by an interpreter. An interpreter translates high-level instructions into an intermediate form, which it then executes. In contrast, a compiler translates high-level instructions directly into machine language. Compiled programs generally run faster than interpreted programs. The advantage of an interpreter, however, is that it does not need to go through the compilation stage during which machine instructions are

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

Windows

UNIXOther OSs like Yes Yes

AMPC Amsterdam Compiler Kit

Yes No

Yes

Yes

Clang

Yes

Yes

Yes

GCC C

Yes

Yes

LabWindows/CVI

Yes

Yes

Yes IBM mainfraime, AmigaOS, VAX/VMS, RTEMS Yes

lcc

Yes

Yes

Yes

Nwcc Open64 Pelles C Portable C Compiler

Yes Yes Yes

Yes Yes No

Yes Yes No

Yes

Yes

Yes

License IDE? type Proprietary Yes Open Source No (BSD) Open Source No (BSD) Open source

No

Proprietary Yes Proprietary (open-source Windows freeware) Open source No Open source No Freeware Yes Open source No (BSD)

Yes IBM mainframe, Proprietary AmigaOS, 68K, 88K, Unix No Open source No Proprietary

SAS/C

Yes

Yes

Tiny C Compiler CCS C Compiler ups debugger[1] (includes C interpreter) VBCC

Yes Yes

Yes Yes

No

Yes

Yes Solaris, SunOS

Open source

Yes

Yes

Yes

Yes

Open Source

No

C/C++ compilers Compiler Windows

UNIX-

Other

License type

Yes No Yes

IDE?

C++ Builder AMD x86 Open64 Compiler Suite Turbo C++ Explorer C++ Compiler Ch interpreter Code::Block[2]

Yes ?

like No ?

OSs No ?

Proprietary ?

Yes ?

Yes

No

No

Freeware

Yes

Yes Yes Yes

No Yes Yes

No

Freeware Freeware Open-Source

No Yes Yes

?

CINT

Yes

Borland C++ Turbo C++ for DOS Clang CodeWarrior Comeau C/C++ CoSy compiler development system Digital Mars Djgpp EDGE ARM C/C++ MinGW

Yes

Yes Yes Solaris, BeBox, MSYes X11/MIT license DOS, Convex, etc. No DOS Proprietary

No

No

Yes Yes Yes

Yes Yes Yes

Yes

Yes

Yes No

No No

Yes

Yes

Yes

GCC HP aC++ IAR C/C++ Compilers Intel C++ Compiler KAI C++ Compiler Microtec MULTI Open Watcom Open64

Yes

Proprietary

Yes

Yes Yes Yes

Open source ? Proprietary

No Yes

No

Proprietary

No

Proprietary Open source

Yes No

Yes

Proprietary

Yes

No

No

Open source

Yes

Yes

Yes

Open source

No

Yes

No

Proprietary

No Yes Apple Xcode for Mac OS X, Eclipse No

Yes

No

No

Proprietary

Yes

Yes

Yes

Yes

Proprietary

Yes

?

? Yes Yes Yes Yes

Yes Yes No Yes

DOS

Yes

DOS DOS

?

? Yes Yes Yes Yes

Proprietary Proprietary Open source Open source

?

? Yes Yes Yes No

No

Proprietary/Open source Proprietary

Yes

Yes

Proprietary

Yes

Proprietary

Yes

PathScale

No

Yes

No

PGI Workstation ProDev WorkShop RealView C/C++ Compiler (armcc)

Yes

Yes

No

No

Yes

Yes

SAS/C C++

No No Yes Yes

IBM mainframe Yes Yes Yes No No No No No

Yes

No

?

Sun Studio TenDRA VectorC Visual C++ Visual C++ Express VisualAge C++ XL C/C++ Wind River (Diab) Compiler

?

?

Yes No Yes

No

AIX OS/2 Yes Yes Yes

Yes

Proprietary

No

?

Proprietary Open source Proprietary Proprietary

Yes No No Yes

Freeware

Yes

Proprietary Proprietary

Yes No

Proprietary

Yes

Linker (computing) In computer science, a linker or link editor is a program that takes one or more objects generated by a compiler and combines them into a single executable program. Computer programs typically comprise several parts or modules; all these parts/modules need not be contained within a single object file, and in such case refer to each other by means of symbols. Typically, an object file can contain three kinds of symbols: • • •

defined symbols, which allow it to be called by other modules, undefined symbols, which call the other modules where these symbols are defined, and local symbols, used internally within the object file to facilitate relocation.

When a program comprises multiple object files, the linker combines these files into a unified executable program, resolving the symbols as it goes along. Linkers can take objects from a collection called a library. Some linkers do not include the whole library in the output; they only include its symbols that are referenced from other object files or libraries. Libraries exist for diverse purposes, and one or more system libraries are usually linked in by default.

The linker also takes care of arranging the objects in a program's address space. This may involve relocating code that assumes a specific base address to another base. Since a compiler seldom knows where an object will reside, it often assumes a fixed base location (for example, zero). Relocating machine code may involve re-targeting of absolute jumps, loads and stores. The executable output by the linker may need another relocation pass when it is finally loaded into memory (just before execution). This pass is usually omitted on hardware offering virtual memory — every program is put into its own address space, so there is no conflict even if all programs load at the same base address. This pass may also be omitted if the executable is a position independent executable. The GNU Compiler Collection (usually shortened to GCC) ,Originally named the GNU C Compiler, because it only handled the C programming language, GCC 1.0 was released in 1987, and the compiler was extended to compile C++ in December of that year TURBO C COMPILER Turbo C++ was a C++ compiler and integrated development environment (IDE) originally from Borland. Most recently it was distributed by Embarcadero Technologies, which acquired all of Borland's compiler tools Turbo C++ v1.01 and Turbo C v2.0 can be downloaded, free of charge, from Borland's Antique Software website C PROGRAMMING LANGUAGE HISTORY The development of Unix in the C language made it uniquely portable and improvable. The first version of Unix was written in the low-level PDP-7 assembler language. Soon after, a language called TMG was created for the PDP-7 by R. M. McClure. Using TMG to develop a FORTRAN compiler, Ken Thompson instead ended up developing a compiler for a new high-level language he called B, based on the earlier BCPL language developed by Martin Richard. When the PDP-11 computer arrived at Bell Labs, Dennis Ritchie built on B to create a new language called C which inherited Thompson's taste for concise syntax, and had a powerful mix of high-level functionality and the detailed features required to program an operating system. Most of the components of Unix were eventually rewritten in C, culminating with the kernel itself in 1973. Because of its convenience and power, C went on to become the most popular programming language in the world over the next quarter century.

This development of Unix in C had two important consequences: •

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



First, write a C-to-assembly language compiler for the new machine. Then use the new compiler to automatically translate the Unix C language source code into the new machine's assembly language. Finally, write only a small amount of new code where absolutely required by hardware differences with the new machine.

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

What is the advantages of c language? •

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



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



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



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

DISADVANTAGES OF C ARE: 1. There is no runtime checking. 2.There is no strict type checking(for ex:we can pass an integer value for the floating data type). 3. As the program extends it is very difficult to fix the bugs. FEATURES OF C C has facilities for structured programming and allows lexical variable scope and recursion, while a static type system prevents many unintended operations. In C, all executable code is contained within functions. Function parameters are always passed by value. Pass-by-reference is simulated in C by explicitly passing pointer values. C also exhibits the following more specific characteristics: • • • • • • • •

variables may be hidden in nested blocks partially weak typing; for instance, characters can be used as integers low-level access to computer memory by converting machine addresses to typed pointers function and data pointers supporting ad hoc run-time polymorphism array indexing as a secondary notion, defined in terms of pointer arithmetic a preprocessor for macro definition, source code file inclusion, and conditional compilation complex functionality such as I/O, string manipulation, and mathematical functions consistently delegated to library routines A relatively small set of reserved keywords o A lexical structure that resembles B more than ALGOL

Absent features The relatively low-level nature of the language affords the programmer close control over what the computer does, while allowing special tailoring and aggressive optimization for a particular platform. This allows the code to run efficiently on very limited hardware, such as embedded systems. C does not have some features that are available in some other programming languages: • •



No nested function definitions No direct assignment of arrays or strings (copying can be done via standard functions; assignment of objects having struct or union type is supported) No automatic garbage collection

• • • • • •



• • • • • •

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:

/* Documentation section */ /* Link section */ /* Definition section */ /* Global declaretion section */ /* Function section */ (return type) (function name) (arguments...) void main() { Declaration part Executable part (statements) } /* Sub-program section */ (return type) (function name 1) (arguments...) (return type) (function name 2) (arguments...) . . . (return type) (function name n) (arguments...) ________________________________________________________________ The following program is written in the C programming language. Open a text file hello.c using vi editor and put the following lines inside that file. #include int main() { /* My first program */ printf("Hello, World! \n"); return 0;// return interger value zero } NOTE: In computer programming, a return statement causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called — known as its return address. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function. If a function does not have a return type (i.e., its return type is void), the return statement can be used without a value, in which case the program just breaks out of the current function and returns to the calling one.

exit(0) This causes the program to exit with a successful termination. exit(1) This causes the program to exit with a system-specific meaning. On many systems, exit(1) signals some sort of failure, however there is no guarantee. As I recall, the C standard only recognizes three standard exit values: EXIT_SUCCESS -- successful termination EXIT_FAILURE -- unsuccessful termination 0 -- same as EXIT_SUCCESS _____________________________________________________________  Preprocessor Commands: These commands tells the compiler to do preprocessing before doing actual compilation. Like #include is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. You will learn more about C Preprocessors in C Preprocessors session.

 Functions: are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. This function is prefixed with keyword int which means this function returns an integer value when it exits. This integer value is retured using return statement. The C Programming language provides a set of built-in functions. In the above example printf() is a C built-in function which is used to print anything on the screen.  Variables: are used to hold numbers, strings and complex data for manipulation..

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

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

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

C is a case sensitive programming language. It means in C printf and Printf will have different meanings. C has a free-form line structure. End of each C statement must be marked with a semicolon.



Multiple statements can be one the same line.



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



Statements can continue over multiple lines.

C Program Compilation To compile a C program you would have to Compiler name and program files name. Assuming your compiler's name is cc and program file name is hello.c, give following command at Unix prompt. $cc hello.c This will produce a binary file called a.out and an object file hello.o in your current directory. Here a.out is your first program which you will run at Unix prompt like any other system program. If you don't like the name a.out then you can produce a binary file with your own name by using -o option while compiling C program. See an example below $cc -o hello hello.c Now you will get a binary with name hello. Execute this program at Unix prompt but before executing / running this program make sure that it has execute permission set. If you don't know what is execute permission then just follow these two steps

$chmod 755 hello $./hello This will produce following result Hello, World The skeleton of a simple C program is given below : main() { statement 1 ; statement 2 ; } function1() { variable declarations; statement 1; statement 2; } ·

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

·

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

·

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

·

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

·

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

WRITING YOUR FIRST C PROGRAM The following is a simple C program that prints a message ‘Hello, world’ on the screen. /* Author: JNTU Date: 13/10/2009 Purpose: This program prints a message */ 1.#include 2.main() 3.{ 4. printf(“Hello, world”); 5.} Type this program in any text editor and then compile and run it using a Ccompiler. 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. 2. 3. 4. 5. 6. 7.

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

If you are using a Linux machine, you have to follow the steps mentioned below: 1. 2. 3. 4. 5. 6. 7. 8.

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

Note: C is a case-sensitive language. It makes a distinction between letters written in lower and upper case. For example, ‘A’ and ‘a’ would be taken to mean different things. Also, remember that all C language keywords should be typed in lower case. UNDERSTANDING THE PROGRAM In the program you saw above, the information enclosed between ‘/* */’ is called a ‘comment’ and may appear anywhere in a C program. Comments are optional and are used to increase the readability of the program. The ‘#include’ in the first line of the program is called a preprocessor directive. A preprocessor is a program that processes the C program before the compiler. All the lines in the C program beginning with a hash (#) sign are processed by the preprocessor. ‘stdio.h’ refers to a file supplied along with the C compiler. It contains ordinary C statements. These statements give information about many other functions that perform input-output roles. Thus, the statement ‘#include’ 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 builtin 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: 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 by

int main(void) { printf(‘‘Hello world!\n’’); } The int stands for the \return type", which says that the main function returns an integer if you tell it to do so. We will get into more detail with functions and return types, but you can return a number to the command line with the return function in C, as in int main(void) { printf(‘‘Hello world!\n’’); return 2; } When you compile and run your program, it will return a 2 to the command line, that you can access with the $? character, which stores the value returned by the last command executed, as in $ ./a.out Hello world! $ echo $? 2 Just as in shell scripts, you can specify exit codes in C as well, which perform the same function as the return function in the previous example: int main(void) { printf(‘‘Hello world!\n’’); exit(2); } Compiling and running this example yields the same result as the previous example. The void statement in main(void) tells the main function that there are no arguments being supplied to it at the command line. Note that all statements in C programs end with the semicolon ; except for the prepro-cessor directives that begin with #. How C program works The jump to the object oriented C++ language becomes much easier. C++ is an extension of C, and it is nearly impossible to learn C++ without learning C first. What is C?

C is what is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an executable that the computer can run (execute). The C program is the human-readable form, while the executable that comes out of the compiler is the machine-readable and executable form. What this means is that to write and run a C program, you must have access to a C compiler. If you are using a UNIX machine (for example, if you are writing CGI scripts in C on your host's UNIX computer, or if you are a student working on a lab's UNIX machine), the C compiler is available for free. It is called either "cc" or "gcc" and is available on the command line. If you are a student, then the school will likely provide you with a compiler -- find out what the school is using and learn about it. If you are working at home on a Windows machine, you are going to need to download a free C compiler or purchase a commercial compiler. On a UNIX machine, type gcc samp.c -o samp (if gcc does not work, try cc). This line invokes the C compiler called gcc, asks it to compile samp.c and asks it

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

• •

On a DOS or Windows machine using DJGPP, at an MS-DOS prompt type gcc samp.c -o samp.exe. This line invokes the C compiler called gcc, asks it to compile samp.c and asks it to place the executable file it creates under the name samp.exe. To run the program, type samp. If you are working with some other compiler or development system, read and follow the directions for the compiler you are using to compile and execute the program. If you mistype the program, it either will not compile or it will not run. If the program does not compile or does not run correctly, edit it again and see where you went wrong in your typing. Fix the error and try again.



• • • •

• • •

• •



This C program starts with #include . This line includes the "standard I/O library" into your program. The standard I/O library lets you read input from the keyboard (called "standard in"), write output to the screen (called "standard out"), process text files stored on the disk, and so on. It is an extremely useful library. C has a large number of standard libraries like stdio, including string, time and math libraries. A library is simply a package of code that someone else has written to make your life easier (we'll discuss libraries a bit later). The line int main() declares the main function. Every C program must have a function named main somewhere in the code. We will learn more about functions shortly. At run time, program execution starts at the first line of the main function. In C, the { and } symbols mark the beginning and end of a block of code. In this case, the block of code making up the main function contains two lines. The printf statement in C allows you to send output to standard out (for us, the screen). The portion in quotes is called the format string and describes how the data is to be formatted when printed. The format string can contain string literals such as "This is output from my first program!," symbols for carriage returns (\n), and operators as placeholders for variables (see below). If you are using UNIX, you can type man 3 printf to get complete documentation for the printf function. If not, see the documentation included with your compiler for details about the printf function. The return 0; line causes the function to return an error code of 0 (no error) to the shell that started execution.

 Header file In computing, header files are a feature of some programming languages (most famously C and C++) that allows programmers to separate certain elements of a program's source code into reusable files. Header files commonly contain forward declarations of classes, subroutines, variables, and other identifiers. Programmers who wish to declare standardized identifiers in more than one source file can place such identifiers in a single header file, which other code can then include whenever the header contents are required. The C standard library traditionally declare their standard functions in header files. Newer compiled languages (such as Java, C#) do not use forward declarations; identifiers are recognized automatically from source files and read directly from dynamic library symbols. This means header files are not needed. In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, or a function) for which the programmer has not yet given a complete definition. but at some point the programmer would still have to provide definitions for the declared entities. struct person; int elements[]; void print(int); After processing these declarations, the compiler would allow the programmer to refer to the entities person, elements and print in the rest of the program struct person { const char *name; char sex; int age; }; int elements[10]; void print(int x) { printf("%d\n", x); }

the following are some of the header files in c: #include #include #include #include #include #include #include #include #include #include #include #include #include there are about 32 header files in c A header file is used to define constants, variables, macro's and functions that may be common to several applications. When a system consists of multiple applications that all access the same data it becomes essential that each application uses identical definitions and it is safer for all of those applications to use the same methods to read that data. updating data should only be performed by a single function, from a single application, but reading data can be safely performed by using the common defintions found in header files. A header file is a file containing C declarations and macro definitions to be shared between several source files. You request the use of a header file in your program by including it, with the C preprocessing directive `#include'. Header files serve two purposes. •



System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries. Your own header files contain declarations for interfaces between the source files of your program. Each time you have a group of related declarations and macro definitions all or most of which are needed in several different source files, it is a good idea to create a header file for them.

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

The header file eliminates the labor of finding and changing all the copies as well as the risk that a failure to find one copy will result in inconsistencies within a program. In C, the usual convention is to give header files names that end with .h. It is most portable to use only letters, digits, dashes, and underscores in header file names, and at most one dot. Both user and system header files are included using the preprocessing directive `#include'. It has two variants: #include 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 . 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 specifies inclusion of a system header file named x/*y. C library headers Name



Description

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

A set of functions for manipulating complex numbers.



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).



For testing error codes reported by library functions.



For controlling floating-point environment.



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).

For precise conversion between integer types.

For programming in ISO 646 variant character sets.



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



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



For computing common mathematical functions.



Declares the macros setjmp and longjmp, which are used for nonlocal exits.



For controlling various exceptional conditions.



For accessing a varying number of arguments passed to functions.

For a boolean data type.



For defining various integer types.



For defining several useful types and macros.



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



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



For manipulating several kinds of strings.

For type-generic mathematical functions.

For converting between various time and date formats.



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

For classifying wide characters.

 C standard library The C standard library consists of a set of sections of the ISO C standard which describe a collection of header files and library routines used to implement common operations, such as input/output and string handling, in the C programming language. The C standard library is an interface standard described by a document; it is not an actual library of software routines available for linkage to C programs. No such implementation is properly called C standard library.

The term C runtime library is used on some platforms to refer to a set of base libraries, which may be distributed in dynamically linkable form with an operating system (with or without header files), or distributed with a C compiler. Another term sometimes used is libc. Not just any library is called the run-time library; run time in this context means the run-time support package associated with a compiler which is understood to make a language complete. The run-time support provides not only the C standard library functions, but possibly other material needed to create an environment for the C program, such as initialization prior to the invocation of the main function, or subroutines to provide arithmetic operations missing from the CPU that are needed by code generated by the C compiler. WHAT IS A GLOBAL DECLARATION? A global declaration of a function or variable is a declaration that is at the global scope of the program, not inside another function. This means that the name will be visible within all functions in the program. THE MAIN FUNCTION AND PROGRAM EXECUTION Every C program has a primary (main) function that must be named main. If your code adheres to the Unicode programming model, you can use the widecharacter version of main, wmain. The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program. A program usually stops executing at the end of main, although it can terminate at other points in the program for a variety of reasons. At times, perhaps when a certain error is detected, you may want to force the termination of a program. To do so, use the exit function. MAIN FUNCTION IN C IS A USER-DEFINED FUNCTION. No doubt it is a rule that without main function C program can not be compiled means that Main function is just to inform compiler about starting of program which is pre-defined in C. DON'T BE CONFUSED BETWEEN THE PRE-DEFINED STATEMENT AND PRE-DEFINED FUNCTION. PRE-DEFINED STATEMENT IS PROGRAM STARTS WITH MAIN FUNCTION AND PRE-DEFINED FUNCTIONS ARE THE FUNCTIONS WHICH ARE TOTALLY DEFINED IN LIBRARY/HEADER FILE. Functions within the source program perform one or more specific tasks. The main function can call these functions to perform their respective tasks. When main calls another function, it passes execution control to the function, so that execution begins at the first statement in the function. A function returns control

to main when a return statement is executed or when the end of the function is reached. You can declare any function, including main, to have parameters. The term "parameter" or "formal parameter" refers to the identifier that receives a value passed to a function. When one function calls another, the called function receives values for its parameters from the calling function. These values are called "arguments." You can declare formal parameters to main so that it can receive arguments from the command line using this format When you want to pass information to the main function, the parameters are traditionally named argc and argv, although the C compiler does not require these names. The types for argc and argv are defined by the C language. Traditionally, if a third parameter is passed to main, that parameter is named envp. ******In C, main() cannot return anything other than an int.Something like void main() is illegal. There are only three valid return values from main() 0, EXIT_SUCCESS, and EXIT_FAILURE The C preprocessor (cpp) is the preprocessor for the C programming language. In many C implementations, it is a separate program invoked by the compiler as the first part of translation. The preprocessor handles directives for source file inclusion (#include), macro definitions (#define), and conditional inclusion (#if). WHAT ARE MACROS? Macros, which are special lines/fragments of code, differ from any other code written in the source files in the aspect that it's not passed to the compiler (either for the purpose of encoding into machine instructions, or some intermediate form instructions). Instead, macros perform textual manipulations on the source code before passing it to the compiler, where this process preliminary to compiling the source files is called "preprocessing", and the software component responsible of doing it is called the "preprocessor". Henceforth, macros are usually defined as "preprocessor directives", where a segment of code is replaced by the results of the macro processing before passing the source code to the compiler. A very valuable technique to gain a thorough understanding of the operation of macros in any environment is to learn how to obtained the preprocessed source code, and see how the macro directives are expanded. In C and C++, a Macro is a piece of text that is expanded by the preprocessor part of the compiler. This is used in to expand text before compiling. #define VALUE 10

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 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 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.

You can nest single line comments within C-style comments. For example, the following program will not output anything: #include int main(void) { /* printf("This line will not print.\n"); // This is a single line comment // This is another single line comment printf("This line will also not print.\n"); */ return 0; \\ } RULES IN C PROGRAMMING LANGUAGE Here are some of the syntax rules in C Programming that must be familiarize: a. Put semicolon at the end of variable declaration. b. Commas should be used to separate variables. c. Variables should be declared first before it can be used. d. An identifier must not begin with a digit. e. An identifier must consist only of letters, digits, or underscores. f. An identifier defined in a C standard library must not be redefined. g. C reserved words cannot be used as an identifier. h. In using the scanf function the order of the placeholders must correspond to the order of the variables in the input list. C PROGRAM COMPILATION STEPS? There are 6 steps 1. 2. 3. 4.

Pre-processor - which replaces macros Code will be separated from comments syntax error will be given - types of parsing 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. Letters 2. Digits 3. Special Characters 4. White Spaces White Spaces are ignored by the compiler until they are a part of string constant. White Space may be used to separate words, but are strictly prohibited while using between characters of keywords or identifiers. C Character-Set Table Letters

Digits

Upper Case A to Z

0 to 9

Lower Case a to z . A character denotes any alphabet ,digit or symbols to represent information.The following are the valid alphabets, numbers and special symbols permitted in C Numerals: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Alphabets: a, b, ….z A, B, ……...Z Arithmetic Operations: +, -, *, /, %(Mod) Special Characters:

(

)

{

}

[

]

<

>

=

!

$

?

.

,

:

;





&

|

^

~

`

#

\

blank

-

_

/

*

%

@

CONSTANTS, VARIABLES AND KEYWORDS A ‘constant’ is an entity that does not change, but a ‘variable’ as the name suggests may change. We do a number of calculations in a computer and the computed values are stored in some memory spaces. Inorder to retrieve and re-use those values from the computer’s memory locations they are given names. Since the value stored in each location may change, the names given to these locations are called as ‘variable names’. Constants: There are mainly three types of constants namely: integer, real and character constants. Integer Constants: The integer constants • • • •

Whole Numbers Eg. 25, 35, -25, -46 Computer allocates only 2 bytes in memory. 16th bit is sign bit. (if 0 then +ve value, if 1 then –ve value)

(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:

• •

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 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. Keyword 2. Identifier 3. Constants/Literals 4. Variable 5. Operator 6. Punctuator

TYPES OF C VARIABLES Variable names are names given to locations in the memory. These locations can contain integer, real or character constants. An integer variable can hold only an integer constant, a real variable can hold only a real constant and a character variable can hold only a character constant. Rules for Constructing Variable Names A variable name is any combination of 1 to 31 alphabets, digits or underscores. Some compilers allow variable names whose length could be up to 247 characters. • • •

The first character in the variable name must be an alphabet No commas or blanks are allowed within a variable name. No special symbol other than an underscore (as in net_sal) can be used in a variable name. Ex.: si_int e_hra pod_e_81 C compiler makes it compulsory for the user to declare the type of any variable name that he wishes to use in a program. This type declaration is

done at the beginning of the program. Following are the examples of type declaration statements: Ex.: int si, e_hra ; float bas_sal ; char code ; Since, the maximum allowable length of a variable name is 31 characters, an enormous number of variable names can be constructed using the above-mentioned rules. It is a good practice to exploit this enormous choice in naming variables by using meaningful variable names. C Keywords C makes use of only 32 keywords or reserved words which combine with the formal syntax to the form the C programming language. Note that all keywords in C are written in lower case. A keyword may not be used as a variable name. auto break case char const continue default do

double

int

struct

else

long

switch

enum

register

typedef

extern

return

union

float

short

unsigned

for

signed

void

goto

sizeof

volatile

if

static

while

As a programmer, you will frequently want your program to "remember" a value. For example, if your program requests a value from the user, or if it calculates a value, you will want to remember it somewhere so you can use it later. The way your program remembers things is by using variables. For example: int b; This line says, "I want to create a space called b that is able to hold one integer value." A variable has a name (in this case, b) and a type (in this case, int, an integer). You can store a value in b by saying something like: b = 5; You can use the value in b by saying something like: printf("%d", b); In C, there are several standard types for variables: int - integer (whole number) values float - floating point values char - single character values (such as "m" or "Z")

• • •

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

LOCAL VARIABLES GLOBAL VARIABLES

Local Variables • •



Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. When a local variable is defined - it is not initalised by the system, you must initalise it yourself. When execution of the block starts the variable is available, and when the block ends the variable 'dies'.

Check following example's output main()

{ int i=4; int j=10; i++; if (j > 0) { /* i defined in 'main' can be seen */ printf("i is %d\n",i); } if (j > 0) { /* 'i' is defined and so local to this block */ int i=100; printf("i is %d\n",i); }/* 'i' (value 100) dies here */ printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/ } This will generate following output i is 5 i is 100 i is 5 Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1; You will see -- operator also which is called decremental operator and it decreases the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1; Global Variables Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it. Global variables are initalised automatically by the system when you define them! Data Type int char float pointer

Initialser 0 '\0' 0 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 : 1. 2.

Primary data types 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, -2 15 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 ; like int num1; 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 ; like float 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 –128 to 127. Syntax: char ; like char 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 ; like typedef 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”.

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. 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.



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: 1 short a=2000; 2 int b; 3 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: 1 short a=2000; 2 int b; 3 b = (int) a; // c-like cast notation 4 b = int (a); // functional notation

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; } 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. 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 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 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"); } 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) }; OR enum 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 Positive = FALSE; for ( Day = Monday; Day

Checks if the value of left operand is greater than the value of right (A > B) is not true. operand, if yes then condition becomes true.

<

Checks if the value of left operand (A < B) is true.

(A == B) is not true.

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

>=

Checks if the value of left operand is greater than or equal to the (A >= B) is not true. value of right operand, if yes then condition becomes true.

> 2 will give 15 which is 0000 by the number of bits specified by 1111 the right operand.

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; unsigned int b = 13; unsigned int c = 0;

/* 60 = 0011 1100 */ /* 13 = 0000 1101 */

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; /* 15 = 0000 1111 */ printf("Line 6 - Value of c is %d\n", c ); } This will produce following result

Line 1 - Value of c is 12

Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15 Assignment Operators: There are following assignment operators supported by C language: Operator

Description

Example

=

Simple assignment operator, C = A + B will assign value of A + B Assigns values from right side into C operands to left side operand

+=

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

-=

Subtract AND assignment operator, It subtracts right operand from the left operand C -= A is equivalent to C = C - A and assign the result to left operand

*=

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

/=

Divide AND assignment operator, It divides left operand with the right C /= A is equivalent to C = C / A operand and assign the result to left operand

%=

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

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

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

> 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 ); 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 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 = 21 Line 2 - += Operator Example, Value of c = 42 Line 3 - -= Operator Example, Value of c = 21 Line 4 - *= Operator Example, Value of c = 441 Line 5 - /= Operator Example, Value of c = 21 Line 6 - %= Operator Example, Value of c = 11 Line 7 - = Operator Example, Value of c = 11 Line 9 - &= Operator Example, Value of c = 2 Line 10 - ^= Operator Example, Value of c = 0 Line 11 - |= Operator Example, Value of c = 2

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 Lvalues 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 Expression

If 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) ); /* 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 = 4 Line 2 - Size of variable b = 2 Line 3 - Size of variable c= 8 Line 4 - Size of variable d= 10 Line 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; int* ptr;

/* variable declaration /* int pointer

/* 'ptr' now contains the address of 'i' printf(" i is %d.\n", i); printf("*ptr is %d.\n", *ptr);

*/ */

ptr = &i;

*/

} 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; 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 30 Value of b is 20

Note : 1's and 2's complement Generally negative numbers can be represented using either 1's complement or 2's complement representation. 1's complement ---reverse all the bits 2'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 . 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 name Member selection via pointer Postfix increment/decrement (see Note 2)

left-to-right

++ -+ ! ~ (type) * & sizeof

Prefix increment/decrement Unary plus/minus Logical negation/bitwise complement Cast (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 to Relational greater than/greater than or equal to

left-to-right

== !=

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

= += -= *= /= %= &= ^= |=

Assignment Addition/subtraction assignment Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment

right-to-left

=

Bitwise shift left/right assignment

,

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: expression3 If 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; Increment operator ++ Prefix: the value is incremented/decremented first and then applied. Postfix: the value is applied and the value is incremented/decremented. #include 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 #include 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 Generally negative numbers can be represented using either 1's complement or 2's complement representation. 1's complement ---reverse all the bits 2's complement ---reverse all the bits + 1 i.e 1's complement of 2 ( 0000 0010 ) is -2 ( 1111 1101 ) Examples Original number: 0111011 1's complement: 1000100 2's complement: 1000101 Original number: 1111111 1's complement: 0000000 2's complement: 0000001

Original number: 1111000 1's complement: 0000111 2'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 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. 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.  getchar()  getche()  getch() getchar() is used to get or read the input (i.e a single character) at run time. Library: 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: 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. 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: 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. # 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 Prints the address of the variable in the memory #include 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 printf(“\n10==10

:%5d”,10==10);// prints 1 for true :%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 && 55 || 8=65 && xmyname -- is wrong and so is: struct_ptr.myname

4: 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
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF