Sunteți pe pagina 1din 92

C Beginner

Day -I C Language History


C language is a structure oriented programming language, was developed at Bell Laboratories in 1972 by Dennis Ritchie C features were derived from earlier language called B (BCPL language) C was invented for implementing UNIX operating system In 1978, Dennis Ritchie and Brian Kernighan published the first edition The C Programming Language and commanly known as K&R C In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or ANSI C, was completed late 1988.

Features of C language:
Reliability Portability Flexibility Interactivity Modularity Efficiency and Effectiveness

Uses of C language:
C is used for developing system applications that forms portion of operating system. Below are some examples of C being used. Database systems Graphics packages Word processors Spread sheets Operating system development Compilers and Assemblers Network drivers
1

C Beginner

Interpreters

Which level the C language belonging to?


S.n o High Level Middle Level Low Level

High level Middle level languages Low level languages provides dont provide all the languages almost everything built-in functions found in provides that the high level languages, but nothing other programmer might provides all building than access to need to do as blocks that we need to the machines already built into produce the result we basic instruction the language want set Examples: Ada, BASIC, COBOL, FORTRAN, Modula-2

C, C++, JAVA, Assembler FORTH, Macro-Assembler

C is a structured language
S.n o Structure oriented Object oriented Non structure

In this type of In this type of There is no specific language, large language, programs structure for programs are divided are divided into programming this into small programs objects language called functions Prime focus is on functions and procedures that operate on data Prime focus is on the data that is being operated and N/A not the functions or procedures

C Beginner

Data moves freely around the systems from one function to another Program structure follows Top Down Approach Examples:

Data is hidden and cannot be accessed N/A by external functions Program structure follows Bottom UP N/A Approach

C,BASIC, COBOL, FORTRAN

C++, JAVA, Ada, Pascal, Modula-2

Assembler

Key points to remember:


C is structured, middle level programming language developed by Dennis Ritchie Operating system programs such as Windows, Unix, Linux are written by C language C has been written in assembly language C Basic Program: Now, we are going to learn a simple Hello World program in this section. Functions and syntax used in this program are explained in below table. 1 #include <stdio.h> 2 3 int main() 4{ 5 6 7 /* Our first simple C basic program */ printf("Hello World! "); return 0;

C Beginner

8} Output: Hello World! Let us see the performance of above program line by line. S.n o Command Explanation This is a preprocessor command that includes standard input output header file(stdio.h) from the C library before compiling a C program This is the main function from where execution of any C program begins whatever is given inside /* */ this command wont be considered by C program for compilation and execution. printf command prints the output onto the screen This command terminates main function then returns 0

#include<stdio.h >

int main()

/* some comments */ printf(Hello World! ); return 0;

Compile and execute C program:


Compilation is the process of converting a C program which is user readable code into machine readable code which is 0s and 1s. This compilation process is done by a compiler which is an inbuilt program in C. As a result of compilation, we get another file called executable file. This is also called as binary file.

C Beginner

This binary file is executed to get the output of the program based on the logic written into it.

Steps to compile & execute a C program: Step Type the above C basic program in a text editor and save 1 as sample.c. To compile this program, open the command prompt and Step goto the directory where you have saved this program and 2 type cc sample.c or gcc sample.c. Step If there is no error in above program, executable file will be 3 generated in the name of a.out. Step To run this executable file, type ./a.out in command 4 prompt. Step You will see the output as shown in the above basic 5 program. C basic structure: As already mentioned,c basic structure is defined by set of rules called protocol, to be followed by programmer while writing C program. Below is the C basic structure.

C Beginner

1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8

/* C basic structure explained Author: cclass.com // Documentation section Date : 01/01/2012 */ #include <stdio.h> // Link section int total; // Global declaration section int sum (int, int); // Function declaration section int main () // Main function { printf ("This is main function \n"); total = sum (1, 1); printf ("Total = %d \n", total); return 0; } int sum (int a, int b) { // User defined function return a + b; // definition section }

C Beginner

We are getting the below output while executing this program.

Output: This is main function Total = 2 Let us see about each section of a C basic program in detail below. All below sections together are called as C basic structure. S.N o Sections Description We can give comments about the program, creation or modified date, author name etc in this section. Comments can be given in two ways inside a C program. 1. Single line comment Syntax : // Your Comments Here 2. Multi line comment Syntax : /* comment line1 comment line2 comment line3 */ The characters or words or anything which are given between /* and */, wont be
7

Documentation section

C Beginner

considered by C compiler for compilation process.These will be ignored by C compiler during compilation. Header files that are required to execute a C program are included in this section In this section, variables are defined and values are set to these variables. Global variables are defined in this section. When a variable is to be used throughout the program, can be defined in this section. Function prototype gives many information about a function like return type, parameter names used inside the function. Every C program is started from main function and this function contains two major sections called declaration section and executable section. User can define their own functions in this section which perform particular task as per the user requirement.

Link Section

Definition Section

Global declaration section Function prototype declaration section

Main function

User defined function section

Key points to remember: Execution of every C program starts from main() function. Protocol is set of rules to be followed by a programmer to write a program.

C Beginner

[DAY 2]

C Data Types
C data types are defined as the data storage format that a variable can store a data to perform a specific operation. Data types are used to define a variable before to use in a program. Size of variable, constant and array are determined by data types.

C data types:
There are four data types in C language. They are, S.no 1 2 3 4 Types Basic data types Enumeration data type Derived data type Void data type Data Types int, char, float, double enum pointer, array, structure, union void

Modifiers:

The amount of memory space to be allocated for a variable is derived by modifiers. There are 5 modifiers available in C language. They are, 1. short
9

C Beginner

2. 3. 4. 5.

long signed unsigned long long

Below table gives the detail about the storage size of each C basic data type. S.N o 1 2 3 C Data types Char int float 1 2 or 4 4 storage Size 127 to 127 32,767 to 32,767 1E37 to 1E+37 with six digits of precision 1E37 to 1E+37 with ten digits of precision 1E37 to 1E+37 with ten digits of precision 2,147,483,647 to 2,147,483,647 32,767 to 32,767 0 to 65,535 32,767 to 32,767 (263 1) to 263 1
10

Range

double

long double

10

6 7 8 9 10

long int short int unsigned short int

4 2 2

signed short int 2 long long int 8

C Beginner

11 12 13

signed long int

2,147,483,647 to 2,147,483,647 0 to 4,294,967,295 264 1

unsigned long int 4 unsigned long long int 8

sizeof () operator is used to find the memory space allocated for each C data types.

Example program for sizeof() function:


1 2 3 #include <stdio.h> 4 #include <limits.h> 5 6 int main() 7 { 8 9 int a; 1 char b; 0 float c; 1 double d; 1 printf("Storage size 1 printf("Storage size 2 \n",sizeof(b)); 1 printf("Storage size 3 \n",sizeof(c)); 1 printf("Storage size 4 \n",sizeof(d)); 1 return 0; 5 } 1 6 Output:

for int data type:%d \n",sizeof(a)); for char data type:%d for float data type:%d for double data type:%d

Storage size for int data type:4 Storage size for char data type:1 Storage size for float data type:4
11

C Beginner

Storage size for double data type:8 Void data type: Void is an empty data type that has no value. This can be used in functions and pointers. Key points to remember: Data types define a variable in a C program. int, char, float, double and void are C basic data types int data type returns a value from function call. void data type does not return any value from function call. It has no size. sizeof () operator is used to find the memory space allocated for each data type

C Tokens, identifiers and keywords:


