C programming by NIKHIL

 Introduction to C programming language  Variables in C programming language  Operators in C programming language  Branching Statement in C programming language  Looping Statement in C language  C Storage Classes  Functions in C programming language  The C Preprocessor  Input/Output Functions in C programming language  File Input/Output Functions in C  Pointers in C  Arrays in C  Dynamic Memory Allocation in C  Strings in C  Structures in C programming language



C programming by NIKHIL

Introduction to C Programming

y In 1972, C was developed at Bell Laboratories by Dennis Ritchie.

y C is a simple programming language with a relatively simple to understand syntax and few keywords.

y C is useless.C itself has no input/output commands, doesn't have support for strings as a fundamental data type. There is no useful math functions built in.

y C requires the use of libraries as C is useless by itself. This increases the complexity of the C.The use of ANSI libraries and other methods,the issue of standard libraries is resolved.

C Programming :: A Quick Hello World Program
Let's give a simple program that prints out "Hello World" to standard out. We'll call our program as hello.c. #include <stdio.h> main() { printf("Hello, world!\n"); return 0; }

Explanation of The Above Code:

#include <stdio.h> -This line tells the compiler to include this header file for compilation.

What is header file?They contain prototypes and other compiler/preprocessor directive.Prototypes are also called the basic abstract function definitions.


C programming by NIKHIL


Some common header files are stdio.h,stdlib.h, unistd.h and math.h.


main()- This is a function, in particular it is the main block.


{ } - These curly braces are equivalent to the stating that "block begin" and "block end".These can be used at many places,such as switch and if statement.


printf() - This is the actual print statement which is used in our c program fraquently.we have header file stdio.h! But what it does? How it is defined?


return 0-What is this? Who knows what is this

Seems like trying to figure out all this is just way too confusing.

Then the return 0 statement. Seems like we are trying to give something back, and it gives the result as an integer. Maybe if we modified our main function definition: int main() ,now we are saying that our main function will be returning an integer!So,you should always explicitly declare the return type on the function.


Let us add #include <stdlib.h> to our includes. Let's change our original return statement to return EXIT_SUCCESS;. Now it makes sense!


printf always returns an int. The main pages say that printf returns the number of characters printed.It is good programming practice to check for return values. It will not only make your program more readable, but at the end it will make your programs less error prone. But we don't really need it in this particular case.So we cast the function's return to (void). fprintf,exit and fflush are the only functions where you should do this.


What about the documentation? We should probably document some of our code so that other people can understand what we are doing. Comments in the C89 standard are noted by this: /* */. The comment always begins with /* and ends with */.


C programming by NIKHIL

An Improved Code of The Above Example
#include <stdio.h> #include <stdlib.h> /* Main Function * Purpose: Controls our program, prints Hello, World! * Input: None * Output: Returns Exit Status */ int main() { (void)printf("Hello, world!\n"); return EXIT_SUCCESS; } Note: The KEY POINT of this whole introduction is to show you the fundamental difference between understandability and correctness. If you lose understandability in an attempt to gain correctness, you will lose at the end. Always place the understandability as a priority ABOVE correctness. If a program is more understandable in the end,the chances it can be fixed correctly will be much higher. It is recommend that you should always document your program. You stand less of a chance of screwing up your program later,if you try to make your program itself more understandable.

The advantages of C
In other words,for writing anything from small programs for personal amusement to complex industrial applications,C is one of a large number of high-level languages designed for general-purpose programming. C has many advantages:


C programming by NIKHIL

The C Compilation Model

Creating, Compiling and Running Your Program
Creating the program


Running the program
The next stage is to run your executable program.You simply type the name of the file containing it, in this case program (or a.out),to run an executable in UNIX. This executes your program able to print any results to the screen. At this stage there may be run-time errors, such as it may become evident that the program has produced incorrect output or division by zero. If so, you must return to edit your program source, and compile it again, and run it again.


C programming by NIKHIL

C is a High Level Language
C is also called as a high-level language. To give a list of instructions (a computer program) to a computer,the high-level computer language is used. The native language of the computer is a stream of numbers called machine level language. As you might expect, the action resulting from a single machine language instruction is very primitive, and many thousands of them can be required to do something like substantial. A high-level language provides a set of instructions you can recombine creatively and give to the imaginary black boxe of the computer. The high-level language software will then translate these high-level instructions into the low-level machine language instructions

Characteristics of C
We briefly list some of C's characteristics that have lead to its popularity as a programming language and define the language. Naturally we will be studying many of these aspects throughout our tutorial.

y y y y y y

Extensive use of function calls Small size Loose typing -- unlike PASCAL Structured language Low level (BitWise) programming readily available Pointer implementation - extensive use of pointers for memory, array, structures and functions.

C has now become a widely used professional language for various reasons.
y y y y

It has high-level constructs. It produces efficient programs. It can handle low-level activities. It can be compiled on a variety of computers.

The main drawback of c is that it has poor error detection which can make it off putting to the beginner. However diligence in this matter can pay off handsomely since having learned the rules of the C we can break them. Not all languages allow this. This if done carefully and properly leads to the power of C programming.


C programming by NIKHIL

C Program Structure
A C program basically has the following form:
y y y y y

Preprocessor Commands Function prototypes -- declare function types and variables passed to function. Type definitions Variables Functions

We must have a main() function C assumes that function returns an integer type,if the type definition is omitted. NOTE: This can be a source of the problems in a program /* Sample program */ main() { printf( ``I Like C \n'' ); exit ( 0 ); } NOTE: 1. 2. 3. 4. printf is a standard C function -- called from main. C requires a semicolon at the end of the every statement. \n signifies newline. Formatted output -- more later. exit() is also a standard function that causes the program to terminate. Strictly speaking it is not needed here as it is the last line of main() and the program will terminate anyway.


C programming by NIKHIL

Variables in C

Variables in C
Like most programming languages, C is able to use and process named variables and their contents. Variables are simply names used to refer to some location in memory - a location that holds a value with which we are working. It may help to think of variables as a placeholder for a value. You can think of a variable as being equivalent to its assigned value.

