C PROGRAMS PDF

adminComment(0)

The first chapter deals with the fundamental concepts of C language. The second chapter focuses on introduction C programming. The third chapter provides. C is a general-purpose, procedural, imperative computer programming language developed in by Dennis M. Ritchie at the Bell Telephone Laboratories to. C programming examples with basic as well as advanced C program examples with output for practice and improving C coding skills.


C Programs Pdf

Author:WESLEY WAMPLER
Language:English, German, Hindi
Country:Thailand
Genre:Children & Youth
Pages:116
Published (Last):04.01.2016
ISBN:838-3-68667-765-7
ePub File Size:26.57 MB
PDF File Size:15.74 MB
Distribution:Free* [*Registration needed]
Downloads:36118
Uploaded by: GABRIELE

This page contains examples on basic concepts of C programming like: loops, functions, pointers, structures etc. C is a programming language developed at AT & T's Bell Laboratories of USA programs are exclusively written in C. C seems so popular is because it is. the first example of a C program. It has been slightly modified. * to illustrate some other points about the language. * By the way, this is an example of a header.

The complete implementation is left to the reader as an exercise. Use that data type to find out factorial for any number. You may wonder whether a C program could output the same or not. It was by Dan Hoey. When you run this program. As it is a tough job. Look at the following code: One of the important uses of pointers is the dynamic memory allocation. DOS or Windows. So we must avoid memory overwrite and we should use only the allocated memory.

So it is more dangerous. Too much of memory leak would crash TC. So array overflow may result in memory overwrite! So when we copy var2 to var1 using strcpy. That is. So the value that was returned by malloc is definitely lost.

The remedy for memory leak is to declare pointer constant. Now we have memory leak even if we call free function. All of these techniques can also be extended to three or more dimensions.

I personally prefer this implementation. There you can find the rules and important dates. As far as I know no Indian has yet received this prize. In other words. Permission for personal.

This is one of the simple tricks used in code obfuscation. Code Obfuscation is very interesting to most of the C programmers. Code Obfuscation refers to confusing others with your code. Throughout the world most of the C programmers participate in this contest. Code Obfuscation is the technical term for crypting your code and preventing others from reading the code Just opposite to Readability.

All Rights Reserved. The resolution of the map is five degrees horizontally. It prints the world map! World Map. New Delhi marked with " obtained by executing whereami 29 77 Southern latitudes and western longitudes are entered as negative numbers. Latitudes near the poles and Antarctica are not shown. The map is a Mercator projection with equal spacing of the latitudes. The position counting down to zero changes the putchar from printing '!

The longitude is divided by five and added.

The signs are opposite because latitude is decreasing and longitude is increasing as you go from upper left to lower right. The map data is a string. Since the resolution is coarse. Logic The map is printed as one long string of ' ' and '!

Here are some cities you might like to try: If your display does not work this way. If you run it with fewer than 2 arguments. The map is reasonably accurate. It's just for show. When I did fall asleep. Since it is stored in ROM. It also has drivers and other software that manages the peripheral devices.

This DOS is same for all the systems. It is a firmware Firmware is a program or data stored in ROM. It contains many low level routines. So I would slightly touch the hardware and DOS internals in this chapter. For system programming you must know the relationship between the two. It is a single-user operating system.

Thus using DOS an interface is made between the user and the computer. It is responsible for basic hardware operations such as interactions with disk drives and keyboards. DOS is designed to provide an easy way to use disks for storage.

The basic operations performed by DOS are regulate space allocation. These are not altered by software. It is very efficient in controlling. When the BIOS finds the boot sector. It makes a call to the disk for loading the operating system into the memory. When the computer is switched ON the process of bootstrapping takes place. At this point. Then it jumps to 0: BIOS data area 40h: It initializes all its data and then looks for a valid boot sector. After this process. After loading the operating system.

First it looks at the Floppy disk A: The conventional memory which is also FFFFF Upper memory called base memory is reserved for the use by the k area Reserved system and the upper memory area is reserved for the memory A use by the graphics boards. In the system there is 1MB of addressable memory area.