C Tokens : These are the basic buildings blocks in C language which are constructed together to write a C program.Each and every smallest individual units in a C program are known as C Tokens.C Tokens are of six types. 1) 2) 3) 4) 5) 6) Keywords (eg: int, while), Identifiers (eg: main, total), Constants (eg: 10, 20), Strings (eg: total, hello), Special symbols (eg: (), {}), Operators (eg: +, /,-,*)

C Tokens: Example Program:


1 int main() 2 { 3 int x, y, total; 4 x = 10, y = 20; 5 total = x + y; 6 Printf (Total = %d \n, total); 7 } where,
12

C Beginner

1. 2. 3. 4. 5.

main identifier {,}, (,) - delimiter int keyword x, y, total identifier main, {, }, (, ), int, x, y, total tokens

Identifiers:
Each program elements in a C program are given a name called identifiers. Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a name given to integer variable in above program. Rules for constructing identifier name: 1. 2. 3. 4. First character should be an alphabet or underscore. Succeeding characters might be digits or letter. Punctuations and special characters arent allowed except underscore. Identifiers should not be keywords.

Key words: Keywords are pre-defined words in a C compiler. Each keyword is meant to perform a specific function in a C program. Since keywords are referred names for compiler, they cant be used as variable name.

C language supports 32 keywords which are given below. auto break case char double else enum extern int long register return struct switch typedef union

13

C Beginner

const continue default do

float for goto if

short signed sizeof static

unsigned void volatile while

C Constant
C Constant are also like normal variables except their values can not be modified by the program once they are defined. They refer to fixed values. They are also called as literals They may be belonging to any of the data type. Please see below table for constants with respect to their data type. Types of C constant: 1. 2. 3. 4. 5. 6. Integer constants Real or Floating point constants Octal & Hexadecimal constants Character constants String constants Backslash character constants

S.n o

Constant type

data type

Example

14

C Beginner

int unsigned int 1 Integer constants long int long long int 53 , 762 , -478 , etc 5000u , 1000U , etc 1000L , -300L , etc 5555555LL

111.22F 2 Real or Floating point constants float, doule 111.22 -0.34565 3 Octal constant int 013 0 */ 090 0x */ A , B,

, ,

2.22e-2f 4.0 ,

/* starts with

4 5 6

Hexadecimal constant character constants string constants

int char char

/* starts with

ABCD , Hai

Rules for constructing C constant:

Integer Constants
1. 2. 3. 4. 5. 6. An integer constant must have at least one digit. It must not have a decimal point. It can either be positive or negative. No commas or blanks are allowed within an integer constant. If no sign precedes an integer constant, it is assumed to be positive. The allowable range for integer constants is -32768 to 32767

Real Constants
1. A real constant must have at least one digit 2. It must have a decimal point
15

C Beginner

3. It could be either positive or negative 4. If no sign precedes an integer constant, it is assumed to be positive. 5. No commas or blanks are allowed within a real constant.

character constants
1. A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas should point to left. 2. For example, C is a valid character constant whereas C is not. 3. The maximum length of a character constant is 1 character

Backslash Character Constants:


There are some characters which have special meaning in C language. They should be preceeded by back slash symbol to make use of special function of them. Given below is the list of special characters and their purpose. Charact er \b \f \n \r \t \ \ \\ \v \a \? Backspace Form feed New line Carriage return Horizontal tab Double quote Single quote Backslash Vertical tab Alert or bell Question mark Meaning

16

C Beginner

\N \XN

Octal constant (N is an octal constant) Hexadecimal constant (N hex.dcml cnst)

How to use constants in a C program?


We can define constants in a C program in the following ways. 1. By const keyword 2. By #define preprocessor directive

Example program using const keyword #include <stdio.h> void main() { const int height = 100; /*int constant*/ const float number = 3.14; /*Real constant*/ const char letter = 'A'; /*char constant*/ const char letter_sequence[10] = "ABC"; /*string constant*/ const char backslash_char = '\?'; /*special char cnst*/ printf("value printf("value printf("value printf("value printf("value } Output: value value value value value of of of of of height : 100 number : 3.140000 letter : A letter_sequence : ABC backslash_char : ? of of of of of height : %d \n", height ); number : %f \n", number ); letter : %c \n", letter ); letter_sequence : %s \n", letter_sequence); backslash_char : %c \n", backslash_char);

17

C Beginner

/* Note: When you try to change constant values after defined in C program, it will through error. */ 2. Example program using #define preprocessor directive: #include <stdio.h> #define #define #define #define #define height 100 number 3.14 letter 'A' letter_sequence "ABC" backslash_char '\?'

void main() { printf("value printf("value printf("value printf("value printf("value } Output: value value value value value of of of of of height : 100 number : 3.140000 letter : A letter_sequence : ABC backslash_char : ? of of of of of height : %d \n", height ); number : %f \n", number ); letter : %c \n", letter ); letter_sequence : %s \n", letter_sequence); backslash_char : %c \n", backslash_char);

18

C Beginner

C Variable
C variable is a named location in a memory where a program can manipulate the data. This location is used to hold the value of the variable. The value of the C variable may get change in the program. C variable might be belonging to any of the data type like int, float, char etc. Rules for naming C variable: 1. 2. 3. 4. 5. Variable name must begin with letter or underscore. Variables are case sensitive They can be constructed with digits, letters. No special symbols are allowed other than underscore. sum, height, _value are some examples for variable name

Declaring & initializing C variable:


Variables should be declared in the C program before to use. Memory space is not allocated for a variable while declaration. It happens only on variable definition.
19

C Beginner

Variable initialization means assigning a value to the variable. S.N o 1 Type Variable declaration Variable initialization Syntax data_type variable_name; data_type variable_name = value; Example

int x, y, z; char flat, ch;

int x = 50, y = 30; char flag = x, ch=l;

There are three types of variables in C program They are, 1. Local variable 2. Global variable 3. Environment variable Example program for local variable: The scope of local variables will be within the function only. These variables cant be accessed outside the function. #include <stdio.h> int main() { int m=40,n=20;

// m, n are local variables

if (m == n) { printf("m and n are equal"); } else { printf("m and n are not equal"); } }

20

C Beginner

Example program for global variable: The scope of global variables will be throughout the program. These variables can be accessed from anywhere in the program. #include <stdio.h> int n=20; int main() { int m=40;

// n is global variable // m is local variable

if (m == n) { printf("m and n are equal"); } else { printf("m and n are not equal"); } }

Do you know difference between variable declaration & definition? S.n o

Variable declaration

Variable definition

Declaration tells the compiler Definition allocates about data type and size of the memory for the variable. variable. It can happen only one Variable can be declared many time for a variable in a times in a program. program. The assignment of properties Assignments of storage and identification to a variable. space to a variable.

21

C Beginner

C Operators and Expressions


The symbols which are used to perform logical and mathematical operations are called C operators. These C operators join individual constants and variables to form expressions. Operators, functions, constants and variables are combined together to form expressions. Example : A + B * 5 where, +, * - operators A, B - variables 5 constant A + B * 5 - expression

22

C Beginner

Types of C operators: C language offers many types of operators. They are, 1. 2. 3. 4. 5. 6. 7. 8. Arithmetic operators Assignment operators Relational operators Logical operators Bit wise operators Conditional operators (ternary operators) Increment/decrement operators Special operators
1.

Arithmetic Operators:

These operators are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus. S.no 1 2 3 4 5 Operator + * / % Operation Addition Subtraction multiplication Division Modulus