You can name a variable anything you like as long as it includes only letters, numbers or underscores and does not start with a number. It is a good idea to keep your variable names less than 32 characters long to save time on typing them out and for compiler compati ility reasons. b Variables must always be declared at the top before any other commands are used. Now let's declare an integer variable called a and a character variable called b.:

int main() { int a; char b; return 0; } C keeps a small set of keywords for its own use only.These keywords are given below: auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while

Identifiers in C
Identifiers" or "symbols" are the names you supply for variables, types,labels, and functions in your program. Identifier names must differ in case and spelling from any keywords. You cannot use keywords as the identifiers; they are reserved for special use only. You create an identifier by specifying it in the declaration of a variable,function,or type. In this example which is given below result is an identifier for an integer variable, and printf and main are identifier names for functions. Identifiers provide names for the given language elements:
o o o o o

Functions Function parameters Macros and macro parameters Type definitions Objects


C programming by NIKHIL

o o o

Labels Enumerated types and enumerators Structure and union names

#include <stdio.h> int main() { int result; if ( result != 0 ) printf_s( "Bad file handle\n" ); }

Variable declarations
Variables are of three different types which are as follows: 1. Global Variable 2. Local Variable 3. Static Variable Global Variable: The C programming language has an extensive system for declaring variables of different types. The rules for the more complex types can be confusing at times, due to the decisions taken over their design. The principal decision is that the declaration of a variable should be similar, syntactically, to its use (declaration reflects use) . Declare it outside of all the functions if you want to declare a global variable. The function will use the variable that was declared within it and ignore the global one,if a variable of the same name is declared both within a function and outside of it. Local Variable: Inside the specific function that creates them,these variables only exist. They are unknown to to the main program and to the other functions. In this case,they are normally implemented using a stack. Local variables cease to exist once if the function that created them is completed. Each time a function is executed or called,they are recreated. Variable declarations show up in three places: Outside a function. These declarations declare global variables which are visible throughout the program (i.e. they have global scope). Use of global variables is always a big mistake. o In the header of a function in the argument list . These variables are the parameters to the function. They are only visible inside the function body and their local scope), exist only from when the function is called to when the


C programming by NIKHIL

function returns (bounded extent---note that this is different from what happens in some garbage-collected languages like Scheme), and get their initial values from the arguments to the function when it is called. o At the start of any block delimited by curly braces only. Such variables are exist only when the containing function is active (bounded extent) and visible only within the block (local scope again). The convention in C is generally to declare all such local variables at the top of a function; this is different from the convention in C++ or Java, which encourage variables to be declared when they are first time used

The following program demonstrate the use of global and local variables.
#include <stdio.h> int counter = 0; /* global because we are outside all blocks.*/ int func(void); main() { counter++; /* global because it has not been declared within this block */ printf("counter is %2d before the call to func\n", counter); func(); /* call a function. */ printf("counter is %2d after the call to func\n", counter); } int func(void) { int counter = 10; /* local variable because it has declared within this block */ */ printf("counter is %2d within func\n", counter); }

Using static variables
Another important feature of the variable scoping is the static variable. In a local function scope,a static variable exists only , but it does not lose its value when program execution leaves this scope. Consider the example which is given below: #include <stdio.h> main() { Test();

10 | P a g e

C programming by NIKHIL

} function Test() { int a = 0; printf("a is %d within func\n", a) a++; } Since every time the function is called it sets a to 0 and prints "0",this function is quite useless . The a++ which increments the variable serves no purpose since as soon as the function exits then a variable disappears. The a variable is declared static to make a useful counting function which will not lose track of the current count: #include <stdio.h> main() { Test(); } function Test() { static int a = 0; printf("a is %d within func\n", a) a++; }

Basic types
There are 4 basic types of variable in C; they are: char, int, double and float Type name char int float double Meaning The most basic unit addressable by the machine; typically a single octet. This is an integral type. The most natural size of integer for the machine; typically a whole 16, 32 or 64 bit addressable word. A single-precision floating point value. A double-precision floating point value.

11 | P a g e

C programming by NIKHIL

Operators in C

Overview of the C Operators
The C operators fall into the following categories:
y y y y

y y

Postfix operators, which follow a single operand only. Unary prefix operators, which precede with a single operand. Binary operators, which take two operands and perform a variety of logical and arithmetic 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 only. Assignment operators, which only assign a value to a variable. The comma operator, which gives guarantees left-to-right evaluation of commaseparated expressions.

To create more complex expressions, variables and constants can be used in conjunction with C operators. The following tables describes different operators available in c Operator () [] -> . + [unary] - [unary] * [unary] & [unary] ~ ++ [postfix] - - [prefix] sizeof sizeof + [binary]
12 | P a g e

Example f() a[10] <s->a <="" td=""> </s>a> s.a +a -a *a &a ~a

Description/Meaning Function call Array reference Structure and union member selection Structure and union member selection Value of a Negative of a Reference to object at address a Address of a One's complement of a The value of a after increment The value of a before increment The value of a after decrement The value of a before decrement Size in bytes of object with type t1 Size in bytes of object having the type of expression e a plus b

++ [prefix] ++a a++ -a sizeof (t1) sizeof e a+b

- - [postfix] a-

C programming by NIKHIL

- [binary] * [binary] /% >> << < > <= >= == != & [binary] | ^ && || ! ?: = += -= *= /= %= >>= <<= &= |= ^= ,

a-b a*b a/b a%b a >> b a << b a<b a>b a <= b a >= b a == b a != b a&b a|b a^b a && b a || b !a a ? e1 : e2 a=b a += b a -= b a *= b a /= b a %= b a >>= b a <<= b a &= b a |= b a ^= b e1,e2