The first K above the conventional memory area is reserved for the use by the video adapter and it is also called video RAM. In the video RAM area the information related to text and graphics display on screen is stored. The total memory area in the system is divided into different segments. Virtual memory area is not present in DOS. The real addressing has bits and Motherboard ROM BIOS so to represent this bit physical address we are using bit segment address and offset address.

The size of the extended memory changes from system to system. These segments use only bit address for storing and retrieving data in 1MB each segment.

The diagram with the conventional. Now DOS is given a graphical user interface and limited multitasking capability by combining with Windows. Compiler is very often treated as language converter. The most important components Compiler. Linker is the one that links object. Compiler is the one. TC that is found on the TC directory to get back default configuration.

Assembler is the one. IDE has got so many components. Editor is the one in which we create. Why I prefer Version 3. Using this you can create assembly files. It is an integrated compiler.

These useful utilities are rarely known in India. Please try to use them for better programming! I will just introduce the utilities. We will see this later! It can handle only x instructions. It is used to assemble the inline assembly to the C file. For more explanations about those utilities. In the beginning of the program you have to add the following line to invoke TASM. Real programmers very often use this useful utility.

To call x instruction. What IDE does is. Otherwise it means the program has been terminated with error. But in my opinion. But using the third argument env is not a standard way. Under 3. Turbo C sends all the three arguments argc. Under versions of DOS before 3. Turbo C supports three arguments: Using a sample program. If it returns '0' means. The reason is. In order to embed blanks we have put it in double quotes. For standard programming use environ.

X versions of DOS. Turbo C accepts both int and void main and Turbo C programmers use both int and void main in their programs. I have found that void main returns 20 even after successful completion of program which means it returns wrong status to the operating system!

Thus we have found that int main is the appropriate usage. In other platforms. You may have to try different voidmain. We will see those things later! All these are done with controls like: It shows the error value or status. Actually header files are those that contain defines and function prototype declarations. The following demonstration explains why writing functions in header and including it in the main program is wrong.

And so it prints the message "Hello! When we include the Badhead. Now you would ask me where to write the function PrintHello1 and PrintHello2. Large and Huge. We can use it as a flag to check whether the file is already included or not. In such a case our code must be compiled in that memory model only We have 6 different memory models: So programmers use conditional compilation method. That is to use pragma and to force the compiler to compile in specified memory model.

Now click [Done] and press F9 to compile the project file. Project file allows you to organize these files.

When you create project file. Now you will get chklib. Then Press F9 to compiler. Now you will get a project window. Add the respective OBJ. Turbo C got the following keywords: Only a narrow-minded people do that!

The applications of these ideas are dealt in forthcoming chapters. You can put all the interrelated functions say mouse functions in a library file and then you can link the library file whenever necessary.

You will get the EXE file.. Creating library file is a good way to organize your program. So it is advisable to create library file for each memory model. LIB and C files. Press [Insert] to add file. And it won't work on all systems. But when you run the corresponding EXE file in command line it will work properly. But this is not much preferred by the professional programmers.

The reason is the delay function is implemented with clock speed. Its also considered 'good form' to call the old int. If everyone does. If you skip the little chunk of ASM code. Alexander J. The clear description can be found on next chapter. You don't have to call the old timer. In such a case we must take effort explicitly to link floating formats. But in certain cases. Normally it would happen if you use strcpy or memcpy with a pointer as its first argument.

If so. Your program may look as if it runs correctly. The actual reason for the cause is you might have written. Whenever TC finds exit or returns from main. If the above function gets linked. Enter a: But a good human Assembly programmer can write much more tight and efficient code.

That is called as Inline Assembly. In such a case you must use TASM and for that you should use pragma inline. If you use pragma inline.

If you use x instructions in inline assembly. BASM cannot assemble those codes. If you are such an efficient-superb Assembly programmer. MOV DX. A good optimizing C compiler will convert C file to a better assembly code. You don't need TASM. Anything that is present in AX register will be returned. INT 21H. We can see more about interrupt programming later.