Example program for C arithmetic operators: # include <stdio.h> int main() { int a=40,b=20, add,sub,mul,div,mod; add = a+b; sub = a-b; mul = a*b; div = a/b; mod = a%b;
23

C Beginner

printf("Addition of a, b is : %d\n", add); printf("Subtraction of a, b is : %d\n", sub); printf("Multiplication of a, b is : %d\n", mul); printf("Division of a, b is : %d\n", div); printf("Modulus of a, b is : %d\n", mod); }
2.

Assignment operators:

The values for the variables are assigned using assignment operators. For example, if the value 10 is to be assigned for the variable sum, it can be done like below. sum = 10; Below are some of other assignment operators :

Operator Simple operator Compound assignment operator

Example = sum = 10

Explanation Value 10 is assigned to variable sum This is same as sum = sum+10 This is same as sum = sum 10

+= sum+=10 -= sum = 10

*= sum*=10 This is same as sum = sum*10

24

C Beginner

/+ sum/=10

This is same as sum = sum/10

% This is same as sum = sum%=10 = sum%10 & = ^ = sum&=10 sum^=10 This is same as sum = sum&10 This is same as sum = sum^10

Example program for assignment operators: # include <stdio.h> int main() { int Total=0,i; for(i=0;i<10;i++) { Total+=i; // This is same as Total = Toatal+i } printf("Total = %d", Total); }

3.

Relational operators:

These operators are used to find the relation between two variables. That is, used to compare the value of two variables.

Operator > < >=

Example x>y x<y x >= y

25

C Beginner

<= == != Example program for relational operators: #include <stdio.h> int main() { int m=40,n=20; if (m == n) { printf("m and n are equal"); } else { printf("m and n are not equal"); } } 4. Logical operators:

x <= y x == y x != y

These operators are used to perform logical operations on the given two variables. Operator && || ! Example x && y x || y x (x || y), !(x && y)

Example program for logical operators: #include <stdio.h> int main() { int m=40,n=20; if (m>n && m !=0) { printf("m is greater than n and not equal to 0"); } }

26

C Beginner

5. Bit wise operators: These operators are used to perform bit operations on given two variables. Truth table for bitwise operation: x 0 0 1 1 y 0 1 0 1 x/y 0 1 1 1 x&y 0 0 0 1 x^y 0 1 1 0 Bitwise operators: Operator Explanation & | ~ ^ << >> Example program for bitwise operators: #include <stdio.h> int main() { int m=40,n=20,AND_opr,OR_opr,XOR_opr ; AND_opr = (m&n); OR_opr = (m|n); XOR_opr = (m^n); printf("AND_opr value = %d\n",AND_opr ); printf("XOR_opr value = %d\n",XOR_opr ); printf("OR_opr value = %d\n",OR_opr ); } Bitwise AND Bitwise OR Bitwise NOT XOR Left Shift Right Shift

27

C Beginner 6.

Conditional operators:
Conditional operators return one value if condition is true and returns other value is condition is false. This operator is also called as ternary operator.

Syntax : (Condition? true_value: false_value); Example : (A > 100 ? 0 : 1); Here, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional statements. Example program for conditional/ternary operators: #include <stdio.h> int main() { int x=1, y ; y = ( x ==1 ? 2 : 0 ) ; printf("x value is %d\n", x); printf("y value is %d", y); } 7. Increment and decrement operators:
These operators are used to either increase or decrease the value of the variable by one. Syntax : ++var_name; (or) var_name++; (or) - var_name; (or) var_name- -; Example : ++i, i++, - -i, i- -

Example program for increment operators: //Example for increment operators #include <stdio.h> int main() { int i=1; while(i<10) { printf("%d\n",i);
28

C Beginner

i++; } } Example program for decrement operators: //Example for decrement operators #include <stdio.h> int main() { int i=20; while(i>10) { printf("%d\n",i); i--; } } 8. Special Operators: Below are some of special operators that the C language offers. Below are some of special operators that the C language offers. S.n Operator o s 1 2 3 4 5 & * Size of () ternary Type cast Description This is used to get the address of the variable. Example: &a will give address of a. This is used as pointer to a variable. Example: * a where, * is pointer to the variable a. This gives the size of the variable. Example: size of (char) will give us 1. This is ternary operator and act exactly as if else statement. Type cast is the concept of modifying variable from one data type to other.

29

C Beginner

Do you know difference between pre/post increment and pre/post decrement operators? That means, i++ and ++i i and i.

Below table will explain you how these operators to be used in a C program. Below table will explain you how these operators to be used in a C program. S.n o 1 2 3 4 Operator while(i++ < 5) while(++i < 5) Description The value of i is compared with 5, before incrementing i value by 1. The value of i is incremented by 1, before comparing with 5.

while(i - < The value of i is compared with 5, before 5) decrementing i value by 1. while(- - i < The value of i is decremented by 1, before 5) comparing with 5.

Example program for pre increment operators: //Example for increment operators #include <stdio.h> int main() { int i=0; while(++i < 5 ) { printf("%d\n",i); } return 0; } Example program for post increment operators: #include <stdio.h> int main() { int i=0; while(i++ < 5 ) {
30

C Beginner

printf("%d\n",i); } return 0; } Example program for pre - decrement operators: #include <stdio.h> int main() { int i=10; while(--i > 5 ) { printf("%d\n",i); } return 0; } Example program for post - decrement operators: #include <stdio.h> int main() { int i=10; while(i-- > 5 ) { printf("%d\n",i); } return 0; }

31

C Beginner

C Decision Control statements


In decision control statements( C if else and nested if ), group of statements are executed when condition is true. If condition is false, then else part statements are executed. There are 3 types of decision making control statements in C language. They are, 1. if statements 2. if else statements 3. nested if statements S.no if statement ifelse statement

nested if if(condition1) { Statement1; } else if(condition2) { Statement2; } else Statement 3; If condition 1 is false, then condition 2 is checked and statements are executed if it is true. If condition 2 also gets failure, then
32

1.Syntax

if(condition) { Statements; }

if(condition) { Statement1; Statement2; } else { Statement3; Statement4; }

2.Descripti on

In these type of In these type of statements, if statements, group condition is of statements are true, then executed when respective block condition is true. of code is If condition is executed. false, then else part statements are executed.

C Beginner

else part is executed. Example program for if: In if control statement, respective block of code is executed when condition is true. int main() { int m=40,n=40; if (m == n) { printf("m and n are equal"); } } Example program for C if else: In C if else control statement, group of statements are executed when condition is true. If condition is false, then else part statements are executed. #include <stdio.h> int main() { int m=40,n=20; if (m == n) { printf("m and n are equal"); } else { printf("m and n are not equal"); } } Example program for C nested if: In nested if control statement, if condition 1 is false, then condition 2 is checked and statements are executed if it is true. If condition 2 also gets failure, then else part is executed.
33

C Beginner

#include <stdio.h> int main() { int m=40,n=20; if (m>n) { printf("m is greater than n"); } else if(m<n) { printf("m is less than n"); } else { printf("m is equal to n"); } }

C Loop control statements


These are used to perform looping operations until the given condition is true. Control comes out of the loop statements once condition becoming false. There are 3 types of loop statements in C language. They are, 1. for loop 2. while 3. do-while S.n o 1 Loop Name for Syntax for(expression1; expression2; expression3) { statements; } Description Where, expression1 variable initialization (Example: i=0, j=2, k=3) expression2 condition checking (Example: i>5, j<3, k=3) expression3 increment / decrement
34

C Beginner

(Example: ++i, j, + +k) while (condition) { statements; } where, condition might be a>5, i<10

while

do { do while statement; } while (condition);