a minus b a times b a divided by b Remainder of a/b a, right-shifted b bits a, left-shifted b bits 1 if a < b; 0 otherwise 1 if a > b; 0 otherwise 1 if a <= b; 0 otherwise 1 if a >= b; 0 otherwise 1 if a equal to b; 0 otherwise 1 if a not equal to b; 0 otherwise Bitwise AND of a and b Bitwise OR of a and b Bitwise XOR (exclusive OR) of a and b Logical AND of a and b (yields 0 or 1) Logical OR of a and b (yields 0 or 1) Logical NOT of a (yields 0 or 1) Expression e1 if a is nonzero; Expression e2 if a is zero a, after b is assigned to it a plus b (assigned to a) a minus b (assigned to a) a times b (assigned to a) a divided by b (assigned to a) Remainder of a/b (assigned to a) a, right-shifted b bits (assigned to a) a, left-shifted b bits (assigned to a) a AND b (assigned to a) a OR b (assigned to a) a XOR b (assigned to a) e2 (e1 evaluated first)

Precedence of C Operators
Category Postfix Unary Multiplicative Additive Shift Relational Equality
13 | P a g e

Operator () [] -> . ++ - + - ! ~ ++ - - (type) * & sizeof */% +<< >> < <= > >= == !=

Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right

C programming by NIKHIL

Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Assignment Comma

& ^ | && || ?: = += -= *= /= %= >>= <<= &= ^= |= ,

Left to right Left to right Left to right Left to right Left to right Right to left Right to left Left to right

14 | P a g e

C programming by NIKHIL

Branching Statement in C

The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the flow of the sequence of instructions. C language provides statements that can alter the flow of a sequence of instructions. These statements are called control statements. These statements help to jump from one part of the program to another. The control transfer may be conditional or unconditional. These statements are called as control statements. To jump from one part of the program to another,these statements help. The control transfer may be unconditional or conditional. Branching Statemnt are of following categories: 1. 2. 3. 4. 5. If Statement The If else Statement Compound Relational tests Nested if Statement Switch Statement

If Statement
The simplest form of the control statement is the If statement. It is very frequently used in decision making and allowing the flow of program execution. The If structure has the following syntax if(condition) statement; The statement is any valid C language statement and the condition is any valid C language expression, frequently logical operators are used in the condition statement. The condition part should not end with a semicolon, since the condition and statement should be put together as a single statement. The command says if the condition is true then perform the following statement or If the condition is fake the computer skips the statement and moves on to the next instruction in the program.

15 | P a g e

C programming by NIKHIL

The following program calculate the absolute value of an integer using if statement:
Calculate the absolute value of an integer */ # include < stdio.h > //Include the stdio.h file void main ( ) // start of the program { int numbers; // Declare the variables printf ("Type a number:"); // message to the user scanf ("%d", & number); // read the number from standard input if (number < 0) // check whether the number is a negative number number = - number; // If it is negative then convert it into positive. Printf ("The absolute value is % d \n", number); // print the value }

The If else Statement
The if else is actually just on extension of the general format of if statement. If the result of the condition is true, then program statement 1 is executed, otherwise program statement 2 will be executed. If any case either program statement 1 is executed or program statement 2 is executed but not both when writing programs this else statement is so frequently required that almost all programming languages provide a special construct to handle this situation. The syntax of the If else statement is as follows: If (condition) Program statement 1; Else Program statement 2;

The following program find whether a number is negative or positive using if statement:
#include < stdio.h > //include the stdio.h header file in your program void main ( ) // Start of the main { int num; // declare variable num as integer printf ("Enter the number"); //message to the user scanf ("%d", &num); // read the input number from keyboard if (num < 0) // check whether number is less than zero.

16 | P a g e

C programming by NIKHIL

Printf ("The number is negative") // If it is less than zero then it is negative. Else // else statement. Printf ("The number is positive"); //If it is more than zero then the given number is positive. }

Compound Relational tests
To perform compound relational tests,C language provides the necessary mechanisms. A compound relational test is simple one or more simple relational tests joined together by either the the logical OR operators or logical AND. These operators are represented by character pairs && // respectively. To form complex expressions in C,the compound operators can be used. The syntax of the Compound Relational tests is as follows: a> if (condition1 && condition2 && condition3) b>if (condition1 // condition2 // condition3)

Nested if Statement
The if statement may itself contain another if statement is known as nested if statement. The syntax of the Nested if Statement is as follows if (condition1) if (condition2) statement-1; else statement-2; else statement-3;

The following example print the given numbers along with the largest number using nested if statement.
#include < stdio.h > //includes the stdio.h file to your program main ( ) //start of main function { int a,b,c,big; //declaration of variables printf ("Enter three numbers"); //message to the user scanf ("%d %d %d", &a, &b, &c); //Read variables a,b,c, if (a>b) // check whether a is greater than b if true then
17 | P a g e

C programming by NIKHIL

if(a>c) // check whether a is greater than c big = a ; // assign a to big else big = c ; // assign c to big else if (b>c) // if the condition (a>b) fails check whether b is greater than c big = b ; // assign b to big else big = c ; // assign C to big printf ("Largest of %d,%d&%d = %d", a,b,c,big); } //print the given numbers along with the largest number.

Switch Statement
The switch-case statement is a multi-way decision making statement. Unlike the multiple decision statement that can be created using if-else, the switch statement evaluates the conditional expression and tests it against the numerous constant values.During execution,the branch corresponding to the value that the expression matches is taken. The value of the expressions in a switch-case statement must have to be an ordinal type i.e. integer, char, short, long, etc.Double and Float are not allowed. The syntax of switch statement is as follows : switch( expression ) { case constant-expression1: statements1; [case constant-expression2: statements2;] [case constant-expression3: statements3;] [default : statements4;] } O/P: #include<stdio.h> main() { int n=7; switch(n) { case 0: printf("You typed zero.\n"); break; case 3: case 5: case 7: printf("n is a prime number\n"); break;
18 | P a g e

C programming by NIKHIL

case 2: printf("n is a prime number\n"); case 4: case 6: case 8: printf("n is an even number\n"); break; case 1: case 9: printf("n is a perfect square\n"); break; default: printf("Only single-digit numbers are allowed\n"); break; } }