DX lower word gets returned as long. But here you will get a warning. ADD AX. Add 5. MOV BX. If you are allergic to warning. In C language the parameters are pushed in the reverse order i. You will get error when you don't have TASM assembler. When you use such Pascal calling conventions. Another solution is to create a separate and a pure i. In case if you use x instructions. In high level language whenever a function is being called. The order in which the parameters are pushed varies from language to language.

Also C passes the parameters by value rather than by reference. Then you might be asking me how is it possible to call such a routine from C.

C Programming Examples

As we discussed. MODEL small. C and Assembly. Turbo C treats Pascal type identifiers those modules with pascal keyword differently. You have to note that we are mating two different language i. CODE Turbo C automatically joins an underscore in front of the identifier before saving that identifier in that object module. File name: That is because of the C's naming convention as discussed in the previous section.

Turbo C automatically joins an underscore in front of the function name too. Please note that in assembly the comment line starts with semicolon. Now you will get chkasm1. We can assemble the Hello2. Case sensitive is important. Next we have to write a C program that uses PrintHello function. When you assemble. Here we find that Hello2. NASM etc. OBJ which contains PrintfHello procedure. The next step is to assemble the Hello2.

For the details regarding the switches. OBJ Now the newlib. Addnum 5. For that you can use TLIB. If you feel that newlib. We can add any number of modules with the library file.

For example to create a library file newlib. The processor introduced after The computing world came across so many processors. Each of the processors has its own merits and demerits. It is a chip that is responsible for processing instructions. Windows 3. The following table shows few of the known processors and its characteristics. They also resisted bit operating system and bit applications. Therefore it is not preferred for commercial applications. So when Microsoft tried to introduce Windows When we check for its unique characteristics.

Processor type is also referred as CPU Id. Any how Gilles Kohl came out with a tough C code that can determine processor type or This logic is used to find out the processor type. It also supports multitasking. Had no protection for memory overwriting. For better results we must use Assembly. Compile with Tasm. This routine can be called from C i. Hardware detection module. C callable. A to Z of C 67 return!! We can call it as a limitation of C language! Using this routine.

C callable as: Clear AX. Alignment check bit which can't be changed on a Recover flags. Try to set bits Push it on the stack.

Zero the flags. Try to zero bits PC Processor detection routine. Save flags xor ax. OK it was probably a A to Z of C 69 pop eax mov ebx. PC Numeric coprocessor detection routine. Returns 1 if coprocessor found. It is by Edward J. CPUID equ "dw 0a20fh". All these codes use the same logic i. MODEL memodel. This module contains a C callable routine which returns a bit integer in AX which indicates the type of CPU on which the program is running.

Add model support via command. The higher eight bits AH contain a collection of bit flags which are defined below. The lower eight bits AL contain a number corresponding to the family number e. Here I provide another Assembly code to find out processor type. Cyrix processors do not alter the AF Aux carry bit when. I think. The or under test. All later CPUs do it correctly.

The Cyrix test. Intel CPUs and. The test. Bits the top four of the flags register are all set to. Intel's CPUs do not -.

The test On the NOT 3. The SX test. On the SX. On the DX this bit can be.

The AC Alignment Check bit was introduced on the If the flag can't be toggled. This one isn't completely reliable -. CPU's don't make it through this one even though they have all. I've heard that the NexGen. We only check the first letter. We reset the NPU using the non-wait versions of the instruction. The NPU test. Then we check for zero.

Since the can be paired with either a or The Write a program that can find the current mode of processor i. Paintbrush must know the file format of BMP file and so on.

If we know the file format of a particular file. But in the following chapters and in CD you can see some real examples.

The software that creates a file of specific type should be aware of its file format. But certain narrow-minded vendors may keep the file format as secret. Usually all files contain what is called as file header and it is nothing but the first few bytes of a file. Each file type uses specific size for the file header. Most of the software vendors document the file format whenever they introduce a new file type.

The file type is identified by what is known as signature. We must understand that each and every file type uses its own file formats. Thus each file got its own architecture or File Format.

Key Highlights of C Programming Tutorial PDF are

After the File Header. For example if we know the file format of BMP file. Each file format has its own advantages and drawbacks. I just introduce the concept.