where, condition might be a>5, i<10

Example program (for loop): In for loop control statement, loop is executed until condition becomes false . #include <stdio.h> int main() { int i; for(i=0;i<10;i++) { printf("%d\n",i); } } Example program (while loop): In while loop control statement, loop is executed until condition becomes false . #include <stdio.h> int main() { int i=3; while(i<10) { printf("%d\n",i);
35

C Beginner

i++; } } Example program (do while loop): In do..while loop control statement, while loop is executed irrespective of the condition for first time. Then 2nd time onwards, loop is executed until condition becomes false. #include <stdio.h> int main() { int i=1; printf("Condition is not checked for first time \n"); do { printf("Now, Condition is true and value is %d\n",i); i++; }while(i<10); } Do you know difference between while & do while loop? S.n o

while

do while

Loop is executed for first time Control goes into the irrespective of the condition. After while loop only when executing the while loop for first time, condition is true. condition is being checked.

36

C Beginner

C Case control statements

The statements which are used to execute only specific block of statements in a given series of block are called case control statements. There are 4 types of case statements in C language. They are, 1. 2. 3. 4. switch case break continue goto

1. switch case statement: This is used to execute only specific case statements based on the switch expression. Syntax : switch (expression) { case label1; statements; break; case label2; statements; break; default: statements; break; } Example program for switch..case: #include <stdio.h>
37

C Beginner

int main () { int value = 3; switch(value) { case 1: printf("Value break; case 2: printf("Value break; case 3: printf("Value break; case 4: printf("Value break; default : printf("Value } return 0; } 2. break statement: Break statement is used to terminate the while loops, switch case loops and for loops from the subsequent execution. Syntax: break; #include <stdio.h> int main() { int i; for(i=0;i<10;i++) { if(i==5) { printf("Coming out of for loop when i = 5"); break; }
38

is 1 \n" ); is 2 \n" ); is 3 \n" ); is 4 \n" ); is other than 1,2,3,4 \n" );

C Beginner

printf("%d\n",i); } } 3. Continue statement: Continue statement is used to continue the next iteration of for loop, while loop and dowhile loops. So, the remaining statements are skipped within the loop for that particular iteration. Syntax : continue; #include <stdio.h> int main() { int i; for(i=0;i<10;i++) { if(i==5 || i==6) { printf("Skipping %d from display using " \ "continue statement \n",i); continue; } printf("%d\n",i); } } 4. goto statements: goto statements is used to transfer the normal flow of a program to the specified label in the program. Syntax: { .

39

C Beginner

go to label; . . Label: Statements; } #include <stdio.h> int main() { int i; for(i=0;i<10;i++) { if(i==5) { printf(" We are using goto statement when i = 5 \n"); goto HAI; } printf("%d\n",i); } HAI : printf("Now, we are inside label name hai \n"); }

40

C Beginner

For vs While vs Do While For loop: When it is desired to do initialization, condition check and increment/decrement in a single statement of an iterative loop, it is recommended to use 'for' loop.

for(initialization;condition;increment/decrement) {/ /block of statements increment or decrement }

Program: Program to illustrate for loop #include<stdio.h> int main() { int i; for (i = 1; i <= 5; i++) { //print the number printf("\n %d", i); } return 0; } Output:
41

C Beginner

12345 Explanation: The loop repeats for 5 times and prints value of 'i' each time. 'i' increases by 1 for every cycle of loop. while loop: When it is not necessary to do initialization, condition check and increment/decrement in a single statement of an iterative loop, while loop could be used. In while loop statement, only condition statement is present. Syntax: #include<stdio.h> int main() { int i = 0, flag = 0; int a[10] = { 0, 1, 4, 6, 89, 54, 78, 25, 635, 500 }; //This loop is repeated until the condition is false. while (flag == 0) { if (a[i] == 54) { //as element is found, flag = 1,the loop terminates flag = 1; } else { i++; } } printf("Element found at %d th location", i); return 0; } Output: Element found at 5th location
42

C Beginner

Explanation: Here flag is initialized to zero. 'while' loop repeats until the value of flag is zero, increments i by 1. 'if' condition checks whether number 54 is found. If found, value of flag is set to 1 and 'while' loop terminates. IF vs Switch IF 1. Nested IF 1. Logical operator can use Multiple condition at a time Switch Not use switch as Nested In switch logical operator cant use Single condition is easy to understand and

Number of condition more then it bcm Switch complicated

implement

43

C Beginner

C Arrays C Arrays are a collection of variables belongings to the same data type. You can store group of data of same data type in an array. Example for C Arrays:
int a[10]; // integer array char b[10]; // character array i.e. string Types of C arrays:

There are 2 types of C arrays. They are, 1. Single dimensional array 2. Multi dimensional array ( Example : Two dimensional array ) 1. Single dimensional array: Syntax : data-type arr_name[array_size]; Array might be belonging to any of the data type Array size must be a constant value. S.n Array declaration Array initialization Accessing array o Syntax: 1 data_type array_name [array_size]; data_type array_name [array_size]= (value 1, value 2, value 3, .);

array_name[index];

age[0]; // 0 is accessed 2 int age [5]; int age[5] = {0, 1, 2, age[1]; // 1 is 3, 4, 5}; accessed age[2]; // 2 is accessed char name[10] = {S, u, r, e, n}; (or) name [0] = S; name[0]; accessed name[1]; accessed //S is //u is

char name [10];

44

C Beginner

name name name name

[1] [2] [3] [4]

= = = =

u; r; e; n;

Example program for one/single dimension C array: #include<stdio.h> int main() { int i; int arr[5] = {10,20,30,40,50}; // declaring and Initializing array for (i=0;i<5;i++) { // Accessing each variable printf("value of arr[%d] is %d \n", i, arr[i]); } } Example program Another way of initializing C array: In single dimension array, array elements can be initialized in the below format also. #include<stdio.h> int main() { int i, arr[5]; // declaring array arr[0] = 10; // Initializing array arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; for (i=0;i<5;i++) { // Accessing each variable printf("value of arr[%d] is %d\n",i,arr[i]); } } 2. Two dimensional array: It is nothing but array of array. syntax : data_type array_name[num_of_rows][num_of_column]
45

C Beginner

Array might be belonging to any of the data type Array size must be a constant value.

S. no

Array declaration Syntax:

Array initialization

Accessing array

data_type array_name[num_of_rows] [num_of_column];

data_type array_name [num_of_rows] [num_of_columns]={{1,2}, {3,4}}}

array_name[i ndex];

arr [0] [0] = 1; arr [0] ]1] = 2; int arr[2][2] = {{1,2}, {3, 4}}; arr [1][0] = 3; arr [1] [1] = 4; Example program for two/multi dimension C array: #include<stdio.h> int main() { int i,j; // declaring and Initializing array int arr[2][2] = {10,20,30,40}; for (i=0;i<2;i++) { for (j=0;j<2;j++) { // Accessing variables printf("value of arr[%d][%d] is %d\n",i,j,arr[i][j]);
46

Example: int arr[2][2];

C Beginner

} } }

Example program Another way of initializing C array: In multi dimension array, array elements can be initialized in the below format also. #include<stdio.h> int main() { int i,j; int arr[2][2]; arr[0][0] arr[0][1] arr[1][0] arr[1][1] = = = =

// declaring array

10; // Initializing array 20; 30; 40;