19 | P a g e

C programming by NIKHIL

Looping Statement in C
Most real programs contain some construct that loops within the program, performing repetitive actions on a stream of data or a region of memory. There are several ways to loop in C. Two of the most common are the while loop: while (expression) { ...block of statements to execute... } and the for loop: for (expression_1; expression_2; expression_3) { ...block of statements to execute... }
The do loop also executes a block of code as long as a condition is satisfied. The difference between a "do ...while" loop and a "while {} " loop is that the while loop tests its condition before execution of the contents of the loop begins; the "do" loop tests its condition after it's been executed at least once. As noted above, if the test condition is false as the while loop is entered the block of code is never executed. Since the condition is tested at the bottom of a do loop, its block of code is always executed at least once. Some people don't like these loops because it is always executed at least once. When i ask them "so what?", they normally reply that the loop executes even if the data is incorrect. Basically because the loop is always executed, it will execute no matter what value or type of data is supposed to be required. The "do ....while" loops syntax is as follows

do { block of code } while (condition is satisfied);
The most interesting and also the most difficult of all the loops is the for loop. The name for is a hangover from earlier days and other languages. It is not altogether appropriate for C's version of for. The name comes from the typical description of a classic for loop: The C for loop is much more versatile than its BASIC counterpart; it is actually based upon the while construction. A for loop normally has the characteristic feature of controlling one particular variable, called the control variable. That variable is somehow associated with the loop. For example it might be a variable which is used to count "for values from 0 to 10" or whatever. The form of the for loop is:

for (statement1; condition; statement2) { }

20 | P a g e

C programming by NIKHIL

C Storage Class

Storage Class
Storage classes include following categories: 1. 2. 3. 4. auto extern register static.

auto is the default storage class for local variables. { int Count; auto int Month; }

extern defines a global variable that is visable to ALL object modules. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined. Source 1 Source 2 -------- -------- extern int count; int count=5; write() main() { { printf("count is %d\n", count); write(); } }

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

static is the default storage class for global variables. The two variables below (count and road) both have a static storage class. The static keyword can be overloaded. static int Count; int Road; main() { printf("%d\n", Count); printf("%d\n", Road); }

21 | P a g e

C programming by NIKHIL

Functions in C

In this tutorial you will learn about C Programming - Functions (Part-I) Functions are used in c for the following reasons, Function definition, Types of functions, Functions with no arguments and no return values, Functions with arguments but no return values, Functions with arguments and return values, Return value data type of function and Void functions. A function is a complete and independent program which is used (or invoked) by the main program or other subprograms. A subprogram receives values called arguments from a calling program, performs calculations and returns the results to the calling program. There are many advantages in using functions in a program they are: 1. It facilitates top down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later. 2. the length of the source program can be reduced by using functions at appropriate places. This factor is critical with microcomputers where memory space is limited. 3. It is easy to locate and isolate a faulty function for further investigation. 4. A function may be used by many other programs this means that a c programmer can build on what others have already done, instead of starting over from scratch. 5. A program can be used to avoid rewriting the same sequence of code at two or more locations in a program. This is especially useful if the code involved is long or complicated. 6. Programming teams does a large percentage of programming. If the program is divided into subprograms, each subprogram can be written by one or two team members of the team rather than having the whole team to work on the complex program We already know that C support the use of library functions and use defined functions. The library functions are used to carry out a number of commonly used operations or calculations. The user-defined functions are written by the programmer to carry out various individual tasks. Function definition: [ data type] function name (argument list) argument declaration; { local variable declarations; statements; [return expression] }

22 | P a g e

C programming by NIKHIL

Example : mul(a,b) int a,b; { int y; y=a+b; return y; } Scope of Function Variables: Only a limited amount of information is available within each function. Variables declared within the calling function can't be accessed unless they are passed to the called function as arguments. The only other contact a function might have with the outside world is through global variables. Local variables are declared within a function. They are created a new each time the function is called, and destroyed on return from the function. Values passed to the function as arguments can also be treated like local variables. Static variables are slightly different, they don't die on return from the function. Instead their last value is retained, and it becomes available when the function is called again. Global variables don't die on return from a function. Their value is retained, and is available to any other function which accesses them. Types of functions: A function may belong to any one of the following categories: 1. Functions with no arguments and no return values. 2. Functions with arguments and no return values. 3. Functions with arguments and return values. Void functions: The functions that do not return any values can be explicitly defined as void. This prevents any accidental use of these functions in expressions.

23 | P a g e

C programming by NIKHIL

The C Preprocessor
The C Preprocessor is a separate step in the compilation process, but not part of the compiler.



C Preprocessor is just a text substitution tool and we'll refer to the C Preprocessor as the CPP.

The C Preprocessor

All preprocessor lines always begin with #. This listing is from Weiss pg. 104. The unconditional directives are as follows: o #define - Define a preprocessor macro o #include - Insert a particular header from another file o #undef - Undefine a preprocessor macro The conditional directives are as follows:
o o o o o o

#ifndef - If this macro is not defined #ifdef - If this macro is defined #if - Test if a compile time condition is true #elif - #else and #if in one statement #else - The alternative for #if #endif - End preprocessor conditional

Other directives include:
o o

## - Token merge, creates a single token from two adjacent ones # - Stringization, replaces a macro parameter with a string constant

The C preprocessor, often known as cpp, is a macro processor that is used automatically by the C compiler to transform your program before compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs. #define MAX_ARRAY_LENGTH 20 The above code will tell the CPP to replace instances of MAX_ARRAY_LENGTH with 20. To increase readability,use #define for constants.

24 | P a g e

C programming by NIKHIL

#include <stdio.h> #include "mystring.h" C preprocessors vary in some details. This manual discusses the GNU C preprocessor, which provides a small superset of the features of ISO Standard C. In its default mode, the GNU C preprocessor does not do a few things required by the standard. These are features which are rarely, if ever, used, and may cause surprising changes to the meaning of a program which does not expect them.