If you know the file format you can do miracles. The file Header contains many useful information such as its file types i. EXE file of first relocation item overlay number 0 for root program relocation table and the program load module follow the header relocation entries are 32 bit values representing the offset into the load module needing patched once the relocatable item is found.

Link file. EXE signature Mark Zbikowski? IP contains number of characters in command tail.

Write a BMP file creator i. For the good quality. Paintbrush in high resolution VESA mode. You should know the file format of Turbo C's help file.

The software has to use both mouse and graphics stylus as input devices. Write software to split and join files.

Write your own image creation utility that uses MP3 compression algorithm and thus develop your own file format for that. Write your own compression utility and thus develop your own file format for that. Remove relocation found in EXE files. Then you can try the following projects: For example if you create a mouse library. Crack the file types for which file format is not yet available and try to document the file format.

Of course it is illegal! But it is not so. Many people think that the interrupt instruction 'INT' is one of the "basic" instructions in assembly language..

The 'INT' instruction just calls or invokes a specific routine i. It is actually an extension of BIOS. Usually most of the BIOS functions are compatible. The prototype of int 5h hence looks like: But professional programmers use the term argument. Different machines may use different hardware. By the way you should know that BIOS programs are not much compatible. Besides interacting with hardware. The value passed through the register AH is referred as function value.

Most Beginner Friendly Tutorials for Programmers

If a routine can be called again before it is finished. In special cases. There is a drawback with DOS functions.

Sometimes we would also pass values through other registers.. These functions can be called by interrupts. DOS programs preside more useful functions such as file maintenance create file.

Operating System is nothing but program that operates computer. We can call these programs by what is known as interrupts.

After generating interrupts. To get the current video mode. Turbo C provides various ways to send arguments and to generate interrupts. We can link this obj file with the main program. Set AH register to 0. Big software companies use "Pure Assembly Style". They create library file with assembly language and link them wherever necessary. Inline assembly is my choice. A to Z of C 85 geninterrupt 0x C style usage and flexibility. If an error occurs. For example in C.

And those functions return the value of AX after completion of the interrupt. One solution for this is to use strtol as: You can even use other styles. Write diagnostic software that finds the status of your peripherals and motherboard. But this interrupt function doesn't increase the size of the EXE file". Is this statement true? That's why I prefer the flexible inline style. This myth is introduced in Indian Programming World by few book authors. But if you are a beginner and if you don't know much of assembly..

I suggest you to use int86 style as it provides good error handling mechanism. Fortunately inline style provides more flexibility and an easy way for entering binary values: Write a program that find out the life of battery found on your motherboard.

This statement has no sense at all. MOV a. To display a single character. If A Graphics Mode you use other adapters Note that it is ROM. VGA is backward compatible.

It supports 16 colors at a time. In the basic VGA mode e. The video card may have upto 8MB in board. On the video card we can see a group of video RAM chips. In normal color text mode 3h 80x25x16 mode. DOS mode.

Hardware engineers sometimes call this video adapter as video card. You can use far pointers to write into video RAM. Whereas in video RAM. Video Adapter Not all the memory is used for display purpose because.

A-to-Z-of-C.pdf

Windows safe mode. But you should know in which display mode. But programmers prefer the declaration. The attribute byte is organized as: The global variable directvideo determine whether the console output by cprintf. The functions of interest in this context are window. For better programming. Following is the example program: In such a case.

Find out the reason. But this mode uses Bh as a segment address. Why graphics mode is slower than text mode? Write a program that finds number of video pages supported by your Video RAM for each mode. From hardware perspective. For example CMOS is accessed via port 70h and 71h. So invoking interrupts some times mean indirect port access. I already pointed out that interrupts are the kind of subroutines and these subroutines also use ports to access hardware devices whenever it is necessary.

Direct port access is much faster in many situations than interrupt code. In this book. The CPU has ports for each of its bus: So using the port addresses we can access hardware devices. Find out the ports used by different peripherals.