for (i=0;i<2;i++) { for (j=0;j<2;j++) { // Accessing each variable printf("value of arr[%d][%d] is %d\n",i,j,arr[i][j]); } } }

C Strings
C String is nothing but array of characters ended with null character (\0). This null character means the end of the string. Example for C string: char string[6] = { c , c , l , a , s , a, \0}; (or) char string[6] = cclass; (or) char string [] = cclass;

47

C Beginner

Difference between above syntax is, when we declare char as string[20], 20 bytes of memory space is allocated by the programmer for holding the string value. When we declare char as string[], any number of required space will be allocated during execution of the program. Example program for C string: #include <stdio.h> int main () { char string[6] = "cclass.com"; printf("The string is : %s \n", string ); return 0; } C String functions: string.h header file supports all the string functions in C language. All the string functions are given below. Click on each function name to display an example program.

S.n o 1

Array declaration strcat (str1, str2) strcpy (str1, str 2) strlen (strl)

Array initialization

Concatenates str2 at the end of str1.

2 3 4

Copies str2 into str1 gives the length of str1.

strcmp (str1, Returns 0 if str1 is same as str2. Returns <0 str2) if strl < str2. Returns >0 if str1 > str2. strchr (str1, Returns pointer to first occurrence of char in char) str1. strstr (str1, Returns pointer to first occurrence of str2 in
48

5 6

C Beginner

str2) strcmpi (str1, str2) strdup() strlwr() strncat() strncpy()

str1. Same as strcmp() function. But, this function negotiates case. A and a are treated as same. duplicates the string converts string to lowercase appends a portion of string to another copies given number of characters of one string to another last occurrence of given character in a string is found reverses the given string sets all character in a string to given character converts string to uppercase tokenizing given string using delimiter

8 9 10 11

12 13 14 15 16

strrchr() strrev() strset() strupr() strtok()

Example program for strlen: It counts number of characters available in a string. #include <stdio.h> #include <string.h> int main( ) { int len1, len2 ; char array1[6]="cclass.com" ; char array2[6]="cclass.com value assigned " \ "at run time";
49

C Beginner

len1 = strlen(array1) ; len2 = strlen(array2) ; printf ( "\nFirst string length = %d \n" , len1 ) ; printf ( "\nSecond string length = %d \n" , len2 ) ; return 0; } Example program for strcpy: #include <stdio.h> #include <string.h> int main( ) { char source[ ] = "cclass" ; char target[6] ; strcpy ( target, source ) ; printf ( "\nContetnt of source string = %s", source ) ; printf ( "\nContetnt of target string = %s", target ) ; } Example program for strcat: It cocatenates two given strings. #include <stdio.h> #include <string.h> int main( ) { char source[ ] = " cclass" ; char target[6]= " C Tutorial" ; strcat ( target, source ) ; printf ( "\nContetnt of source string = %s", source ) ; printf ( "\nContetnt of target string = %s", target ) ; } Example program for strcmp:
It compares two strings and returns 0 if they are same. If string1< string2, it returns < 0 value. If string1> string2, it returns > 0 value. It copies contents of one string to another

#include <stdio.h> #include <string.h> int main( ) { char str1[ ] = "fresh" ;


50

C Beginner

char str2[ ] = "refresh" ; int i, j, k ; i = strcmp ( str1, "fresh" ) ; j = strcmp ( str1, str2 ) ; k = strcmp ( str1, "f" ) ; printf ( "\n%d %d %d", i, j, k ) ; }

Printing Strings: Using Character pointer: char *name = Learn C; printf(name); printf(%s, name); printf(%s,&name[0]); Using Character Array: char name[]=Learn C; printf(name); printf(%s, name); printf(%s,& name[0]); printf function can be used to print a string. Similarly, puts function can be used to print a string as shown below. char name[]=Learn C; puts(name); Accepting String as input: We can use scanf or gets to accepts string from the user. Using scanf: scanf(%s,name); The above statement passes the base address implicitly. scanf(%s,&name[0]); In the above statement, we are passing the address of the first element. Using gets: 51

C Beginner gets(name); gets(&name[0]); Note: Although scanf and gets seems to be the same, there is a big difference between them. Lets understand this difference.

Program using scanf: char *str; printf(Enter the string: ); scanf(%s,str); printf(\n%s,str); Output: Enter the string: Learn C at ITEskul Learn Program using gets: char *str; printf(Enter the string: ); gets(str); printf(\n%s,str);

Output: Enter the string: Learn C at ITEskul Learn C at ITEskul When a string is accepted using scanf function, if a space is encountered then it will treat it as null character(\0). In the above example, a space encountered after Learn is treated as null character. Hence while printing, only Learn is printed. This problem can be resolved using gets function.

52

C Beginner

Understanding 2D-Array Step by Step We can define 2-dimensional array as follows. int A[3][3]={11,12,13,14,15,16,17,18,19} Element Element Element Element Element 11 12 13 14 15 can can can can can be be be be be referred referred referred referred referred as as as as as A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] and so on.

Another way to define 2-D array is: int A[3][3]={ {11,12,13}, {14,15,16}, {17,18,19} } The above mentioned method increases the readability of the matrix.

Note:
int A[][] and A[3][] are invalid. We cannot skip the column index in 2-D arrays. int A[][3] and A[3][3] are both valid. Program that accept values in 2-Dimensional 3 by 3 array and displays the sum of all the elements. void main(){

53

C Beginner

int arr[3][3], i, j, sum=0; /*Accepts input from the user and stores it in 2-D array*/ for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf(\nEnter the value for A[%d][%d]: ,i,j); scanf(%d,&arr[i][j]); } }

/*Calculate sum of elements in 2-D array*/ for(i=0;i<3;i++){ for(j=0;j<3;j++){ sum=sum+arr[i][j]; } } /*Display the value of sum*/ printf(\nThe sum of the elements of 2-D array is %d, sum); } Output: Enter the value for A[0][0]: 1 Enter the value for A[0][1]: 2 Enter the value for A[0][2]: 3 Enter the value for A[1][0]: 4 Enter the value for A[1][1]: 5 Enter the value for A[1][2]: 6 Enter the value for A[2][0]: 7
54

C Beginner

Enter the value for A[2][1]: 8 Enter the value for A[2][2]: 9 The sum of the elements of 2-D array is 45 Explanation: There are two for loops. The first one accepts input from the user and stores it The second one Calculates the sum of the elements present in 2D array. for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf(\nEnter the value for A[%d][%d]: ,i,j); scanf(%d,&arr[i][j]); } }

Let us understand the above for loop iteration wise.


1st Iteration of Outer for loop: Value of i=0. Condition i<3 is satisfied. Hence it enters this for loop. 1st Iteration of Inner for loop: Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop. Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][0]. 2nd Iteration of Inner for loop: Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][1].
55

C Beginner

3rd Iteration of Inner for loop: Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[0][2]. Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied. Hence it exits this inner for loop. 2nd Iteration of Outer for loop: Value of i=1. Condition i<3 is satisfied. Hence it enters this for loop. 1st Iteration of Inner for loop: Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop. Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][0]. 2nd Iteration of Inner for loop: Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop. Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][1]. 3rd Iteration of Inner for loop: Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop.Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[1][2]. Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied. Hence it exits this inner for loop. 3rd Iteration of Outer for loop: Value of i=2. Condition i<3 is satisfied. Hence it enters this for loop. 1st Iteration of Inner for loop: Value of j=0. Condition j<3 is satisfied. Hence it enters this for loop. Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][0]. 2nd Iteration of Inner for loop: Value of j is incremented. Hence j=1. Condition j<3 is satisfied. Hence it enters this for loop.

56

