A Beginner's Guide To "C" Programming
A Beginner's Guide To "C" Programming
Sindu Naraayanan
Page 1 of 56
Today, C remains the second most popular programming language in the world (or at least the language in which the second most lines of code have been written), and ushered in C++ and Java; C has been
C is a popular general purpose programming language. C programs are efficient, fast and highly portable computer can be run on another i.e. C programs written with little or no on one
modification. It
combines the features of high level language and functionality like assembly language. It reduces the gap between high level language and low level language that is why it is known as middle level language. C is a structured language.
Sindu Naraayanan
Page 2 of 56
STRUCTURE OF A C PROGRAM :
Sindu Naraayanan
Page 3 of 56
Global declaration:
This section declares some variables that are used in more than one function. These variables are known as global variables.
Function main:
Every program written in C language must contain main ( ) function. An empty parenthesis after main is necessary. The function main ( ) is starting part of program execution.
Declaration part:
The declaration part declares the entire variables that are used in the executable part. The initializations of variables are also done in this section
Executable part:
This part contains the statement following the declaration of variables. This part contains a set of statements or a single statement. These statements are enclosed within braces.
Sindu Naraayanan
Page 4 of 56
Comments:
Comments are not necessary in the program. However, to understand the flow of programs the programmer can include comments in the program. Comments are placed between the delimiters /* &*/. Comments are not the part of executable programs.
PROGRAMMING RULES:
1. All statements should be written in lower case letters (small letters). Upper case letters are only used for symbolic constants. 2. Blank spaces should not be used while declaring a variable, keyword, constants and function. 3. All statements are terminated with semi-colon (;). 4. The opening and closing brace should be balanced, i.e. if opening braces are four then closing braces should be four. 5. Declaration of variables of same type is done in a single statement using comma (,). A program is a set of statements for a specific task, which will be executed in a sequential form. Every program must follow accurately the syntax rules supported by the language.
BASIC TOKENS:
1. Keywords: The C keywords are reserved words by the compiler all the c keywords have been assigned fixed meaning. The keywords cannot be used as variable names because they have been assigned jobs. E.g : auto , break , int , char , float , long , short , e.t.c
Identifiers are names of variables, functions, and arrays. They are user defined names, consisting of sequence of letters as the first character .Lower case letters are preferred; however upper case letters are also permitted. The underscore (_) symbol is used as a link between two words in long identifiers. #define N 10 (means N =10)
3. Constants:
Variables whose value does not change during the execution of a program are known as constants. Constants are declared using the keyword const. The different types of constants in C are Numeric constants Integer constants Real constants Character constants Single character constants String constants
Variables:
A variable is a data name used for storing a data value. Its value may be changed during the program execution. A variable name may be declared based on the meaning of the operation. E.g: A variable used to store the sum of two numbers can be named as SUM.
Sindu Naraayanan
Page 6 of 56
Data types:
All C compilers support a variety of data types. This enables the programmer to select the appropriate data types as per the need of the application.
Range: -32,768 t0 +32,767 Control string: %d (or) %I E.g. short int 2=5;
Long integer Occupies 4 bytes in memory Range: -2147483648 to +2147483647 control string used is %ld E.g. long int c= 30004;
Sindu Naraayanan
Page 7 of 56
Signed integer Occupies 2 bytes in memory Range: -32,768 t0 +32,767 Control string: %d (or) %i
E.g. int a= 2;
Unsigned integer Occupies 2 bytes in memory Range: 0 to 65535 Control string used is %u E.g. unsigned long b;
Sindu Naraayanan
Page 8 of 56
(iii) Float:
Floating point number has two parts they are mantissa and exponent. The mantissa is either whole number or a decimal number. The exponent is an integer number which may be positive or negative.
Float:
Occupies 4 bytes in memory Range: 3.4e-38 to 3.4e+38 Control string: %f E.g: float a;
Double
Occupies 2 bytes in memory Range: 1.7e-308 to 1.7e+308 Control string used is %lf E.g: double k;
long double
Occupies 10 bytes Range is 3.4e-4932 to 1.1e+4932 Control string is %lf. E.g: long double x;
Sindu Naraayanan
Page 9 of 56
Declaring variables:
The declaration of variables should be done in the declaration part of the program .The variables must be declared before they are used in the program. Declaration provides two things (i) (ii) compiler obtains the variable name It tells the complier data type of the variable declared and helps in allocating memory. Syntax: Data_type variable _name;
Data Types
Character Signed character Unsigned character Integer Signed int Unsigned int Unsigned short integer Signed long integer Unsigned long integer Floating point
Keyword
char Signed char Unsigned char int Signed int Unsigned int Unsigned short int Signed long int Unsigned long int float
Sindu Naraayanan
Page 10 of 56
Initializing variables:
Variables declared can be assigned or initialized using an assignment operator = . The declaration and initialization can be done in the same line.
Syntax:
variable_name= constant or data_type variable_ name =constant Example: int x; x=2; int z =5;
Sindu Naraayanan
Page 11 of 56
They are arithmetic operators relational operators logical operators bitwise operator
Type f operators
Arithmetic operators Relational operators Logical operators Increment and decrement operator Assignment operators Bitwise operators Comma operator Conditional operator
Symbolic representation
+,-,*,/ and % >, <, = =,>=, <= and ! = &&, || and ! ++ and -= &,|,^,>>,<< and ~ , ?:
Sindu Naraayanan
Page 12 of 56
Operators
() [] ->
Operation
Function call Array expression Structure operator
Clubbing
Left to right Left to right Left to right
Priority
1st 1st 1st
Structure operator
Left to right
1st
+ ++
--
Decrement operator
Right to left
2nd
! ~
2nd 2nd
Pointer operator Address operator Size of operator Type cast Multiplication Division
Right to left Right to left Right to left Right to left Left to right Left to right
Sindu Naraayanan
Page 13 of 56
Modular division Addition Subtraction Left shift Right shift Less than Less than or equal to
Left to right Left to right Left to right Left to right Left to right Left to right Left to right
> >=
6th 6th
== != & ^ | && || ?:
Equality Inequality Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional operator
Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left
Assignment operator
Right to left
14th
Sindu Naraayanan
Page 14 of 56
Comma operator
Left to right
15th
When two operators of the same priority are found in the expression, precedence is given to extreme left operator.
If there are more sets of parenthesis in the expression, the innermost parenthesis will be solved first, followed by the second and so on.
Comma operator:
The comma operator is used to separate two or more expressions. The comma operator has lowest priority among all the operators. E.g: int a= 2, b= 4, c= a+b;
Syntax:
condition? expression 1 : expression 2 E.g: 3>2 ? printf (true): printf (false);
Output: true
Sindu Naraayanan
Page 15 of 56
Arithmetic operators:
The two types of arithmetic operators are Binary operator: These arithmetic operators are used for numerical calculations between two constant (or operands) values. These are arithmetic operators
are called as binary operators. The binary operators are: +, - , *, /, % (refer table for their precedence).
Unary operator: The arithmetic operators which act on one operand are called as unary operator. They are increment (++), decrement (--) and minus (-). Unary minus is used to indicate or change the arithmetic sign of a value.
Output: y = 50
Sindu Naraayanan
Page 16 of 56
then the post increment/ decrement takes place. If ++ or are used as a prefix to variables name then the pre increment/ decrement takes place. Example 1: int a= 6; printf (a++ = %d, a++); printf ( \n a = %d,a);
Example 2: int a= 6; printf (++a = %d, a++); printf (\n a = %d, a); Output: ++a = 7 a=7
Sindu Naraayanan
Page 17 of 56
Relational operator:
These operators are used to distinguish between two values depending on their relations. These operators provide relationship between the two expressions. If the relation is true then it returns true else false. The relational operators are >, <, <=,> =, = =, =
Sindu Naraayanan
Page 18 of 56
Example: printf (10 = = 10 = %d, 10==10); printf (10 != 10 = %d, 10!=10); printf (10 > = 6 = %d, 10>=6); printf (10 < =10 = %d, 10<=10);
Logical operators:
The logical relationship between the two expressions is checked with logical operators. Using these operators low expressions can be combined .this operators also returns either a1 (true) or 0 (false).The operators could be constants, variables or expressions. Example: printf (%d, 5>3 && 2>3); printf (%d,5>3 || 2>3); printf (%d,!(10==10));
Sindu Naraayanan
Page 19 of 56
Output: 0 1 0
Bitwise operator:
C supports a set of bitwise operator, they are >>, <<, ^, ~, &,|. These operators are used to perform bit by bit manipulation on data .these operators can act only on integer such as int, char, short int, long int etc. << (left shift operator) multiplies the number by 2; x = 2; x>>3; Output is 8 (2 is multiplied 3 times by 2) >> (right shift operator) divides the number by 2; x = 8; x>>1; Output is 4 (8 is divided 1 times by 2)
Sindu Naraayanan
Page 20 of 56
Formatted functions: The formatted I/O functions read and write all types of data values. They require control strings to identify the data type. Hence, they can be used for both reading and writing of all data values. The formatted functions return the values after execution. The return value is equal to the number of variables successfully read/written. Using this value user can find out the errors occurring during reading or writing data. Unformatted functions: The unformatted I/O functions only work with the character data type, so they dont need control strings. The unformatted function also returns value, but the return value of unformatted function is always the same.
I/O functions
Unformatted functions : getch() ,getchar(), gets(),putch(), putchar(), puts()
Sindu Naraayanan
Page 21 of 56
FORMATTED FUNCTIONS
printf () statement: The printf () function printf all types of data values to the console. It requires control string and variable names to print the data. the control string and variable names should be in order. Syntax: printf (control stings , variables); Example: int x; float y; char z; printf (%d, %f, %c, x, y, z);
scanf () statement: The scanf () statement reads all type of data values. It is used for runtime assignment of variables. The scanf () statement also requires control string to identify the type of data to be read during execution of the program. The scanf () statement requires & operator called address operator, its role is to indicate the memory location of the variable , so that the value read would be placed at that location. Syntax: scanf(control string,& variable names); Example: int x; float y ; char z; printf (%d, %f, %c ,&x ,&y ,&z);
Sindu Naraayanan
Page 22 of 56
Data type
Short int Short unsigned Long singed Long unsigned Integer Unsigned hexadecimal Unsigned octal Float Real Double Signed character unsigned character character String
Control string
%d or %i %u %ld %lu %x %o %f or %g %lf %c %c %s
Example: void main() { char name[25]; printf(\n Enter your name : ); scanf(%s,name); printf(\n My name is %s ,name); }
Sindu Naraayanan
Page 23 of 56
UNFORMATTED FUNCTIONS :
C has three types of I/O functions, they are
Syntax: variable_name = getchar(); Example: char word[15]; int count =0; while((word[count] = getchar())!=\n) c++; word[count] = \0; printf(\n%s,word);
Sindu Naraayanan
Page 24 of 56
2) putchar():
This function prints one character on the screen at a time which is read by the standard input.
Syntax:
putchar(variable_name);
Example:
void main() { char word[15]; int count =0; while((word[count] = getchar())!=\n) { putchar(word[count]); c++; } word[count] = \0; }
Sindu Naraayanan
Page 25 of 56
Sindu Naraayanan
Page 26 of 56
4) putch() : This function prints any alphanumeric character taken by the standard input device. Syntax: putch(variable_name); Example: char ch; printf(\n Enter any character to continue :); ch= getch(); printf(\n You entered : ); putch(ch);
gets():
This function is used for accepting any string through stdin(keyboard) until enter key is pressed. The header file needed is <stdio.h>.
Syntax:
Sindu Naraayanan
Page 27 of 56
gets(variable_name); Example: char name[25]; printf(\n Enter your name: ); gets(name); printf(\n %s,name);
puts() :
This function prints the string or character array(another name of string ).
Syntax:
puts(variable_name);
Sindu Naraayanan
Page 28 of 56
puts(name); }
Output:
Enter your name: Techhoot Techhoot
Syntax:
fscanf(file_pointer ,control string, variable_name); fprintf():
Syntax:
fprintf(file_pointer ,control string, variable_name);
Example:
FILE *p1; char name[10]=techhoot, ch[10];
Sindu Naraayanan
Page 29 of 56
fprintf (p1,%s,name); fscanf (p1,%s,ch); printf (\n Content of the file is %s,ch);
Output:
Content of the file is techhoot
DECISION STATEMENTS
A program is nothing but the execution of one or more instructions. In monolithic program the sequences of instructions are executed in the same way as they paper in the program. This sequence can be altered using decision making statements. By using decision making the following can be achieved To alter the flow of a program Test the logical conditions. Control the flow of execution as per the selection.
The decision making statements checks the given condition and then executes its sub block. The decision statement decides the statement to be executed after the success or failure of a given condition. 1. The if statement: If statement executes a set of command lines or one command line when the logical condition is true else it executes statement x. It has only on option. The condition is always enclosed within a pair of parenthesis . The conditional statements should not be terminated with semicolon (;).
Sindu Naraayanan
Page 30 of 56
Syntax:
if(condition) { action block; } Example: int sum; if(3>2) { printf(\n true); }
2. The if ....else statement: The if..else statement takes care of true as well as false conditions. It has two blocks. One block is for if and it is executed when the condition is true. The other block is of else and it is executed when the condition fails. The else statement cannot be used without if.
Syntax:
if(condition) { action block 1;
Sindu Naraayanan
Page 31 of 56
Syntax:
if(condition)
Sindu Naraayanan
Page 32 of 56
Sindu Naraayanan
Page 33 of 56
Syntax:
if(condition 1) { //action block } else if (condition 2) { // action block } .
Sindu Naraayanan
Page 34 of 56
Example: if(mark>80) printf(\n distinction); else if(mark >60) printf(\n first class); else if(mark>=40) printf(\n pass); else printf(\n fail);
Sindu Naraayanan
Page 35 of 56
The keyword break allows the user to terminate the loop. The break skips from the loop or block in which it is defined. The control then automatically goes to the first statement after the loop or block. The break statement can be associated with all conditional statements. If break statement is used within the innermost loop, then the control of the program is terminated only from the innermost loop. Example: for(i=0;i<n;i++) { printf(\n); for(j=0 ; j<i ; j++) { if(j==i) { break; } printf(\t %d,j); } }
Explanation:
Here the break statement causes the control to exit from j loop (innermost loop)
The continue statement is used for continuing next iteration of the loop statements. When it occurs in the loop it does not terminate, but skips the statements that continue statement. It is useful when we want to continue the program without executing any part of the program.
Sindu Naraayanan
Page 37 of 56
The keywords case and break performs the respectively the job of opening and closing curly braces.
Syntax:
switch(variable or expression) { case constant_1: statement; break; case constant_2 : statement; break; case constant_n: statement; break; default: statement; }
Example: int ch; printf(\n enter a number either 1 or 2); scanf(%d,&ch); switch(ch) { case 1:printf(\n ONE);break;
Sindu Naraayanan
Page 38 of 56
LOOPING STATEMENTS:
A loop is defined as a block of statements which are repeatedly executed for certain number of times otherwise Loop causes a section of code to be executed repeatedly until a termination condition is met. The following are the looping statements supported in c: (a) for statement (b) while statement (c) do-while statement Purpose (working) of each loop is the same, difference lies in their structure.
Steps in loop:
Loop variable: It is a variable used in the loop. Initialization: It is the first step in which starting value is assigned to the loop variable. Each time the updated value is checked by the loop itself. Increment/Decrement: It is the numerical value added or subtracted to the variable in each round of the loop. Test expression (or) condition: This determines when the loop is to be terminated.
Sindu Naraayanan
Page 39 of 56
Based on the place where condition is placed we have two types of loop, they are (i) Entry check loop (ii) Exit check loop
Syntax:
for(initialise counter; test condition; increment/decrement) { // body of for loop }
Example: // to calculate factorial n numbers using for loop int i, n,f=1; for(i=1;i<n;i++)
Sindu Naraayanan
Page 40 of 56
while loop:
while is the keyword . it is not terminated with (;).
Syntax:
initialization; while(condition) { // body of while loop increment/decrement; }
Example: // to calculate factorial n numbers using while loop int i, n,f=1; i=1; while(i<n) {
Sindu Naraayanan
Page 41 of 56
Do-while loop:
do and while are the key words, and in do-while loop condition is terminated with (;). while is the keyword . it is not terminated with (;).
Syntax:
initialization; do { // body of while loop increment/decrement; } while(condition);
Sindu Naraayanan
Page 42 of 56
ARRAYS
Array is a collection of similar data types in which each element is unique and located in separate memory locations. Characteristic of array:
All elements of an array share the name, and they are distinguished from
the other with help of an element number ( array index)
Array index plays a major role in calling each element. Array is identified with its [] brackets. They have contiguous memory location Array index always starts from 0 to (size -1) Size of an array should be positive
Sindu Naraayanan
Page 43 of 56
Array can initialized as they are declared. The two types of initialization are static and dynamic initialization. If the array is initialized where it is declared it is said to be static initialization. E.g. int a[5]={11,2,3,4,5}//one dimensional array, i.e. ay with one subscript) Dynamic initialization is done using malloc(), calloc() and new. E.g. int a[]=(int)malloc(sizeof(int),5); Note: string is a one dimensional array and it is terminated by a null string \0.
NOTE: There does not exist any row or column in memory , elements of 2D array are stored in continuous locations(like chain). Passing an array to function:
Sindu Naraayanan
Page 44 of 56
Syntax: function_name(array_name/identifier, array_size); Example: main() { int a[5]; //some statements; add(a,5);//passing array named a to the function add() return 0; }
Pointer notations:
1-D array: Syntax:
*(pointer variable + array_index)//array_index-position of the element Example: int natural[5] ,*p; p=natural[0]//or p= natural or p= &natural[0] printf(%d,*(p+2));//prints the element at position 2;
2-D array:
Sindu Naraayanan
Page 45 of 56
syntax:
*(pointer_variable +row_no * no.of col +col_no); Example: int matrix[2][3],*p; p=matrix; printf(%d,*(p+1*3+2));//prints the element at matrix[1][2];
FUNCTIONS:
Building blocks of c programs are functions. A function is a self - contained block or a sub program with one or more statements that performs a special task. The two types of functions are
Working of functions:
Sindu Naraayanan
Page 46 of 56
Once a function is defined and called, it takes some data from the calling program and returns a value to the calling program.// calling program program which calls the function , called function program which is called for some special task. Whenever a function is called, control passes to the called function and the working of calling function is stopped. When the execution of called function is completed, control returns back to the calling program and execute the next statement. The values of actual parameters passed by calling function are received by formal parameters of the called function. The number of actual and formal parameter should be the same. The called function can also return data to the calling function. This is done by the return statement. Function prototype (declaration): return_type function_name(argument /parameter list);// semi colon is present in the function declaration and absent in function definition. void add(int a, int b);//a , b are the name of the parameters /arguments By default the return type of a function is int. A function prototype contains the function name , return type , number of parameters and their data types . Actual argument/parameter: The arguments of the calling function are called actual arguments. Formal parameter: The arguments of the called function are called formal parameters/arguments.
Sindu Naraayanan
Page 47 of 56
Sindu Naraayanan
Page 48 of 56
Arguments are passed to the called function by the calling function and the called function does not return any values to the calling function. They are partially dependent: Example: void main()// calling function { void add(int , int ); add( 5,6);// call to the function add() } void add(int a , int b ) { int c; c= a+b; }
Sindu Naraayanan
Page 49 of 56
int c; int add(int , int ); c = add( 5,6);// call to the function add() } int add(int a , int b ) { int d; d= a+b; return (d);// return is the keyword }
Sindu Naraayanan
Page 50 of 56
Sindu Naraayanan
Page 51 of 56
2) Call by reference:
In this type instead of value, address (reference) is passed, so the formal parameters should be of pointers. Hence any changes made to the formal parameter are reflected back in the actual parameter. Example: void main() { int a = 5 , b= 6; swap(&a,&b); // print values of a and b } void swap( int *a, int *b) { int t; t=*a; *a=*b; *b=*t; // print values of a and b } Function can return more than one value using reference method (i.e. .pointers).
Sindu Naraayanan
Page 52 of 56
Syntax:
struct structure_name { data_type data_type data_type data_type }; member 1; member 2; member 3; member n;
Example:
struct classroom { int benches;//structure members char class_name[25]; }; Syntax to create object for a structure:structure_name object_name; classroom c1;
Sindu Naraayanan
Page 53 of 56
Union:
Union is similar to structure. In structure each element has its own memory, but members of union share common memory. The member or variable which occupies more number of bytes will be the size of the union and that number of bytes is allocated to the union. This allocated memory is shared by all other members of the same union.
Syntax:
union union_name { data_type data_type data_type data_type }; member 1; member 2; member 3; member n;
Example:
union classroom { int benches;//structure members, occupies 2 bytes char class_name[25];// occupies 25 bytes }; Syntax to create object for a union: union_name object_name; classroom c1;
Sindu Naraayanan
Page 54 of 56
Thus I conclude this ebook with hope that it would have instilled the interest and skill of C programming in you. The above discussed topics are the basic for anyone to develop a C program. Happy C coding !!!
-Sindu Naraayanan,
Author, Techhoot.com
Sindu Naraayanan
Page 55 of 56
Did you like this PDF Guide? Then why not visit Techhoot.com for daily posts on cool websites, free software and internet tips.
Subscribe to Techhoot Times and receive instant access to such material like this one covering wide range of topics. Moreover, you will be able to download free Cheat Sheets, Software reviews and other cool things.
Techhoot.com Links:
Home: Home Newsletter: Techhoot Times Facebook: Techhoot At Facebook Twitter: Techhoot at Twitter
Sindu Naraayanan
Page 56 of 56