#undef MEANING_OF_LIFE #define MEANING_OF_LIFE 42 The above code tells the CPP to undefine MEANING_OF_LIFE and defin e it for 42.

#ifndef IROCK #define IROCK "You wish!" #endif The above code tells the CPP to define IROCK only if IROCK isn't defined already.

#ifdef DEBUG /* Your debugging statements here */ #endif Thed above code tells the CPP to do the following statements if DEBUG is defined.If you pass the -DDEBUG flag to gcc,this is useful .

25 | P a g e

C programming by NIKHIL

Input/Output Functions in C

The Standard Input Output File
Like many other programming languages, C programs read in (input) or write out (output) characters. Of note is that most any underlying computer (executing C code) also generally has a mechanism by which a single character may be input or output. This input or output of a single character will often be the only way for a program to accomplish I/O functionality.

Character Input / Output
The functions getc() and putc() are much the same. The difference between these and getchar() and putchar() are an extra parameter that identifies a file (through the use of a file descriptor or file pointer) for input to come from, or output to go to. The structure FILE defined in gives access to file pointers and files. 1. getchar 2. putchar

getchar always returns the next character of keyboard input as an int. The EOF (end of file) is returned,if there is an error . It is usual to compare this value against EOF before using it. So error conditions will not be handled correctly,if the return value is stored in a char, it will never be equal to EOF. The following program is used to count the number of characters read until an EOF is encountered. EOF can be generated by typing Control - d. #include <stdio.h> main() { int ch, i = 0; while((ch = getchar()) != EOF) i ++; printf("%d\n", i); }

26 | P a g e

C programming by NIKHIL

putchar puts its character argument on the standard output (usually the screen). The following example program converts any typed input into capital letters.It applies the function toupper from the character conversion library ctype.h to each character in turn to do this. #include <ctype.h> /* For definition of toupper */ #include <stdio.h> /* For definition of getchar, putchar, EOF */ main() { int ch; while((ch = getchar()) != EOF) putchar(toupper(ch)); } Formatted Input / Output These includes following: 1. printf 2. scanf

This offers more structured output than the putchar. Its arguments are, in order; a control string, which controls what get printed, followed by a list of values to be substituted for entries in the control string. The prototype for the printf() is:

int printf(const char *format, ...);

To print,printf takes in a formatting string and the actual variables . An example of printf is: int x = 5; char str[] = "abc";
27 | P a g e

C programming by NIKHIL

char c = 'z'; float pi = 3.14; printf("\t%d %s %f %s %c\n", x, str, pi, "WOW", c); We have already seen that printf handles formatted output to stdout. The counterpart statement for reading from stdin is scanf. The syntax scanf("format string", variables); resembles that of printf. The format string may contain blanks or tabs (ignored), ordinary ASCII characters, which must match those in stdin, and conversion specifications as in printf. Equivalent statements exist to read from or write to character strings. They are: sprintf(string, "format string", variables); scanf(string, "format string", variables); The ``string'' argument is the name of (i.e. a pointer to) the character array into which you want to write the informatio printf("%10.4d", x); The . allows for the precision.To floats as well,this can be applied.The number 5 is on the tenth spacing as the number 10 puts 0005 over 10 spaces. You can also add - and + right after % to make the number explicitly output as +0005. Note that the value of x does not actually change. In other words,you will not get output using %-10.4d will not output -0005. %e is useful for outputting floats using the scientific notation. %le for doubles and %Le for the long doubles.

To grab things from input,scanf() is used. Beware though, scanf isn't greatest function that C has to offer. Some people brush off the scanf as a broken function that shouldn't be used often. The prototype for scanf is: Last example will create a rectangle with rounded corner: int scanf( const char *format, ...); To read of data from the keyboard,scanf allows formatted . Like printf it has a control string,followed by the list of items to be read. However scanf wants to know the address of items to be read, since it is a function which will change that value. Therefore the names of variables are preceeded by the & sign. Character strings are an exception to this. Since a string is already a character pointer, we give the names of the string variables unmodified by a leading &. Control string entries which match values to be read are preceeded by the percentage sign in a similar way to their printf equivalent. Looks similar to printf, but doesn't completely behave like the printf does. Take the example: scanf("%d", x); For grabbing things from input. Beware though, scanf isn't the greatest function that C has to offer,scanf() is used.

28 | P a g e

C programming by NIKHIL

File I/O Functions in C

C File Handling - File Pointers
Use a new datatype called a file pointer to with C files . This type is written as FILE *, and defined within stdio.h. A file pointer called output_file is declared in a statement is as follows:

Opening a file pointer using fopen: Your program must open a file before it can access it. This is done using the fopen function, which returns the required file pointer. If the file cannot be opened for any reason then the value NULL will be returned. You will usually use fopen as follows: if ((output_file = fopen("output_file", "w")) == NULL) fprintf(stderr, "Cannot open %s\n", "output_file"); fopen takes two arguments, both are strings, the first is the name of the file to be opened, the second is an access character, which is usually one of: r-open for reading w-create file for writing a-open file for appending Abstractly, a file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characetrs, words, lines, paragraphs and pages from a textual document; fields and record s belonging to a database; or pixels from a graphical image. The meaning attached to a particular file is determined entirely by the data structures and operations used by a program to process the file. Closing a file using fclose: The fclose command can be used to disconnect a file pointer from a file. This is usually done so that the pointer can be used to access a different file. Systems have a limit on the number of files which can be open simultaneously, so it is a good idea to close a file when you have finished using it. This would be done using a statement like: fclose(output_file);

29 | P a g e

C programming by NIKHIL

Pointers in C