C Beginner

Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][1]. 3rd Iteration of Inner for loop: Value of j is incremented. Hence j=2. Condition j<3 is satisfied. Hence it enters this for loop. Here the value entered by the user is assigned to the variable arr[i][j] i.e. arr[2][2]. Now the value of j is again incremented. Hence j=3. But, the condition j<3 is not satisfied. Hence it exits this inner for loop. Now the value of i is again incremented. Hence i=3. But, the condition i<3 is not satisfied. Hence it exits this outer for loop. NOTE:Similar logic applies while calculating the addition of the array elements.

-:Scope of Variables:A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable can not be accessed. There are three places where variables can be declared in C programming language: 1. Inside a function or a block which is called local variables, 2. Outside of all functions which is called global variables. 3. In the definition of function parameters which is called formal parameters. Let us explain what are local and global variables and formal parameters.

Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables. Here all the variables a, b and c are local to main() function. #include <stdio.h> int main () { /* local variable declaration */ int a, b;
57

C Beginner

int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0; }

Global Variables
Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:

#include <stdio.h> /* global variable declaration */ int g; int main () { /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0; }

58

C Beginner

A program can have same name for local and global variables but value of local variable inside a function will take preference. Following is an example: #include <stdio.h> /* global variable declaration */ int g = 20; int main () { /* local variable declaration */ int g = 10; printf ("value of g = %d\n", g); return 0; } When the above code is compiled and executed, it produces following result: value of g = 10

Formal Parameters
A function parameters, formal parameters, are treated as local variables with-in that function and they will take preference over the global variables. Following is an example: #include <stdio.h> /* global variable declaration */ int a = 20; int main () { /* local variable declaration in main function */ int a = 10; int b = 20; int c = 0; printf ("value of a in main() = %d\n", a); c = sum( a, b); printf ("value of c in main() = %d\n", c); return 0;
59

C Beginner

} /* function to add two integers */ int sum(int a, int b) { printf ("value of a in sum() = %d\n", a); printf ("value of b in sum() = %d\n", b); return a + b; } When the above code is compiled and executed, it produces following result: value of a in main() = 10 value of a in sum() = 10 value of b in sum() = 20 value of c in main() = 30

Initializing Local and Global Variables


When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows:
DataType int char float double pointer Initial DefaultValue 0 '\0' 0 0 NULL

It is a good programming practice to initialize variables properly otherwise, your program may produce unexpected results because uninitialized variables will take some garbage value already available at its memory location.

60

C Beginner

C Pointer
C Pointer is used to allocate memory dynamically i.e. at run time.C Pointer is a variable that stores the address of another variable The variable might be any of the data type such as int, float, char, double, short etc. Syntax : data_type *var_name; Example : int *p; char *p; Where * is used to denote that p is pointer variable and not a normal variable. Normal variable stores the value whereas pointer variable stores the address of the variable. The content of the C pointer always be a whole number i.e. address.
61

C Beginner

Always C pointer is initialized to null, i.e. int *p = null. The value of null pointer is 0. & symbol is used to get the address of the variable. * symbol is used to get the value of the variable that a pointer is pointing to. If pointer is assigned to NULL, it means it is pointing to nothing. Two pointers can be subtracted to know how many elements are available between these two pointers. But, Pointer addition, multiplication, division are not allowed. The size of any pointer is 2 byte (for 16 bit compiler).

Example program for C pointer: #include <stdio.h> int main() { int *ptr, q; q = 50; /* address of q is assigned to ptr */ ptr = &q; /* display q's value using ptr variable */ printf("%d", *ptr); return 0; }

C Function
A large C program is divided into basic building blocks called C function. C function contains set of instructions enclosed by { } which performs specific operation in a C program. C Functions can be invoked from anywhere within a C program. main() function is the function from where every C program is started to execute. Name of the function is unique in a C program.

62

C Beginner

Structure of a C function: data_type function_name (parameters) { Body of function; } Example for C function: int add (int a , int b) { int sum; sum = a+b; return sum; } Where,

Before calling and defining a function, we have to declare function prototype in order to inform the compiler about the function name, function parameters and return value type.

Defining a Function:
The general form of a function definition in C programming language is as follows: return_type function_name( parameter list ) { body of the function }
63

C Beginner

A function definition in C programming language consists of a function header and a function body. Here are all the parts of a function: Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body: The function body contains a collection of statements that define what the function does. Example program for C function: #include<stdio.h> // function prototype, also called function declaration float square ( float x ); // main function, program starts from here int main( ) { float m, n ; printf ( "\nEnter some number for finding square \n"); scanf ( "%f", &m ) ; // function call n = square ( m ) ; printf ( "\nSquare of the given number %f is %f",m,n ); }

64

C Beginner

float square ( float x ) // function definition { float p ; p=x*x; return ( p ) ; } How to call a C function? While calling a function, there are two ways that arguments can be passed to a function: Call Type Call by value Description This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

Call by reference

By default, C uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.

1. Call by value: Arguments are passed by value while calling a function in C program. Example program for C function (using call by value): #include<stdio.h> // function prototype, also called function declaration
65

C Beginner