Find out the port used by your mouse. Use the details to write a mouse driver program. Controller found on the motherboard can also send data back to the keyboard. In detail. In a typical AT system. The upper and lower case is determined by the state of shift keys. The function of the keyboardcontroller on the motherboard is to translate scan codes and perform other functions.

When you press a key on the keyboard the micro controller in keyboard reads the key switch location in the key matrix. When the keyboardcontroller on the motherboard receives data. This area also holds pointers to keyboard buffer and key status. So I think it is enough to explain the secrets of keyboard in AT systems..

Whenever a key is been inputted through keyboard. Some people say that the size of the keyboard buffer is 32 bytes. Keyboard buffer is a character i.

The pointer kbuftail points to the recently inputted key and the pointer kbufhead points to the key that is being currently processed. The size of the keyboard buffer may vary from system to system. So when the keyboard buffer is empty. When we try to input more keystrokes. Here you should note one important thing: Whereas the kbufhead and kbuftail points to the character on the keyboard buffer and so these pointers do move.

It has four 2-byte wide pointers: In that case you may call INT The status lights. INT 16h. For that we have two ways.

The first byte value must be EDh. To change the status of keyboard. Port 60h keyboard controller data port can be used as keyboard input buffer or keyboard output buffer. If bit0 of status port is 1. That is because. The second byte contains the state to set LEDs. If bit1 of status port is 0. This is because. The BIOS scan code is usually. We can stuff keys with BIOS interrupt 16h or with keyboard buffer. I have restructured it for the sake of clarity.

If no keystroke is available. Usually all BIOS support this interrupt. This is widely used for cracking passwords with brute force technique. The code below was actually by Alexander Russell. So the success of the above code depends upon the reading program written in BIOS.

In order to test this program. Stuff ch. For me the above code works fine. This has many applications. One of them is Piano programming where we would press more than one key.

Write a program that temporarily lock or freeze the system. Write getch and kbhit functions without using any interrupt. Write a program to find out the size of the keyboard buffer. Use stuff key techniques and interfacing techniques to input keys from other devices. Write software to increase or decrease the size of the keyboard buffer.

And so PIT can be setup to work as a one shot pulse generator. Almost all systems have PC speaker. People from Electronics background may be aware that Timer is the one which produces clock signals.

People who like to have digitized sound go for MIDI card or sound blaster card. The output port of speaker is 61h. But for normal operations. Sound ChangeSpeaker ON.

Turn speaker on or off. There are twelve distinct tones in an octave. Using the above formula. Other notes may be calculated from this by using a simple formula: The following program demonstrates this.

In general. The frequencies of higher octaves are just a multiple of frequencies for lower octaves. I could have used a single dimensional array notes[12]. But I have used a two dimensional array notes[7][12] to avoid calculations and to increase the speed. As the frequencies of higher octaves are just a multiple of frequencies of lower octaves.

The main idea here is you have to use port 60h to get a key. This program will provide you the opportunity to try 8 octaves. Since we are using port 60h. Do not use any gadgets or Trial and Error Techniques. If I start explaining all the sound cards. And we must know the standards used by each and every manufacturer.

Each manufacturing company produces sound cards with its own standard. So I left the reader to program for his own sound card as an exercise. I have already explained multiple keys input concept. In that manual. Sound cards are necessary for music software.

Few example codes are available in CD. Write software that plays WAV. If you can write such a software. MIDI files through sound card.

The basic idea is that you have to load frequency value to the register of the sound card. C Program to Demonstrate the Working of Keyword long. C Program to Swap Two Numbers. C Program to Check Leap Year. C Program to Find Factorial of a Number. C Program to Generate Multiplication Table. C Program to Display Fibonacci Sequence. C Program to Reverse a Number. C Program to Calculate the Power of a Number.

C Program to Check Armstrong Number. C Program to Display Factors of a Number. C Program to Find G. D Using Recursion. C program to Reverse a Sentence Using Recursion. C program to calculate the power using recursion.Fortunately we have other commercial Other notes may be calculated from this by using a simple formula: In a typical AT system.

You have to use ports The function of the keyboardcontroller on the motherboard is to translate scan codes and perform other functions. But if you have added the corresponding object OBJ file of the driver. If an error occurs.