What is Pointer?
A pointer in C is the address of something. It is a rare case indeed when we care what the specific address itself is, but pointers are a quite common way to get at the contents of something. The unary operator `&' is used to produce the address of an object, if it has one.

A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type. The unary or monadic operator & gives the ``address of a variable''. The indirection or dereference operator * gives the ``contents of an object pointed to by a pointer''. To declare a pointer to a variable do: int *pointer;

The following example illustrate the declataion of pointer variable
int *ptr; float *string;

Address operator:
Once we declare a pointer variable then we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=# The above code tells that the address where num is stores into the variable ptr. The variable ptr has the value 21260,if num is stored in memory 21260 address then

30 | P a g e

C programming by NIKHIL

The following program illustrate the pointer declaration
/* A program to illustrate pointer declaration*/ main() { int *ptr; int sum; sum=45; ptr=&sum printf ("\n Sum is %d\n", sum); printf ("\n The sum pointer is %d", ptr); }

Pointer expressions & pointer arithmetic:
In expressions,like other variables pointer variables can be used. For example if p1 and p2 are properly initialized and declared pointers, then the following statements are valid. y=*p1**p2; sum=sum+*p1; z= 5* - *p2/p1; *p2= *p2 + 10;

The following program illustrate the pointer expression and pointer arithmetic
/*Program to illustrate the pointer expression and pointer arithmetic*/ #include< stdio.h > main() { int ptr1,ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2 6; y=6*- *ptr1/ *ptr2 +30; printf("\nAddress of a +%u",ptr1); printf("\nAddress of b %u",ptr2); printf("\na=%d, b=%d",a,b); printf("\nx=%d,y=%d",x,y); ptr1=ptr1 + 70; ptr2= ptr2;
31 | P a g e

C programming by NIKHIL

printf("\na=%d, b=%d,"a,b); }

Pointers and function:
In a function declaration,the pointer are very much used . Sometimes,only with a pointer a complex function can be easily represented and success. In a function definition,the usage of the pointers may be classified into two groups. 1. Call by reference 2. Call by value.

Call by value:
We have seen that there will be a link established between the formal and actual parameters when a function is invoked. As soon as temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between formal and actual parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter always represents a local variable in the called function. The current value of the corresponding actual parameter becomes the initial value of formal parameter. In the body of the actual parameter,the value of formal parameter may be changed. In the body of the subprogram,the value of formal parameter may be changed by assignment or input statements. This will not change the value of the actual parameters. /* Include< stdio.h > void main() { int x,y; x=20; y=30; printf("\n Value of a and b before function call =%d %d",a,b); fncn(x,y); printf("\n Value of a and b after function call =%d %d",a,b); } fncn(p,q) int p,q; { p=p+p; q=q+q; }

32 | P a g e

C programming by NIKHIL

Call by Reference:
The address should be pointers,when we pass address to a function the parameters receiving . By using pointers,the process of calling a function to pass the address of the variable is known as call by reference. The function which is called by reference can change the value of the variable used in the call. /* example of call by reference*? /* Include< stdio.h > void main() { int x,y; x=20; y=30; printf("\n Value of a and b before function call =%d %d",a,b); fncn(&x,&y); printf("\n Value of a and b after function call =%d %d",a,b); } fncn(p,q) int p,q; { *p=*p+*p; *q=*q+*q; }

Pointer to arrays:
an array is actually very much similar like pointer. We can declare as int *a is an address,because a[0] the arrays first element as a[0] and *a is also an address the form of declaration is also equivalent. The difference is pointer can appear on the left of the assignment operator and it is a is a variable that is lvalue. The array name cannot appear as the left side of assignment operator and is constant. /* A program to display the contents of array using pointer*/ main() { int a[100]; int i,j,n; printf("\nEnter the elements of the array\n"); scanf(%d,&n); printf("Enter the array elements"); for(I=0;I< n;I++) scanf(%d,&a[I]); printf("Array element are");
33 | P a g e

C programming by NIKHIL

for(ptr=a,ptr< (a+n);ptr++) printf("Value of a[%d]=%d stored at address %u",j+=,*ptr,ptr); }

Pointers and structures
We know the name of an array stands for address of its zeroth element the same concept applies for names of arrays of structures. Suppose item is an array variable of the struct type. Consider the following declaration: struct products { char name[30]; int manufac; float net; item[2],*ptr; this statement ptr as a pointer data objects of type struct products and declares item as array of two elements, each type struct products.

Pointers on pointer
A pointer contains garbage value until it is initialized. Since compilers cannot detect the errors may not be known until we execute the program remember that even if we are able to locate a wrong result,uninitialized or wrongly initialized pointers it may not provide any evidence for us to suspect problems in pointers. For example the expressions such as *ptr++, *p[],(ptr).member

34 | P a g e

C programming by NIKHIL

Arrays in C

What is an Array?

Array types in C are traditionally of a fixed, static size specified at compile time. However, it is also possible to allocate a block of memory (of arbitrary size) at run-time, using the standard library's malloc function, and treat it as an array. C's unification of arrays and pointers means that true arrays and these dynamically-allocated, simulated arrays are virtually interchangeable. Since arrays are always accessed (in effect) via pointers, array accesses are typically not checked against the underlying array size, although the compiler may provide bounds checking as an option. Array bounds violations are therefore possible and rather common in carelessly written code, and can lead to various repercussions, including illegal memory accesses, corruption of data, buffer overruns, and run-time exceptions.


Although C supports static arrays, it is not required that array indices be validated (bounds checking). For example, one can try to write to the sixth element of an array with five elements, generally yielding undesirable results. This type of bug, called a buffer overflow or buffer overrun, is notorious for causing a number of security problems. On the other hand, since bounds checking elimination technology was largely nonexistent when C was defined, bounds checking came with a severe performance penalty, particularly in numerical computation. The syntax is simple: type name[dim] .

Declaration of arrays
Arrays must be declared before they are used like any other variable. The general form of declaration is: type variable-name[SIZE]; For Ex: int billy [5]; String constants can be associated with variables. C provides the char type variable, which can contain one character--1 byte--at a time. A character string is stored in an array of character type, one ASCII character per location. Never forget that, since strings are conventionally terminated by the null character ``###BOT_TEXT###'', we require one extra storage location in the array!

35 | P a g e

C programming by NIKHIL

float height[50]; Declares the height to be an array containing the 50 real elements. Any subscripts 0 to 49 are all valid. In C the array elements index or subscript begins with the number zero. So height [0] refers to first element of the array. (For this reason, it is easier to think of it as referring to element number zero, rather than as referring to first element). The declaration int values[10]; would reserve the enough space for an array called values that could hold up to 10 integers. Refer to below given picture to conceptualize the reserved storage space.
values[0] values[1] values[2] values[3] values[4] values[5] values[6] values[7] values[8] values[9]

Initialization of arrays:
We can initialize the elements in an array in the same way as the ordinary variables when they are declared. The general form of initialization off arrays is: type array_name[size]={list of values}; For Ex: int array2d[ROWS][COLUMNS]; The values in the list care separated by commas, for example the statement int number[3]={0,0,0}; The initialization of arrays in c suffers two drawbacks 1. There is no convenient way to initialize only selected element. 2. There is no shortcut method to initialize large number of element

36 | P a g e

C programming by NIKHIL

The following program to count the no of positive and negative numbers
/* Program to count the no of positive and negative numbers*/ #include< stdio.h > void main( ) { int a[50],n,count_neg=0,count_pos=0,I; printf("Enter the size of the array\n"); scanf(%d,&n); printf("Enter the elements of the array\n"); for I=0;I < n;I++) scanf(%d,&a[I]); for(I=0;I < n;I++) { if(a[I]< 0) count_neg++; else count_pos++; } printf("There are %d negative numbers in the array\n",count_neg); printf("There are %d positive numbers in the array\n",count_pos); }

Multi dimensional Arrays:
Often there is a need to store and manipulate two dimensional data structure such as the matrices & tables. Here array has two subscripts. One subscript denotes row & the other the column. The declaration of two dimension arrays is as follows: data_type array_name[row_size][column_size]; int m[10][20]; The following program illustrate addition two matrices & store the results in the 3rd matrix /* example program to add two matrices & store the results in the 3rd matrix */ #include< stdio.h > #include< conio.h > void main() { int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q; clrscr();

37 | P a g e

C programming by NIKHIL

printf("enter the order of the matrix\n"); scanf("%d%d",&p,&q); if(m==p && n==q) { printf("matrix can be added\n"); printf("enter the elements of the matrix a"); for(i=0;i < m;i++) for(j=0;j <n;j++) scanf(%d,&a[i][j]); printf("enter the elements of the matrix b"); for(i=0;i < p;i++) for(j=0;j <q;j++) scanf(%d,&b[i][j]); printf("the sum of the matrix a and b is"); for(i=0;i <m;i++) for(j=0;j <n;j++) c[i][j]=a[i][j]+b[i][j]; for(i=0;i < m;i++) { for(j=0;j <n;j++) printf(%d\t,&a[i][j]); printf(\n); } }

38 | P a g e

C programming by NIKHIL

Dynamic Memory Allocation in C

What is Dynamic Memory Allocation?
y Dynamic Memory Allocation is defined as the dynamically allocation of space for variables at runtime. y It is wasteful when dealing with array type structures to allocate so much space when it is declared

Five ANSI Standartd Function Used in Dynamic Memory Allocation
ANSI C provides five standard functions that will help you allocate memory on the heap which are as follows: 1. 2. 3. 4. 5. sizeof() malloc() calloc() realloc() free()

The following table describe the five different standard functions that helps you allocate memory dynamically
Function Task sizeof malloc calloc free realloc The sizeof() function returns the memory size of the requested variable Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space Allocates space for an array of elements initializes them to zero and returns a pointer to the memory Frees previously allocated space Modifies the size of previously allocated space.

39 | P a g e

C programming by NIKHIL

The sizeof() function returns the memory size of requested variable. This call should be used in the conjunction with the calloc() function call, so that only the necessary memory is allocated, rather than a fixed size. Consider the following, struct date { int hour, minute, second; }; int x; x = sizeof( struct date );

A block mf memory may be allocated using the function called malloc. The malloc function reserves a block of memory of specified size and return a pointer of type void. This means that we can assign it to any type of the pointer. It takes the following form: ptr=(cast-type*)malloc(byte-size); ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with the size byte-size. The following is the example of using malloc function x=(int*)malloc(100*sizeof(int));

Calloc is another memory allocation function that is normally used to request the multiple blocks of storage each of same size and then sets all bytes to zero. The general form of calloc is: ptr=(cast-type*) calloc(n,elem-size); The above statement allocates contiguous space for n blocks each size of the elements size bytes. All bytes are initialized to zero and a pointer to the first byte of allocated region is returned. If there is not enough space a null pointer is also returned.

40 | P a g e

C programming by NIKHIL

The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function called realloc. This process is called the reallocation of memory. The general statement of reallocation of memory is : ptr=realloc(ptr,newsize);

Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required at all.When the storage is limited,the release of storage space becomes important . When we no longer need the data we stored in a block of memory and we do not intend to use that block for the storing any other information, Using the free function,we may release that block of memory for future use. free(ptr); ptr is a pointer that has been created by using calloc or malloc.

41 | P a g e

C programming by NIKHIL

Strings in C

What is a String?

A string is combination of characters.


In computing, a C string is a character sequence stored as a onedimensional character array and terminated with a null character ('###BOT_TEXT###', called NUL in ASCII). The name refers to the ubiquitous C programming language which uses this string representation.


In c it is required to do some meaningful operations on the strings

Initializing Strings
In C, an array of type char is used to represent a character string, the end of which is marked by a byte set to 0 (also known as a NUL character) The following definitions both set their arrays to the same values int str1[] = {'a', 'b', 'c', '###BOT_TEXT###'}; int str2[] = "abc";

The following example shows the use of string:
/*String.c string variable*/ #include < stdio.h > main() { char month[15]; printf ("Enter the string"); gets (month); printf ("The string entered is %s", month); } Note: Character string always terminated by a null character µ###BOT_TEXT###¶. A string variable is always declared as an array & is any valid C variable name.

42 | P a g e

C programming by NIKHIL

Reading Strings from the terminal:
The function scanf with %s format specification is needed to read the character string from the terminal itself. The following example shows how to read strings from the terminals: #include < stdio.h > main() { char month[15]; printf (³Enter the string´); gets (month); printf (³The string entered is %s´, month); }

String operations (string.h)
language recognizes that strings are terminated by null character and is a different class of array by letting us input and output the array as a unit. To array out many of the string manipulations,C library supports a large number of string handling functions that can be used such as: 1. 2. 3. 4. 5. Length (number of characters in the string). Concatentation (adding two are more strings) Comparing two strings. Substring (Extract substring from a given string) Copy(copies one string over another)

strlen() function:
This function counts and returns the number of characters in a particular string. The length always does not include a null character. The syntax of strlen() is as follows: n=strlen(string); Where n is the integer variable which receives the value of length of the string.

43 | P a g e

C programming by NIKHIL

The following program shows to find the length of the string using strlen() function
/*writr a c program to find the length of the string using strlen() function*/ #include < stdio.h > include < string.h > void main() { char name[100]; int length; printf("Enter the string"); gets(name); length=strlen(name); printf("\nNumber of characters in the string is=%d",length); } strcat() function: when you combine two strings, you add the characters of one string to the end of the other string. This process is called as concatenation. The strcat() function is used to joins 2 strings together. It takes the following form: strcat(string1,string2) string1 & string2 are the character arrays. When the function strcat is executed string2 is appended to the string1. the string at string2 always remains unchanged.

strcmp function:
In c,you cannot directly compare the value of 2 strings in a condition like if(string1==string2) Most libraries however contain the function called strcmp(),which returns a zero if 2 strings are equal, or a non zero number if the strings are not the same. The syntax of strcmp() is given below: Strcmp(string1,string2)

44 | P a g e

C programming by NIKHIL

strcmpi() function
This function is same as strcmp() which compares 2 strings but not case sensitive. Strcmp(string1,string2)

strcpy() function:
To assign the characters to a string,C does not allow you directly as in the statement name=Robert; Instead use the strcpy() function found in most compilers the syntax of the function is illustrated below. strcpy(string1,string2);

strlwr () function:
This function converts all characters in a string from uppercase to lowercase The syntax of the function strlwr is illustrated below strlwr(string);

strrev() function:
This function reverses the characters in a particular string. The syntax of the function strrev is illustrated below strrev(string);

45 | P a g e

C programming by NIKHIL

The following program illustrate the use of string functions:
/* Example program to use string functions*/ #include < stdio.h > #include < string.h > void main() { char s1[20],s2[20],s3[20]; int x,l1,l2,l3; printf("Enter the strings"); scanf("%s%s",s1,s2); x=strcmp(s1,s2); if(x!=0) {printf("\nStrings are not equal\n"); strcat(s1,s2); } else printf("\nStrings are equal"); strcpy(s3,s1); l1=strlen(s1); l2=strlen(s2); l3=strlen(s3); printf("\ns1=%s\t length=%d characters\n",s1,l1); printf("\ns2=%s\t length=%d characters\n",s2,l2); printf("\ns3=%s\t length=%d characters\n",s3,l3); }

46 | P a g e

C programming by NIKHIL

Structures and Unions in C

What is a Structure?

Structure is a method of packing the data of different types.


When we require using a collection of different data items of different data types in that situation we can use a structure.


A structure is used as a method of handling a group of related data items of different data types.

Syntax of Using Structure
structure definition: general format: struct tag_name { data type member1; data type member2; .... ... }

Example of Using Structure:
struct lib_books { char title[20]; char author[15]; int pages; float price; };

47 | P a g e

C programming by NIKHIL

To holds the details of four fields namely title, author pages and price,the keyword struct declares a structure. These are the members of the structures. Each member may belong to same or different data type. The tag name can be used to define the objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure. We can declare the structure variables using the tag name any where in the program. For example the statement, struct lib_books book1,book2,book3; declares the book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books. The complete structure declaration might look like this The complete structure declaration might look like this struct lib_books { char title[20]; char author[15]; int pages; float price; }; struct lib_books, book1, book2, book3;

Get the Length of a Node List
The node list is always keeps itself up-to-date. If an element is deleted or added, in the node list or the XML document, the list is automatically updated. The node list has a useful property called the length. The length property return the number of node in a node list. The following code fragment get the number of <title> elements in "bookdetails.xml": struct lib_books { char title[20]; char author[15]; int pages; float price; }; struct lib_books, book1, book2, book3; The following program shows the use of structure

48 | P a g e

C programming by NIKHIL

/* Example program for using a structure*/ #include< stdio.h > void main() { int id_no; char name[20]; char address[20]; char combination[3]; int age; }newstudent; printf("Enter the student information"); printf("Now Enter the student id_no"); scanf(³%d´,&newstudent.id_no); printf(³Enter the name of the student´); scanf(³%s´,&new student.name); printf(³Enter the address of the student´); scanf(³%s´,&new student.address); printf(³Enter the cmbination of the student´); scanf(³%d´,&new student.combination); printf(Enter the age of the student´); scanf(³%d´,&new student.age); printf(³Student information\n´); printf(³student id_number=%d\n´,newstudent.id_no); printf(³student name=%s\n´,newstudent.name); printf(³student Address=%s\n´,newstudent.address); printf(³students combination=%s\n´,newstudent.combination); printf(³Age of student=%d\n´,newstudent.age); }

However the members that we compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for the application involving multiple members. Where values need not be assigned to all the members at any time. Unions like structure contain members whose individual data types may differ from one another also. Like structures union can be declared using the keyword union as follows:

49 | P a g e

C programming by NIKHIL

Last example will create a rectangle with rounded corner: union item { int m; float p; char c; } code; The notation for accessing a union member that is nested inside a structure remains the same as for the nested structure.In effect,a union creates a storage location that can be used by one of its members at a time. When a different number is assigned to a new value the new value supercedes the previous members value. Unions may be used in all the places where a structure is allowed.

50 | P a g e