void swap(int a, int b); int main() { int m = 22, n = 44; // calling swap function by value printf(" values before swap m = %d \nand n = %d", m, n); swap(m, n); } void swap(int a, int b) { int tmp; tmp = a; a = b; b = tmp; printf(" \nvalues after swap m = %d\n and n = %d", a, b); } 2. Call by reference: Arguments are passed by address while calling a function in C program. Example program for C function (using call by reference): #include<stdio.h> // function prototype, also called function declaration void swap(int *a, int *b); int main() { int m = 22, n = 44; // calling swap function by reference printf("values before swap m = %d \n and n = %d",m,n); swap(&m, &n); }
66

C Beginner

void swap(int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; printf("\n values after swap a = %d \nand b = %d", *a, *b); } Output: values before swap m = 22 and n = 44 values after swap a = 44 and b = 22 Do you know how many values can be return from a function at a time? Only one value can be returned. If you want to return more than one values, pointers can be used.

Functions from the C Standard Library


While the C language doesn't itself contain functions, it is usually linked with the C Standard Library. To use this library, you need to add an #include directive at the top of the C file, which may be one of the following:
<assert.h> <ctype.h> <errno.h> <float.h> <limits.h> <locale.h> <math.h> <signal.h> <stdarg.h> <stddef.h> <stdio.h> <complex.h> <stdlib.h> <string.h>

<setjmp.h>

67

C Beginner The functions available are:


<assert.h> <limits.h> <signal.h> <stdlib.h>

atof(char*), atoi(char*), atol(char*)

strtod(char * str, char ** endptr ), strtol(char *str, char **endptr), strtoul(char *str, char **endptr)

(constants only) int raise(int sig). This assert(int) void* signal(int sig, void (*func) (int))

rand(), srand() malloc(size_t), calloc (size_t elements, size_t elementSize), realloc(void*, int) free (void*) exit(int), abort() atexit(void (*func)()) getenv system qsort(void *, size_t number, size_t size, int (*sortfunc)(void*, void*))


<ctype.h> <locale.h> <stdarg.h>

abs, labs div, ldiv


<string.h>

68

C Beginner

isalnum, isalpha, isblank iscntrl, isdigit, isgraph islower, isprint, ispunct isspace, isupper, isxdigit tolower, toupper struct lconv* localeconv(voi d); char* setlocale(int, const char*); va_start (va_list, ap) va_arg (ap, (type)) va_end (ap) va_copy (va_list, va_list) errno.h (errno) math.h sin, cos, tan asin, acos, atan, atan2 sinh, cosh, tanh ceil exp stddef.h offsetof macro

memcpy, memmove memchr, memcmp, memset

strcat, strncat, strchr, strrchr strcmp, strncmp, strccoll strcpy, strncpy strerror strlen strspn, strcspn strpbrk strstr strtok strxfrm time.h asctime (struct tm* tmptr) clock_t clock() char* ctime(const time_t* timer) double difftime(time_t timer2, time_t timer1) 69

C Beginner struct tm* gmtime(const time_t* timer) fabs floor fmod frexp ldexp log, log10 modf pow sqrt struct tm* gmtime_r(const time_t* timer, struct tm* result) struct tm* localtime(const time_t* timer) time_t mktime(struct tm* ptm) time_t time(time_t* timer) char * strptime(const char* buf, const char* format, struct tm* tptr) fclose fopen, freopen remove rename rewind tmpfile time_t timegm(struct tm *brokentime) float.h (constants) setjmp.h int setjmp(jmp_buf env) void longjmp(jmp_b uf env, int value) stdio.h fread, fwrite getc, putc getchar, putchar, fputchar gets, puts printf, vprintf fprintf, vfprintf

70

C Beginner clearerr feof, ferror fflush fgetpos, fsetpos fgetc, fputc fgets, fputs ftell, fseek ungetc tmpnam setbuf, setvbuf sprintf, snprintf, vsprintf, vsnprintf perror scanf, vscanf fscanf, vfscanf sscanf, vsscanf

Static Functions If a function is to be called only from within the file in which it is declared, it is appropriate to declare it as a static function. When a function is declared static, the compiler will now compile to an object file in a way that prevents the function from being called from code in other files. Example:
static int compare( int a, int b ) { return (a+4 < b)? a : b; }

Recursion Here's a simple function that does an infinite loop. It prints a line and calls itself, which again prints a line and calls itself again, and this continues until the stack overflows and the program crashes. A function calling itself is called recursion, and normally you will have a conditional that would stop the recursion after a small, finite number of steps.
// don't run this! void infinite_recursion() { printf("Infinite loop!\n"); infinite_recursion(); }
71

C Beginner

A simple check can be done like this. Note that ++depth is used so the increment will take place before the value is passed into the function. Alternatively you can increment on a separate line before the recursion call. If you say print_me(3,0); the function will print the line Recursion 3 times. void print_me(int j, int depth) { if(depth < j) { printf("Recursion! depth = %d j = %d\n",depth,j); //j keeps its value print_me(j, ++depth); } } Recursion is most often used for jobs such as directory tree scans, seeking for the end of a linked list, parsing a tree structure in a database and factorising numbers (and finding primes) among other things.

Call by Value
If data is passed by value, the data is copied from the variable used in for example main() to a variable used by the function. So if the data passed (that is stored in the function variable) is modified inside the function, the value is only changed in the variable used inside the function. Lets take a look at a call by value example: #include <stdio.h> void call_by_value(int x) { printf("Inside call_by_value x = %d before adding 10.\n", x); x += 10; printf("Inside call_by_value x = %d after adding 10.\n", x); } int main() { int a=10; printf("a = %d before function call_by_value.\n", a); call_by_value(a); printf("a = %d after function call_by_value.\n", a); return 0; } The output of this call by value code example will look like this: a = 10 before function call_by_value.

72

C Beginner
Inside call_by_value x = 10 before adding 10. Inside call_by_value x = 20 after adding 10. a = 10 after function call_by_value. Ok, lets take a look at what is happening in this call-by-value source code example. In the main() we create a integer that has the value of 10. We print some information at every stage, beginning by printing our variable a. Then function call_by_value is called and we input the variable a. This variable (a) is then copied to the function variable x. In the function we add 10 to x (and also call some print statements). Then when the next statement is called in main() the value of variable a is printed. We can see that the value of variable a isnt changed by the call of the function call_by_value().

Call by Reference
If data is passed by reference, a pointer to the data is copied instead of the actual variable as is done in a call by value. Because a pointer is copied, if the value at that pointers address is changed in the function, the value is also changed in main(). Lets take a look at a code example: #include <stdio.h> void call_by_reference(int *y) { printf("Inside call_by_reference y = %d before adding 10.\n", *y); (*y) += 10; printf("Inside call_by_reference y = %d after adding 10.\n", *y); } int main() { int b=10; printf("b = %d before function call_by_reference.\n", b); call_by_reference(&b); printf("b = %d after function call_by_reference.\n", b); return 0; } The output of this call by reference source code example will look like this: b = 10 Inside Inside b = 20 before function call_by_reference. call_by_reference y = 10 before adding 10. call_by_reference y = 20 after adding 10. after function call_by_reference.

Lets explain what is happening in this source code example. We start with an integer b that has the value 10. The function call_by_reference() is called and the address of the variable b is passed to this function. Inside the function there is some before and after print statement done and there is 10 added to the value at the memory pointed by y.

73

C Beginner
Therefore at the end of the function the value is 20. Then in main() we again print the variable b and as you can see the value is changed (as expected) to 20.

When to Use Call by Value and When to use Call by Reference?


One advantage of the call by reference method is that it is using pointers, so there is no doubling of the memory used by the variables (as with the copy of the call by value method). This is of course great, lowering the memory footprint is always a good thing. So why dont we just make all the parameters call by reference? There are two reasons why this is not a good idea and that you (the programmer) need to choose between call by value and call by reference. The reason are: side effects and privacy. Unwanted side effects are usually caused by inadvertently changes that are made to a call by reference parameter. Also in most cases you want the data to be private and that someone calling a function only be able to change if you want it. So it is better to use a call by value by default and only use call by reference if data changes are expected. That is all for this C tutorial, where you (hopefully) have learned the difference between call-by-value and call-by-reference.

C Structure
C Structure is a collection of different data types which are grouped together and each element in a structure is called member.
If you want to access structure members, structure variable should be declared. Below table will help you how to form a C structure, declare a structure, initializing and accessing the members of the structure. S.n o Type syntax initializin declaring g example structure structure variable variable struct student { struct student report; struct student report = {100, Mani, accessing structure members report.mark report.name

Using struct normal tag_name variable {

74

C Beginner data type var_name1; int mark; data type char var_name2; name[10]; float data type average; var_name3; }; }; report.averag e

99.5};

struct tag_name {

struct student

struct report student rep mark = {100, Mani, 99.5};

{ data type struct Using var_name1; int mark; student pointer *report, variable data type char var_name2; name[10]; rep; float data type average; var_name3; }; };

report name report = &rep; report average

Example program for C structure:


#include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; }; int main() { struct student record;
75

C Beginner

record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); return 0; }

Example program Another way of declaring C structure:


#include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; } record; int main() { record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); return 0; }

76

C Beginner

More programs on C Structure:


Structure using typedef Passing structures to function (by value) Passing structures to function (by address)

Example program Structure using typedef:


// Structure using typedef: #include <stdio.h> #include <string.h> typedef struct student { int id; char name[20]; float percentage; } status; int main() { status record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); return 0; }

77

C Beginner

Example program passing structures to function (by value)


#include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; }; void func(struct student record); int main() { struct student record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; func(record); return 0; } void func(struct student record) { printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); }

Example program Passing structures to function (by address)


#include <stdio.h> #include <string.h>
78

C Beginner

struct student { int id; char name[20]; float percentage; }; void func(struct student *record); int main() { struct student record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; func(&record); return 0; } void func(struct student *record) { printf(" Id is: %d \n", record->id); printf(" Name is: %s \n", record->name); printf(" Percentage is: %f \n", record->percentage); }

UNION
A union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.

79

C Beginner

Defining a Union
To define a union, you must use the union statement in very similar was as you did while defining structure. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows: union [union tag] { member definition; member definition; ... member definition; } [one or more union variables]; The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str: union Data { int i; float f; char str[20]; } data; Now a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable ie. same memory location can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement. The memory occupied by a union will be large enough to hold the largest member of the union. For example, in above example Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string. Following is the example which will display total memory size occupied by the above union: #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data;

80

C Beginner
printf( "Memory size occupied by data : %d\n", sizeof(data)); return 0; } When the above code is compiled and executed, it produces following result: Memory size occupied by data : 20

Accessing Union Members


To access any member of a union, we use the memberaccessoperator(.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type. Following is the example to explain usage of union: #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "data.str : %s\n", data.str); } return 0;

81

C Beginner
When the above code is compiled and executed, it produces following result:

data.i : 1917853763 data.f : 4122360580327794860452759994368.000000 data.str : C Programming Here we can see that values of i and f members of union got corrupted because final value assigned to the variable has occupied the memory location and this is the reason that the value if str member is getting printed very well. Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having union: #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; printf( "data.i : %d\n", data.i); data.f = 220.5; printf( "data.f : %f\n", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %s\n", data.str); return 0; } When the above code is compiled and executed, it produces following result: data.i : 10 data.f : 220.500000 data.str : C Programming

Typedef
82

C Beginner
The C programming language provides a keyword called typedef which you can use to give a type a new name. Following is an example to define a term BYTEfor one-byte numbers: typedef unsigned char BYTE; After this type definitions, the identifier BYTE can be used as an abbreviation for the type unsignedchar, for example: . BYTE b1, b2;

By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows: typedef unsigned char byte; You can use typedef to give a name to user defined data type as well. For example you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows: #include <stdio.h> #include <string.h> typedef struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } Book; int main( ) { Book book; strcpy( book.title, "C Programming"); strcpy( book.author, "Nuha Ali"); strcpy( book.subject, "C Programming Tutorial"); book.book_id = 6495407; printf( printf( printf( printf( } "Book "Book "Book "Book title : %s\n", book.title); author : %s\n", book.author); subject : %s\n", book.subject); book_id : %d\n", book.book_id);

return 0;

When the above code is compiled and executed, it produces following result: Book Book title : C Programming author : Nuha Ali

83

C Beginner
Book Book subject : C Programming Tutorial book_id : 6495407

typedef vs #define
The #define is a C-directive which is also used to define the aliases for various data types similar totypedef but with three differences: The typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as well, like you can define 1 as ONE etc. The typedef interpretation is performed by the compiler where as #define statements are processed by the pre-processor. Following is a simplest usage of #define: #include <stdio.h> #define TRUE 1 #define FALSE 0 int main( ) { printf( "Value of TRUE : %d\n", TRUE); printf( "Value of FALSE : %d\n", FALSE); return 0; } When the above code is compiled and executed, it produces following result: Value of TRUE : 1 Value of FALSE : 0

84

C Beginner

File I/O
Last chapter explained about standard input and output devices handled by C programming language. This chapter we will see how C programmers can create, open, close text or binary files for their data storage. A file represents a sequence of bytes, does not matter if it is a text file or binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. This chapter will take you through important calls for the file management. Opening Files You can use the fopen( ) function to create a new file or to open an existing file, this call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Following is the prototype of this function call: FILE *fopen( const char * filename, const char * mode ); Here filename is string literal which you will use to name your file and access mode can have one of the following values: Mode Description r w Opens an existing text file for reading purpose. Opens a text file for writing, if it does not exist then a new file is created. Here your program will start writing content from the beginning of the file. Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here your program will start appending content in the existing file content. Opens a text file for reading and writing both. Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist. Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.

a r+ w+

a+

If you are going to handle binary files then you will use below mentioned access modes instead of the above mentioned:

85

C Beginner "rb", "wb", "ab", "ab+", "a+b", "wb+", "w+b", "ab+", "a+b" Closing a File To close a file, use the fclose( ) function. The prototype of this function is: int fclose( FILE *fp ); The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This function actually, flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h. There are various functions provide by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see few of the in the next section. Writing a File Following is the simplest function to write individual characters to a stream: int fputc( int c, FILE *fp ); The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream: int fputs( const char *s, FILE *fp ); The function fputs() writes the string s to the output stream referenced by fp. It returns a nonnegative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. Try the following example: #include <stdio.h> main() { FILE *fp; fp = fopen("/tmp/test.txt", "w+"); fprintf(fp, "This is testing for fprintf...\n"); fputs("This is testing for fputs...\n", fp); fclose(fp); } When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in next section. Reading a File Following is the simplest function to read a single character from a file: 86

C Beginner int fgetc( FILE * fp ); The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error it returns EOF. The following functions allow you to read a string from a stream: char *fgets( char *buf, int n, FILE *fp ); The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string. If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it stops reading after the first space character encounters. #include <stdio.h> main() { FILE *fp; char buff[255]; fp = fopen("/tmp/test.txt", "r"); fscanf(fp, "%s", buff); printf("1 : %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("2: %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("3: %s\n", buff ); fclose(fp); } When the above code is compiled and executed, it reads the file created in previous section and produces following result: 1 : This 2: is testing for fprintf... 3: This is testing for fputs...

87

C Beginner Let's see a little more detail about what happened here. First fscanf() method read just This because after that it encountered a space, second call is for fgets() which read the remaining line till it encountered end of line. Finally last call fgets() read second line completely. Binary I/O Functions There are following two functions which can be used for binary input and output: size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); Both of these functions should be used to read or write blocks of memories - usually arrays or structures.

88

C Beginner

Recursion
Recursion is the process of repeating items in a self-similar way. Same applies in programming languages as well where if a programming allows you to call a function inside the same function that is called recursive call of the function as follows. void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); } The C programming language supports recursion ie. a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go in infinite loop. Recursive function are very useful to solve many mathematical problems like to calculate factorial of a number, generating fibonacci series etc. Number Factorial Following is an example which calculate factorial for a given number using a recursive function: #include <stdio.h> int factorial(unsigned int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); } int main() { int i = 15; printf("Factorial of %d is %d\n", i, factorial(i)); return 0; } When the above code is compiled and executed, it produces the following result: Factorial of 15 is 2004310016

89

C Beginner

Fibonacci Series Following is another example which generates fibonacci series for a given number using a recursive function: #include <stdio.h> int fibonaci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonaci(i-1) + fibonaci(i-2); } int main() { int i; for (i = 0; i < 10; i++) { printf("%d\t%n", fibonaci(i)); } return 0; } When the above code is compiled and executed, it produces the following result:

90

C Beginner

Command line arguments


It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program specially when you want to control your program from outside instead of hard coding those values inside the code. The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly: #include <stdio.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } } When the above code is compiled and executed with a single argument, it produces the following result. $./a.out testing The argument supplied is testing When the above code is compiled and executed with a two arguments, it produces the following result. $./a.out testing1 testing2 Too many arguments supplied. When the above code is compiled and executed without passing any argument, it produces the following result. $./a.out One argument expected It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, otherwise and if you pass one argument then argc is set at 2. 91

C Beginner You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where we will print program name and we also pass a command line argument by putting inside double quotes: #include <stdio.h> int main( int argc, char *argv[] ) { printf("Program name %s\n", argv[0]); if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } } When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following result. $./a.out "testing1 testing2" Progranm name ./a.out The argument supplied is testing1 testing2

92

S-ar putea să vă placă și