142
- ABHISHEK DWIVEDI LEARNING 5 September 2015 ABHISHEK DWIVEDI

Learning c - An extensive guide to learn the C Language

Embed Size (px)

Citation preview

Page 1: Learning c - An extensive guide to learn the C Language

- ABHISHEK DWIVEDI

LEARNING

5 September 2015 ABHISHEK DWIVEDI

Page 2: Learning c - An extensive guide to learn the C Language

5 September 2015 ABHISHEK DWIVEDI

WHICH TOPIC U WANNA STUDY ???

INTRODUCTION

CONSTANTS & VARIABLES

OPERATORS & EXPRESSIONS

STRUCTURE OF A C PROGRAM

CONTROL STRUCTURES

ARRAYS AND STRINGS

FUNCTIONS

STORAGE CLASSES

STRUCTURES & UNIONS

POINTERS

DYNAMIC MEMORY ALLOCATION

FILE MANAGEMENT IN C

COMMAND LINE ARGUMENTS

Page 3: Learning c - An extensive guide to learn the C Language

¾ C is a programming language developed at AT & T Bell Laboratories of USA in 1972, designed and written by Dennis Ritchie .

¾ C is highly portable i.e., software written for one computer can be run on another computer.

¾ An important feature of C is its ability to extend itself. A C program is basically a collection of functions.

Introducing C

5 September 2015 ABHISHEK DWIVEDI

Page 4: Learning c - An extensive guide to learn the C Language

ALGOL Æ Algorithmic Language CPL Æ Combined Programming Language BCPL Æ Basic Combined Programming Language

Historical Development of C

5 September 2015 ABHISHEK DWIVEDI

Page 5: Learning c - An extensive guide to learn the C Language

¾ A token is an atomic unit (smallest indivisible units) in a program. ¾ The most basic elements in a C program recognized by the compiler are a single character or a group of characters called C tokens. ¾ The compiler cannot breakdown the token any further. For example, the words main, { brace , (parenthesis) are all tokens of C program.

C Tokens

5 September 2015 ABHISHEK DWIVEDI

Page 6: Learning c - An extensive guide to learn the C Language

1. Keywords Examples: float, int, double, while, for. 2. Identifiers Examples: main, amount 3. Constants Examples: 12.4, 7894 4. Strings Examples: CSM , Thursday 5. Special Symbols Examples: [,], {, }, (, ) 6. Operators Examples: +, *, /

Types of tokens.

5 September 2015 ABHISHEK DWIVEDI

Page 7: Learning c - An extensive guide to learn the C Language

The C character set includes the upper case letters A to Z, the lower case a to z, the decimal digits 0 to 9 and certain special characters.

Letters a, b, c, ……………z

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

Special characters ~ , . ; : ? ! [ ] { } / \ < > = + - $ # @ & * % ^

The C character set

5 September 2015 ABHISHEK DWIVEDI

Page 8: Learning c - An extensive guide to learn the C Language

Character/ Symbol

Meaning Character/ Symbol

Meaning

~ tilde , Comma . Period ; Semicolon

? Ques. mark : Colon “ Double Quote ‘ Single Quote

( Left parenthesis ) Right Parenthesis

[ Left Bracket ] Right Bracket { Left Brace } Right Brace / Slash \ Back Slash

< Less than > Greater than

= Equal to ! Exclamatory Mark

- Minus + Plus # Hash $ Dolor Sign & Ampersand * Asterisk (or

star) % Percent ^ Carat _ Underscore | Vertical Bar 5 September 2015 ABHISHEK DWIVEDI

Page 9: Learning c - An extensive guide to learn the C Language

Identifiers are distinct names given to program elements such as constants, variables, etc.

An Identifier is a sequence of letters, digits, and the special character _ underscore .

1. It must start with either a letter or underscore. _

2. No commas or blanks are allowed within a variable name.

3. The upper case and lower case letters are treated as distinct, i.e., identifiers are case-sensitive.

4. An identifier can be of any length. 5. No special symbol can be used in a variable

name.

Identifiers

5 September 2015 ABHISHEK DWIVEDI

Page 10: Learning c - An extensive guide to learn the C Language

9 Keywords are predefined tokens in C. These are also called reserved words.

9 Key words have special meaning to the C compiler. These key words can be used only for their intended action; they cannot be used for any other purpose.

9 C has 32 keywords.

Keywords

5 September 2015 ABHISHEK DWIVEDI

Page 11: Learning c - An extensive guide to learn the C Language

auto break case char const

continue default do double else

enum extern float for goto

if int long register return

short signed sizeof static struct

switch typedef union unsigned void

volatile while

The standard keywords are

5 September 2015 ABHISHEK DWIVEDI

Page 12: Learning c - An extensive guide to learn the C Language

A data type defines a set of values and the operations that can be performed on them.

Every datatype item (constant, variable etc.) in a C program has a datatype associated with it.

C also has a special datatype called void, which, indicates that any data type, i.e., no data type, does not describe the data items.

Data types

5 September 2015 ABHISHEK DWIVEDI

Page 13: Learning c - An extensive guide to learn the C Language

Data types Description Size (No. of Bytes) Range

Char Single character 1 0 to 255

Int An integer 2 -32768 to +32767

Float Floating point number 4 -2,147,483,648 to +2,147,483,647

Double Floating point number 8 Approximately 15 digits of Precision

Void No data type 0

signed char Character 1 -128 to 127

unsigned char Unsigned character 1 0 to 255

short signed int Short signed integer 2 -32768 to +32767

short unsigned int Short unsigned integer

3 0 to 65535

Long singed int Long signed integer 4 -2,147,483,648 to +2,147,483,647

5 September 2015 ABHISHEK DWIVEDI

Page 14: Learning c - An extensive guide to learn the C Language

A constant is a literal, which remain unchanged during the execution of a program.

A constant is a fixed value that cannot be altered during the execution of a program. C constants can be classified into two categories.

9 Primary Constants 9 Secondary Constants

Constants and Variables

5 September 2015 ABHISHEK DWIVEDI

Page 15: Learning c - An extensive guide to learn the C Language

An integer constant must have at least one digit.

It should not contain either a decimal point or exponent.

If a constant is positive, it may or may not be preceded by a plus sign. If it is a negative, it must be preceded by a minus sign.

Commas, blanks and non-digit characters are not allowed in integer constants.

The value of integer constant cannot exceed specified limits. The valid range is

–32768 to +32767.

Rules for constructing Integer constants

5 September 2015 ABHISHEK DWIVEDI

Page 16: Learning c - An extensive guide to learn the C Language

Real values are often called floating-point constants. There are two ways to represent a real constant decimal form and exponential form.

In exponential form of representation, the real constant is represented in two parts. The part appearing before e is called mantissa, whereas the part following e is called exponent.

Real constants

5 September 2015 ABHISHEK DWIVEDI

Page 17: Learning c - An extensive guide to learn the C Language

The mantissa part and the exponential part should be separated by a letter e.

The mantissa part may have a positive or negative sign.

Default sign of mantissa part is positive.

The exponent must have at least one digit, which must be a positive or negative integer. Default sign is positive.

Range of real constants expressed in exponential form is - 3.4e38 to 3.4e38.

Rules for constructing Real constants

5 September 2015 ABHISHEK DWIVEDI

Page 18: Learning c - An extensive guide to learn the C Language

A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas point to the left. For example, A is valid character constant whereas A is not.

The maximum length of a character constant can be 1 character.

Note: Every character has its ASCII (American Standard Code for Information Interchange) value. That means every character is interchange with integer constant. For example, A value is 65 and a value is 97.

Rules for constructing Characters constants

5 September 2015 ABHISHEK DWIVEDI

Page 19: Learning c - An extensive guide to learn the C Language

A string constant is a sequence of characters enclosed in double quotes. The characters may be letters, numbers, blank space or special characters.

Note that is null string or empty string. And the single string constant A is not equivalent to the single character constant A .

Each string constant must end with a special character \ . This character is called null character and used to terminate the string. The compiler automatically places a null \ character at the end of every string constant.

String constants

5 September 2015 ABHISHEK DWIVEDI

Page 20: Learning c - An extensive guide to learn the C Language

Some non-printing characters and some other characters such as double quote , single quote , question mark ? and backslash \), require an escape sequence. A list of commonly used backslash character constants is given below.

Escape sequence

Escape Sequence Meaning ASCII value Escape

Sequence Meaning ASCII value

\a Bell 7 \r Carriage return

13

\b Back Space 8 \ Double Quote

34

\t Tab 9 \ Single Quote 39

\n New line 10 \? Question Mark

63

\v Vertical tab 11 \\ Back Slash 92

\f Form feed 12 \0 Null 0 5 September 2015 ABHISHEK DWIVEDI

Page 21: Learning c - An extensive guide to learn the C Language

A variable can be considered as a name given to the location in memory.

The term variable is used to denote any value that is referred to a name instead of explicit value.

A variable is able to hold different values during execution of a program, where as a constant is restricted to just one value.

For example, in the equation 2x + 3y = 10; since x and y can change, they are variables, whereas 2,3 and 10 cannot change, hence they are constants. The total equation is known as expression.

Variables

5 September 2015 ABHISHEK DWIVEDI

Page 22: Learning c - An extensive guide to learn the C Language

The name of a variable is composed of one to several characters, the first of which must be a letter .

No special characters other than letters, digits, and underscore can be used in variable name. Some compilers permit underscore as the first character.

Commas or Blanks are not allowed with in a variable name.

Upper case and Lower case letters are significant. That is the variable income is not same as )NCOME .

The variable name should not be a C key word. Also it should not have the same name as a function that is written either by user or already exist in the C library.

Rules for constructing variable names

5 September 2015 ABHISHEK DWIVEDI

Page 23: Learning c - An extensive guide to learn the C Language

There are basically four types of instructions in C: Type Declaration Instruction Input/Output Instruction Arithmetic Instruction Control Instruction

C Instructions

5 September 2015 ABHISHEK DWIVEDI

Page 24: Learning c - An extensive guide to learn the C Language

The purpose of each instructions 9 Type Declaration instruction

to declare the type of variables used in a C program

9 Input/Output instruction To perform the function of supplying input data to a program and obtaining the output results from it.

9 Arithmetic instruction to perform arithmetic operations between constants and variables.

9 Control instruction to control the sequence of execution of various statements in a C program.

5 September 2015 ABHISHEK DWIVEDI

Page 25: Learning c - An extensive guide to learn the C Language

An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.

Operators are used in program to manipulate data and variables. The data items that operators act upon are called operands.

Some operators require two operands, while others act upon only one operand. The operators are classified into unary, binary and ternary depending on whether they operate on one, two or three operands respectively.

Operators & Expressions

5 September 2015 ABHISHEK DWIVEDI

Page 26: Learning c - An extensive guide to learn the C Language

C has four classes of operators 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Bit-wise Operators

In addition, C has some special operators, which are unique to C, they are

1. Increment & Decrement Operators 2. Conditional Operators 3. Assignment Operators, etc.

Types of operators

5 September 2015 ABHISHEK DWIVEDI

Page 27: Learning c - An extensive guide to learn the C Language

There are five arithmetic operators in C.

The following table lists the arithmetic operators allowed in C:

Arithmetic Operators

Operator Meaning

+ Addition

_ Subtraction; also for unary minus

* Multiplication

/ Division

% Modulo division (remainder after integer division)

5 September 2015 ABHISHEK DWIVEDI

Page 28: Learning c - An extensive guide to learn the C Language

Relational Operators are symbols that are used to test the relationship between two variables or between a variable and a constant. We often compare two quantities, and depending on their relation takes certain decisions. These comparisons can be done with the help of relational operators.

C has six relational operators as shown below.

Relational Operators

Operator Meaning

> Greater than >= Greater than or Equal to < Less than

<= Less than or Equal to == Equal to != Not equal to

5 September 2015 ABHISHEK DWIVEDI

Page 29: Learning c - An extensive guide to learn the C Language

Logical Operators are symbols that are used to combine or negate expressions containing relational operators.

C has three logical operators as defined below.

Logical Operators

Operator Meaning

&& Logical AND

||

Logical OR

! Logical NOT

5 September 2015 ABHISHEK DWIVEDI

Page 30: Learning c - An extensive guide to learn the C Language

The lowest logical element in the memory is bit. C allows the programmer to interact directly with the hardware of a particular system through bitwise operators and expression.

These operators work only with int and char datatypes and cannot be used with float and double type.

The following table shows the bitwise operators that are available in C.

Bitwise operators

Operator Meaning - One s Complement

| Bitwise OR

& Bitwise AND

^ Bitwise Exclusive OR (XOR)

>> Right Shift

<< Left Shift 5 September 2015 ABHISHEK DWIVEDI

Page 31: Learning c - An extensive guide to learn the C Language

C has two very useful operators for adding and subtracting a variable. These are the increment and decrement operators, ++ and -- . These two operators are unary operators.

The increment operator ++ adds 1 to its operand, and the decrement operator -- subtracts 1 from its operand. Therefore, the following are equivalent operations.

++i is equivalent to i = i + 1;

--i is equivalent to i = i – 1;

These operators are very useful in loops.

Increment & Decrement operators

5 September 2015 ABHISHEK DWIVEDI

Page 32: Learning c - An extensive guide to learn the C Language

In addition to usual assignment operator =, C has a set of shorthand operators, that simplifies the coding of a certain type of assignment statement.

It is of the form

var op = exp

where var is a variable, op is a C binary arithmetic operator and exp is an expression.

5 September 2015 ABHISHEK DWIVEDI

Assignment operators

Statement Equivalent Statement a + = b a = a + b

a - = b a = a - b

a * =b a = a * b

a * = b + c a = a * ( b+ c)

a % = b a = a % b

a * = a a = a * a

Page 33: Learning c - An extensive guide to learn the C Language

C provides a peculiar operator ? : which is useful in reducing the code. It is ternary operator requiring three operands.

The general format is

exp1 ? exp2 : exp3;

where exp1, exp2 and exp3 are expressions.

In the above conditional expression, exp1 is evaluated first. If the value of exp1 is non zero (true), then the value returned will be exp2. if the value of exp1 is zero (false), then the value returned will be exp3.

5 September 2015 ABHISHEK DWIVEDI

Conditional Operator

Page 34: Learning c - An extensive guide to learn the C Language

The priority or precedence in which the operations of an arithmetic statement are performed is called the hierarchy of operators.

The operators of at the higher level of precedence are evaluated first. The operators of the same precedence are evaluated either from left to right or from right to left, depending on the level. This is known as the Associativity property of an operator.

PRECEDENCE OF OPERATORS (Arithmetic operators only)

5 September 2015 ABHISHEK DWIVEDI

Hierarchy (precedence) of operators

Operator Description Associativity Rank

* Multiplication Left to right 3

/ Division 3

% Modulo 3

+ Addition 4

- Subtraction 4

Page 35: Learning c - An extensive guide to learn the C Language

C programs consist of one or more functions. Each function performs a specific task. A function is a group or sequence of C statements that are executed together. The following is a simple C program that prints a message on the screen. /* A simple program for printing a message */ # include <stdio.h> # include <conio.h> void main( ) { clrscr( ); printf Welcome to C ; getch( ); }

5 September 2015 ABHISHEK DWIVEDI

Structure of a ‘C’ program

Page 36: Learning c - An extensive guide to learn the C Language

The first line /* A simple program for printing a message */

is a comment line. Comments in the c program are optional and may appear anywhere in a C program. Comments are enclosed between /* and */.

The second line # include <stdio.h>

tells the compiler to read the file stdio.h and include its contents in this file. stdio.h, one of header files, contain the information about input and output functions. stdio.h means Standard Input Output Header file. This file contains the information about printf() function.

5 September 2015 ABHISHEK DWIVEDI

Description

Page 37: Learning c - An extensive guide to learn the C Language

The third line # include <conio.h> tells the compiler to read the file conio.h and include its contents in this file. conio.h means Consoled Input Output Header file. This file contains the information about clrscr() and getch() functions.

The fourth line void main( ) is the stat of the main program. The word main is followed by a pair of ordinary parenthesis ( ), which indicates that main is also a function.

The fifth line { the left brace represents the beginning of the program.

The sixth line clrscr( ); tells the compiler to clear the screen and kept the cursor at left side corner.

5 September 2015 ABHISHEK DWIVEDI

Description (contd…)

Page 38: Learning c - An extensive guide to learn the C Language

The seventh line printf Welcome to C ;

this function causes its arguments to be printed on the screen on the computer.

The eight line getch( );

is reads the single character directly from the keyboard without printing on the screen.

The ninth line }

the right brace represents the ending of the program.

5 September 2015 ABHISHEK DWIVEDI

Description (contd…)

Page 39: Learning c - An extensive guide to learn the C Language

1. All C statements must end with semicolon. 2. C is case-sensitive. That is, upper case and lower case characters

are different. Generally the statements are typed in lower case. 3. A C statement can be written in one line or it can split into multiple

lines. 4. Braces must always match upon pairs, i.e., every opening brace {

must have a matching closing brace }. 5. Every C program starts with void main( ) function. 6. Comments cannot be nested. For example,

/* Welcome to C ,/* programming*/ */ A comment can be split into more than one line.

5 September 2015 ABHISHEK DWIVEDI

Rules to write a C program

Page 40: Learning c - An extensive guide to learn the C Language

Steps to be followed in writing and running a C program.

Creation of Source Program Create a C program file in various C compilers are available under MS-DOS, Turbo C Editor etc.

Compilation of the Program Turbo C compiler is user friendly and provides integrated program development environment. Thus, selecting key combination can do compilation. That means press Alt + F9 for compilation.

Program Execution In Turbo C environment, the RUN option will do the compilation and execution of a program. Press Ctrl + F9 for execution the program.

5 September 2015 ABHISHEK DWIVEDI

Execution of C Program

Page 41: Learning c - An extensive guide to learn the C Language

The printf( ) function is used to write information to standard output (normally monitor screen). The structure of this function is

printf(format string, list of arguments);

The format string contains the following: 1. Characters that are simply printed on the screen. 2. Specifications that begin with a % sign and define the output format

for display of each item.

3. Escape sequence characters that begin with a \ sign such as \n, \t, \b etc.

5 September 2015 ABHISHEK DWIVEDI

printf( ) Function: Writing Output Data

Character Argument Resulting Output

c Character A single character

d Integer Signed decimal integer

s String Prints character strings

f Floating point

Single floating point number

Page 42: Learning c - An extensive guide to learn the C Language

The real power of a technical C program is its ability to interact with the program user. This means that the program gets input values for variables from users.

The scanf( ) function is a built-in C function that allows a program to get user input from the keyboard. The structure of this function is

scanf(format string &list of arguments);

Examples

scanf %d , &a ;

scanf %d %c %f ,&a, &b, &c ;

5 September 2015 ABHISHEK DWIVEDI

scanf( ) Function: getting user input

Page 43: Learning c - An extensive guide to learn the C Language

The control flow statements of a language determine the order in which the statements are executed.

We also need to be able to specify that a statement, or a group of statements, is to be carried out conditionally, only if some condition is true.

Also we need to be able to carry out a statement or a group of statements repeatedly based on certain conditions.

These kinds of situations are described in C using Conditional Control and Loop Control structures.

5 September 2015 ABHISHEK DWIVEDI

CONTROL STRUCTURES

Page 44: Learning c - An extensive guide to learn the C Language

A conditional structure can be implemented in C using The if statement

The if-else statement

The nested if-else statement

The switch statement.

whereas loop control structures can be implemented in C using while loop

do-while loop

for statement

5 September 2015 ABHISHEK DWIVEDI

Conditional & loop structures

Page 45: Learning c - An extensive guide to learn the C Language

The if statement is used to control the flow of execution of statements. The general form of if statement is if (condition) statement; Suppose if it is required to include more than one statement, then a compound statement is used, in place of single statement. The form of compound statement is if (condition) { statement1; statement2; } If the condition is true, then the statement/statements will be executed. If the condition is false, then the statement/statements will not be executed.

5 September 2015 ABHISHEK DWIVEDI

The if statement

Page 46: Learning c - An extensive guide to learn the C Language

Program /* Inputting year is Leap or not */ #include<stdio.h> #include<conio.h> void main() { int year; clrscr(); printf Enter year: ; scanf %d ,&year); if(year%4==0) printf Leap year ; if(year%4!=0) printf Not leap year ; getch(); } 5 September 2015 ABHISHEK DWIVEDI

The if statement : Program

Output 1 Enter year:1990 Not leap year Output 2 Enter year:1996 Leap year

Page 47: Learning c - An extensive guide to learn the C Language

The general form of if-else statement is… if (condition) statement1; else statement2; If the condition is true, then statement1 is executed. Otherwise if the condition is false, then the statement2 is executed. Here statements statement1 and statement2 are either simple statements or compound statements. That is… if (condtion) { statements /* if block */ } else { statements /* else */ }

5 September 2015 ABHISHEK DWIVEDI

The if-else Statement

Page 48: Learning c - An extensive guide to learn the C Language

Program /* Single digit or not */ #include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf Enter a number: ; scanf %d ,&n); if(n<=9) printf Single digit ; else printf Not single digit ; getch(); }

5 September 2015 ABHISHEK DWIVEDI

The if-else Statement : Program

Output 1 Enter a number:5 Single digit Output 2 Enter a number:12 Not single digit

Page 49: Learning c - An extensive guide to learn the C Language

When a series of conditions are involved, we can use more than one if-else statement in nested form.

This form is also known as if-else if-else statements. The general form of if-else if-else statement is

if (condition)

statements;

else if (condition)

statements;

else

statements;

Note that a program contains number of else if statements and must be ended with else statement.

5 September 2015 ABHISHEK DWIVEDI

Nested if-else Statements

Page 50: Learning c - An extensive guide to learn the C Language

Program

/* To check whether +ve, -ve or zero */ #include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf Enter a number: ; scanf %d ,&n); If(n>0) printf +ve ; else if(n<0) printf -ve ; else printf zero ; getch(); }

5 September 2015 ABHISHEK DWIVEDI

Nested if-else Statements : Program

Output 1 Enter a number: -2 -ve Output 2 Enter a number:0 zero Output 3 Enter a number:5 +ve

Page 51: Learning c - An extensive guide to learn the C Language

The Switch statement is an extension of the if-else if-else statement. The switch makes one selection when there are several choices to be made. The direction of the branch taken by the switch statement is based on the value of any int (or int compatible) variable or expression. The general form of Switch statement is shown below. switch (variable) { case constant1:statement 1; case constant2:statement 2; case constant3:statement 3; case constant n:statement n; default :statement; }

5 September 2015 ABHISHEK DWIVEDI

The Switch Statement

Page 52: Learning c - An extensive guide to learn the C Language

Program

/* Letter -> color name */

#include<stdio.h>

#include<conio.h>

void main()

{

char x;

clrscr();

printf Enter a char: ;

scanf %c ,&x);

switch(x)

{

case w :printf w->white ;

break;

case b :printf b->black ;

break;

default:printf No color ;

}

getch();

}

5 September 2015 ABHISHEK DWIVEDI

The Switch Statement : Program

Output 1 Enter a char:w w->white Output 2 Enter a char:b b->black Output 3 Enter a char:c No color

Page 53: Learning c - An extensive guide to learn the C Language

The exit( ) is a function in the standard library of C. This function causes immediate termination of the program and execution control return to the operating system.

In general, the termination to exit( ) function is 0 to indicate that termination is normal. Other arguments may be used to indicate some sort of an error.

5 September 2015 ABHISHEK DWIVEDI

The exit( ) Function

Page 54: Learning c - An extensive guide to learn the C Language

A portion of program that is executed repeatedly is called a loop.

The C programming language contains three different program statements for program looping. They are

9 For loop 9 While loop 9 Do-While loop

5 September 2015 ABHISHEK DWIVEDI

LOOPS

Page 55: Learning c - An extensive guide to learn the C Language

The for loop is used to repeat the execution statement for some fixed number of times.

The general form of for loop is

for(initialization;condition;increment/decrement)

statement;

where the statement is single or compound statement.

initialization is the initialization expression, usually an assignment to the loop-control variable. This is performed once before the loop actually begins execution.

condition is the test expression, which evaluated before each iteration of the loop, which determines when the loop will exist.

increment is the modifier expression, which changes the value of loop control variable. This expression is executed at the end of each loop.

5 September 2015 ABHISHEK DWIVEDI

The For Loop

Page 56: Learning c - An extensive guide to learn the C Language

Program

/* Print 1 to 10 numbers */

#include<stdio.h>

#include<conio.h>

void main()

{

int i;

clrscr();

for(i=1;i<=10;i++)

printf \n%d ,i);

getch();

}

5 September 2015 ABHISHEK DWIVEDI

The For Loop : Program

Output 1 2 3 4 5 6 7 8 9 10

Page 57: Learning c - An extensive guide to learn the C Language

The while loop is best suited to repeat a statement or a set of statements as long as some condition is satisfied.

The general form of while loop is

initial expression;

while(conditional-expression)

{

statement;

increment/decrement;

}

where the statement (body of the loop) may be a single statement or a compound statements. The expression (test condition) must results zero or non-zero.

5 September 2015 ABHISHEK DWIVEDI

The While Loop

Page 58: Learning c - An extensive guide to learn the C Language

Program /* Print a message 3 times */ #include<stdio.h> #include<conio.h> void main() { int i=1; clrscr(); while(i<=3) { printf \nJiffy Solutions ; i++; } getch(); }

5 September 2015 ABHISHEK DWIVEDI

The While Loop : Program

Output Jiffy Solutions Jiffy Solutions Jiffy Solutions

Page 59: Learning c - An extensive guide to learn the C Language

The structure of do-while loop is similar to while loop. The difference is that in case of do-while loop the expression is evaluated after the body of loop is executed. In case of while loop the expression is evaluated before executing body of loop.

The general form of do-while statement is

do

{

statement;

}while(expression);

where statement is a single statement or compound statement. In contrast to while loop statement (body of loop), do-while loop is executed one or more times.

5 September 2015 ABHISHEK DWIVEDI

The do-while loop

Page 60: Learning c - An extensive guide to learn the C Language

An Array is a collection of same data type. The elements of an array are referred by a common name and are differentiate from one another by their position with in an array. The elements of an array can be of any data type but all elements in an array must be of the same type.

The general form of declaring a array is

type array_name[size];

where type is a valid datatype, array_name is the name of the array and size is the number of elements that array_name contains.

Example:

int A[100];

int Æ data type of elements that an array

A Æ name of array

100 Æ size of an array

5 September 2015 ABHISHEK DWIVEDI

ARRAYS

Page 61: Learning c - An extensive guide to learn the C Language

The individual elements of an array can be referenced by means of its subscript (or index) Suppose A is an array of 20 elements, we can reference each element as

A[0] Æ 1st element

A[1] Æ 2nd element A[2] Æ 3rd element :

:

A[19] Æ 20th element Note: Subscript enclosed within parenthesis.

In C subscript starts from 0. That is, if we declare an array of size n, then we can refer the elements from 0 to (n-1)th element.

Arrays are of 3 types. They are 9Single Dimensional Array

9Double Dimensional Array 9Multi Dimensional Array

5 September 2015 ABHISHEK DWIVEDI

ARRAYS (Contd…)

Page 62: Learning c - An extensive guide to learn the C Language

The general form of Single Dimensional array is:

datatype variable[size];

Example:

int A[20];

Initialization of arrays during declaration

Similar to other datatypes, the array also can be initialized at the time of declaration.

int num[5] ={3,2,1,5,4};

char name[ ] = { c , o , m , p , u , t , e , r , s };

float rate[] = {20.5,15.75,12.34};

5 September 2015 ABHISHEK DWIVEDI

Single Dimensional Array

Page 63: Learning c - An extensive guide to learn the C Language

Program illustrating Single Dimensional Array #include<stdio.h> #include<conio.h> void main() { int a[5],i; clrscr(); printf Enter elements into an array: ; for(i=0;i<=4;i++) scanf %d ,&a[i]); printf The elements are: ; for(i=0;i<=4;i++) printf \n%d ,a[i]); getch(); }

5 September 2015 ABHISHEK DWIVEDI

Single Dimensional Array : Program

Page 64: Learning c - An extensive guide to learn the C Language

The general form of Two-Dimensional Arrays is

type array_name[row_size][column_size];

Example:

int a[2][2];

Initializing Two-Dimensional Arrays

Like the one-dimensional arrays, following their declaration with a list of initial values enclosed in braces may initialize two-dimensional arrays. For example,

int a[2][2] ={1,2,5,4};

initializes the elements of the first row to zero and the second row to one. The initialization is done row by row. The above statement can be equivalently written as

int a[2][2]={{1,2},{5,4}};

5 September 2015 ABHISHEK DWIVEDI

Two-Dimensional Array

Page 65: Learning c - An extensive guide to learn the C Language

Program Illustrating Two Dimensional arrray #include<stdio.h> #include<conio.h>

void main() { int a[2][2],i,j;

clrscr(); printf Enter elements into array: ; for(i=0;i<=1;i++)

{ for(j=0;j<=1;j++) {

scanf %d ,&a[i][j]); } }

5 September 2015 ABHISHEK DWIVEDI

Two-Dimensional Array : Programs printf The elements are:\n ;

for(i=0;i<=1;i++) { for(j=0;j<=1;j++) { printf %d ,a[i][j]); } printf \n ; } getch(); }

Page 66: Learning c - An extensive guide to learn the C Language

A string is an array of characters. There is no string built-in data type in C. But we can declare string as an array of characters. To recognize a character array, it should end with a null character \ .

For example, the string SCIENCE would be stored as

S C ) E N C E \

The length of a string is the number of characters it contains excluding null character. Hence, the number of locations needed to store a string is one more than length of string.

In this example, the length of the string is 7.

5 September 2015 ABHISHEK DWIVEDI

Handling of Character Strings

Page 67: Learning c - An extensive guide to learn the C Language

The general form of declaration of string variable is char string-name[size]; where, string-name is the name of a string and size is the maximum number of characters the string-name can contain. Example: char name[30]; String variables can be initialized at the time of declaration. Example: char name[ ] = Millennium ; A string can also be initialized at the time of declaration in the following ways. char name[ ] = Millennium ; or char name[ ] ={ M , i , l , l , n , n , i , u , m , \ };

5 September 2015 ABHISHEK DWIVEDI

Declaring and initializing string variables

Page 68: Learning c - An extensive guide to learn the C Language

The scanf(), printf() function is used with %s with format specification to read and print a string.

Example:

char str[30];

scanf %s ,str);

printf %s ,str);

In the case of reading strings, the ampersand (&) is not required before the string variable name. As mentioned earlier, one of the limitations of the scanf() function is that it is not capable of holding multiword strings, even though it can read them.

5 September 2015 ABHISHEK DWIVEDI

Reading and writing strings

Page 69: Learning c - An extensive guide to learn the C Language

Program #include<stdio.h> #include<conio.h> void main() { char line[80]; clrscr(); printf Enter a line\n ; scanf %s ,line); printf The entered line is:%s ,line); getch(); }

5 September 2015 ABHISHEK DWIVEDI

Reading and writing strings : Program

Page 70: Learning c - An extensive guide to learn the C Language

Every C compiler provides a large set of string handling library functions, which are contained in the header file string.h

The following table shows some of the functions available in string.h header file.

5 September 2015 ABHISHEK DWIVEDI

String handling Functions: string.h

Function Meaning

strcat()

String concatenate. Append one string to another. First character of string2 overwrites null character of string1.

strlen()

Returns the length of the string not counting the null character.

strlwr() Converts a string to lower case.

strupr() Converts a string to upper case.

strcpy() Copies a string into another.

strcmp() Compares two strings

strrev() Reverses a string

Page 71: Learning c - An extensive guide to learn the C Language

The strcat() function concatenates the source string at the end of the target string. For example Computing and Techniques on concatenation would result in string ComputingTechniques .

The general form is

strcat(string1, string2);

strong2 appends to string1 and the first character to string2 overwrites null character of first string1. This function returns the first argument i.e., string1. The string2 remains unchanged.

5 September 2015 ABHISHEK DWIVEDI

strcat() function

Page 72: Learning c - An extensive guide to learn the C Language

Program

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char s1[30],s2[15];

clrscr();

printf Enter String : ;

gets(s1);

printf Enter String : ;

gets(s2);

printf The entire string is:%s ,strcat(s1,s2));

getch();

}

5 September 2015 ABHISHEK DWIVEDI

strcat() function : Program

Output Enter String1:Jiffy Enter String2:Solutions The entire string is: Jiffy Solutions

Page 73: Learning c - An extensive guide to learn the C Language

strcmp() function compares two strings to find out whether they are same or different.

The two strings are compared character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first.

The general form is:

strcmp(string1, string2);

If the two strings are same, strcmp() returns a value 0.

If they are not same, it returns the numeric difference between the ASCII values of the first non-matching characters.

That is, it returns less than 0 if string1 is less than string2, and greater than 0 if string1 is greater than string2.

5 September 2015 ABHISHEK DWIVEDI

strcmp() function

Page 74: Learning c - An extensive guide to learn the C Language

Program

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char s1[25],s2[25];

int c;

clrscr();

printf Enter string : ;

gets(s1);

printf Enter string : ;

gets(s2);

c=strcmp(s1,s2);

if(c>0)

printf String > String ;

else if(c<0)

printf String > String ;

else

printf Both are equal ;

getch();

} 5 September 2015 ABHISHEK DWIVEDI

strcmp() function : Program

Output Enter String1:abc Enter String2:ABC String1 > String2

Page 75: Learning c - An extensive guide to learn the C Language

The general form is:

strcpy(String1, String2);

The strcpy() function is used to copy the character string from String2 to String1.

This function returns the result string String1 the String2 remains unchanged. String2 may be a character array or a string constant.

5 September 2015 ABHISHEK DWIVEDI

strcpy() function

Page 76: Learning c - An extensive guide to learn the C Language

Program

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

{

char s1[15],s2[15];

clrscr();

printf Enter String :

gets(s1);

printf The String is:%s ,strcpy(s2,s1));

getch();

}

5 September 2015 ABHISHEK DWIVEDI

strcpy() function : Program

Output Enter String1:Millennium The String2 is:Millennium

Page 77: Learning c - An extensive guide to learn the C Language

This function strlen() counts the number of characters present in a string. The counting ends at the first null character.

The general form is

strlen (String1);

The strlen() function returns the length of the argument String1 excluding the null character. The argument may be a string constant.

5 September 2015 ABHISHEK DWIVEDI

strlen() function

Page 78: Learning c - An extensive guide to learn the C Language

Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str[30]; clrscr(); printf Enter a string: ; gets(str); printf The length of a string is:%d ,strlen(str)); getch(); }

5 September 2015 ABHISHEK DWIVEDI

strlen() function : Program

Output Enter a string: Millennium Software Solutions The length of a string is:29

Page 79: Learning c - An extensive guide to learn the C Language

The strupr() function is used to convert the string into upper case.

The strlwr() function is used to convert the string into lower case.

The strrev() function prints the entire string in reverse order.

5 September 2015 ABHISHEK DWIVEDI

strupr(), strlwr(), strrev() functions

Page 80: Learning c - An extensive guide to learn the C Language

Program #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str[15]; clrscr(); printf Enter a string: ; gets(str); printf The upper case string is:%s ,strupr(str)); printf \nThe lower case string is:%s ,strlwr(str)); printf \nThe reverse string is:%s ,strrev(str)); getch(); }

5 September 2015 ABHISHEK DWIVEDI

strupr(), strlwr(), strrev() functions : Program

Output Enter a string:millennium The upper case string is:MILLENNIUM The lower case string is:millennium The reverse string is:muinnellim

Page 81: Learning c - An extensive guide to learn the C Language

Functions are building blocks of C. Function performs the same set of instructions on different sets of data or at different portions of a program.

C functions can be classified into two categories, namely

library functions and user-defined functions.

main is an example of user-defined functions. printf and scanf belong to the category of library functions.

The main distinction between these two categories is that library functions are not required to be written by us whereas a user-defined function has to be developed by the user at the time of writing a program.

The general form of C function is

Return-type Function-name (parameter list)

parameter declaration;

{

Body of function;

}

5 September 2015 ABHISHEK DWIVEDI

Functions

Page 82: Learning c - An extensive guide to learn the C Language

9It facilitates top-down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later.

9The length of a source program can be reduced by using functions at appropriate places. This factor is particularly critical with microcomputers where memory space is limited.

9Many other programs may use a function. This means that a C programmer can build on what others have already done, instead of starting over, from scratch.

9As mentioned earlier, it is easy to locate and isolate a faulty function for further investigations.

5 September 2015 ABHISHEK DWIVEDI

Advantages of user-defined functions:

Page 83: Learning c - An extensive guide to learn the C Language

A function, depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories:

Category 1: Functions with no arguments and no return values.

Category 2: Functions with arguments and no return values.

Category 3: Functions with arguments and return values.

5 September 2015 ABHISHEK DWIVEDI

Category of functions

Page 84: Learning c - An extensive guide to learn the C Language

Program #include<stdio.h> #include<conio.h> Function Declaration void printline(); void main() { clrscr(); printline(); /*Function Declaration*/ printf This illustrates the use of C functions\n ; printline(); getch(); } void printline() /*Return Type & Function Name*/ { int i; for(i=1;i<=40;i++) printf - ; printf \n ; }

5 September 2015 ABHISHEK DWIVEDI

Functions with no arguments and no return values

Page 85: Learning c - An extensive guide to learn the C Language

Program

#include<stdio.h>

#include<conio.h>

void swap(int,int);

void main()

{

int a,b;

clrscr();

printf Enter numbers: ;

scanf %d%d ,&a,&b);

swap(a,b); /* Function Call*/

getch();

}

void swap(int x, int y) /*Called Function*/

{

int z;

z = x;

x = y;

y = z;

printf \nAfter swapping:%d,%d ,x,y);

}

5 September 2015 ABHISHEK DWIVEDI

Arguments but no Return values

Page 86: Learning c - An extensive guide to learn the C Language

Program

#include<stdio.h>

#include<conio.h>

int big(int,int);

void main()

{

int a,b,max;

clrscr();

printf Enter numbers: ;

scanf %d%d ,&a,&b);

max = big(a,b);

printf \nThe biggest number is:%d ,max);

getch();

}

int big(int x, int y)

{

if(x>y)

return x;

else

return y;

}

5 September 2015 ABHISHEK DWIVEDI

Arguments with Return Values

Page 87: Learning c - An extensive guide to learn the C Language

Recursion is a technique to be used to call itself.

In C, it is possible for the functions to call themselves.

A function is called recursive if a statement with in the body of a function calls the same function itself.

Program

#include<stdio.h>

#include<conio.h>

long int fact(int);

void main()

{

int n;

long int res;

clrscr();

printf Enter a positive number: ;

scanf %d ,&n);

res = fact(n);

printf The factorial is:%ld ,res);

getch();

}

5 September 2015 ABHISHEK DWIVEDI

Recursion long int fact(int n) { long int f; if(n==1) return 1; else f = n*fact(n-1); return f; }

Page 88: Learning c - An extensive guide to learn the C Language

9All C programs must contain atleast one function. [The main() function serves this rule]

9A function can return only one value. Thus we should not specify two values to return.

9The return type in function declaration is optional. If no return type is specified it is assumed to be an integer which is default.

9When a function is not returning any value, void type can be used as return type.

9Parameter list is optional.

9 C provides a statement return

return expression

9Return statement is used in function definition to communicate the return value to the calling function.

5 September 2015 ABHISHEK DWIVEDI

Important points about functions

Page 89: Learning c - An extensive guide to learn the C Language

9Return statement indicates exit from the function and return to the point from where the function was invoked.

9There may be any number of return statements in function definition, but only one return statement will activate in a function call.

9The variable declarations within the function (between braces { }) are local to the function and are not available outside the function.

9If there is no return statement, the program will return to the calling point after it reaches the end of the function body (}).

9A function call can be used wherever a variable of same type is used (except the left side of an assignment statement).

9There should be one to one correspondence between the actual and formal parameters in type, order and number.

9C allows recursion. That is a function can call itself.

9A C function cannot be defined in another function.

5 September 2015 ABHISHEK DWIVEDI

Important points (Contd…)

Page 90: Learning c - An extensive guide to learn the C Language

Like the values of simple variables, it is also possible to pass the values of an array to a function.

To pass an array to a called function, it is sufficient to list the name of the array, without any subscripts, and the size of the array as arguments. For example, the call

largest(a,n);

will pass all the elements contained in the array a of size n. The called function expecting this call must be appropriately defined. The largest function header might look like:

int largest(array,size);

int array[];

int size;

5 September 2015 ABHISHEK DWIVEDI

Functions with Arrays

Page 91: Learning c - An extensive guide to learn the C Language

There are three basic places in a C program where variables will be declared:

9 inside the function,

9in the definition of function parameters,

9or outside of all functions.

These variables are called local variables, formal parameters, and global variables respectively.

5 September 2015 ABHISHEK DWIVEDI

Variables

Page 92: Learning c - An extensive guide to learn the C Language

The body of any function comprises of two parts: declaration of variables and a set of executable statements.

Variables declared inside a function are called local variables. This name derives from the fact that a variable inside a function can be used only inside that function.

An attempt on our part or access the local variable of one function in another, will draw an error from the compiler: Identifier undefined.

5 September 2015 ABHISHEK DWIVEDI

Local Variables

Page 93: Learning c - An extensive guide to learn the C Language

C program consists of three sections namely: the preprocessor directives, the global variable section and finally the functions.

The variables that are declared in the global variable section are called global variables.

While a local variable can be used only inside a function in which it is declared, a global variable can be used anywhere in the program.

5 September 2015 ABHISHEK DWIVEDI

Global Variables Block Variables Yet another place to declare variables is inside any block: these variables are called block variables and these can be used only inside that block.

Page 94: Learning c - An extensive guide to learn the C Language

The storage class of a variable dictates how, when and where storage will be allocated for the variable. The different storage classes available are:

1. Auto

2. Register

3. Extern

4. Static

5 September 2015 ABHISHEK DWIVEDI

Storage classes

Page 95: Learning c - An extensive guide to learn the C Language

Automatic variables are declared inside a function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited, hence the name automatic.

Automatic variables are therefore private (or local) to the function in which they are declared. Because of this property, automatic variables are also refereed to as local or internal variables.

A variable declared inside a function without storage class specification is, by default, an automatic variable.

One important feature of automatic variables is that their value cannot be changed accidentally by what happens in some other function in the program. This assures that we may declare and use the same variable name in different functions in the same program without causing any confusion to the compiler.

5 September 2015 ABHISHEK DWIVEDI

Auto

Page 96: Learning c - An extensive guide to learn the C Language

#include<stdio.h>

#include<conio.h>

void function1();

void function2();

void main()

{

int m = 1000;

clrscr();

function2();

printf %d\n ,m);

getch();

}

5 September 2015 ABHISHEK DWIVEDI

Auto : Program void function1() { int m = 10; printf %d\n ,m); } void function2() { int m = 100; function1(); printf %d\n ,m); }

Page 97: Learning c - An extensive guide to learn the C Language

It is possible for use to attribute the register storage class to certain variables. We can tell the compiler that a variable should be kept in one of the machine s registers, instead of keeping in the memory where normal variables are stored). Since a register access is much faster than a memory access, keeping the frequently accessed variables in the register will lead to faster execution of programs. This is done as follows: register int count; The important point while using register variables is, registers of CPU do not have addresses. Thus, we should not refer the address of a register variable. For example, The following statement will result an error : register int i; scanf %d ,&i);

5 September 2015 ABHISHEK DWIVEDI

Register

Page 98: Learning c - An extensive guide to learn the C Language

#include<stdio.h>

#include<conio.h>

void main()

{

register int count;

int sum;

clrscr();

for(count=0;count<10;count++)

sum = sum + count;

printf The sum is:%d ,sum);

getch();

}

5 September 2015 ABHISHEK DWIVEDI

Register : Program

Page 99: Learning c - An extensive guide to learn the C Language

This is the default storage class for all global variables.

Extern storage class variables get initialized (to zero in the case of integers) automatically, retain their value throughout the execution of the program and can be shared by different modules of the same program.

(owever, assuming int intvar; is present in a.c., to be also to have proper binding with the same variable, b.c another file should have extern int intvar .

5 September 2015 ABHISHEK DWIVEDI

Extern

Page 100: Learning c - An extensive guide to learn the C Language

a.c file

#include<stdio.h>

#include<conio.h>

int intvar;

extern float f;

void main()

{

char ch;

funct(ch,intvar);

printf %f ,f);

getch();

}

5 September 2015 ABHISHEK DWIVEDI

Extern : Program b.c file float f = 84.237; extern int intvar; funct(char c, int intvar) { char c1,c2; : : }

Page 101: Learning c - An extensive guide to learn the C Language

The static storage class has a number of implications depending upon its usage. The default storage class for all local variables is auto. This can be changed to static by prefixing the declaration with the keyword static as in static int intvar. A local variable with static storage class is still a local variable as far as its scope is concerned, it is still available only inside the function in which it is declared. But certain other properties of the variable change; It gets initialized to zero automatically, is initialized only once, (during program startup) and it retains its value throughout the execution of the program. When applied to a global variable, the global variable becomes inaccessible outside the file in which it is declared. This storage class can be applied to functions too. Similar to case 2, the functions become inaccessible outside the file.

5 September 2015 ABHISHEK DWIVEDI

Static

Page 102: Learning c - An extensive guide to learn the C Language

Program: #include<stdio.h> #include<conio.h> void main() { function1( ); function1( ); function1( ); getch(); } void function1() { static int n; n++; printf \nThe value of n is:%d ,n); }

5 September 2015 ABHISHEK DWIVEDI

Static : Program

Output The value of n is 1 The value of n is 2 The value of n is 3

Page 103: Learning c - An extensive guide to learn the C Language

5 September 2015 ABHISHEK DWIVEDI

Storage class

Type Default initial value

Where declared

Scope Life Storage

Auto or none

Local garbage value

within the function within the function where it is declared

until function is no longer active

Memory

Register Local garbage value

within the function within the function where it is declared

until function is no longer active

CPU registers

Static Local Zero within the function within the function where it is declared

until program ends, value of the variable persists between different function calls

Memory

Extern Global Zero A heat of all functions within a file

All files including other files where declared extern

While any of these files are active. That is, as long as the program’s execution doesn’t come to an end

Memory

Page 104: Learning c - An extensive guide to learn the C Language

A structure is a convenient tool for handling a group of logically related data items. These fields are called structure elements or members. Declaring A Structure The general form of a structure declaration statement is given below: struct <structure name> { structure element1; structure element2; structure element3; ………. ………. }

5 September 2015 ABHISHEK DWIVEDI

Structures Example: struct book { char name[20]; char author[15]; int pages; float price; }

Page 105: Learning c - An extensive guide to learn the C Language

9The closing brace in the structure type declaration must be followed by a semicolon.

9It is important to understand that a structure type declaration does not tell the compiler to reserve any space in memory. All a structure declaration does is, it defines the form of the structure.

9Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined.

5 September 2015 ABHISHEK DWIVEDI

Important points while declaring a structure type:

Page 106: Learning c - An extensive guide to learn the C Language

We can assign values to the members of a structure in a number of ways. As mentioned earlier, the members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator . Which is also known as dot operator or period operator .

The general form is

Structure-Variable. Structure-Member;

For example,

book1.price;

We can also use scanf to give the values through the keyboard.

scanf %s ,book .name ;

scanf %d ,&book .pages ;

are valid input statements.

5 September 2015 ABHISHEK DWIVEDI

ACCESSING STRUCTURES ELEMENTS

Page 107: Learning c - An extensive guide to learn the C Language

we may declare an array of structures, each element of the array representing a structure variable. For example,

struct class student[100];

defines an array called student, that consists of 100 elements. Each element is defined to be of the type struct class. Consider the following declaration:

struct marks

{

int sub1;

int sub2;

int sub3;

}s[5];

5 September 2015 ABHISHEK DWIVEDI

ARRAYS OF STRUCTURES

Page 108: Learning c - An extensive guide to learn the C Language

C permits the use of arrays as structure members. We have already used arrays of characters inside a structure. Similarly, we can use single-or multi-dimensional arrays of type int or float.

For example, the following structure declaration is valid:

struct marks

{

int number;

float sub[3];

}s[2];

5 September 2015 ABHISHEK DWIVEDI

ARRAYS WITHIN STRUCTURES

Page 109: Learning c - An extensive guide to learn the C Language

Structures within a structure means nesting of structures. Nesting of structures is permitted in C. Let us consider the following structure definition: struct salary { char name[20]; char dept[10]; struct { int dearness; int house_rent; int city; }allowance; }employee;

5 September 2015 ABHISHEK DWIVEDI

STRUCTURES WITHIN STRUCTURES

The salary structure contains a member named allowance which itself is a structure with three members. The members contained in the inner structure namely dearness, house_rent, and city can be referred to as employee.allowance.dearness employee.allowance.house_rent employee.allowance.city

Page 110: Learning c - An extensive guide to learn the C Language

Unions are a concept borrowed from structures and therefore follow the same syntax as structures. However, there is major distinction between them in terms of storage. In structures, each member has its own storage location, whereas all the members of a union use the same location. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Like structures, a union can be declared using the keyword union as follows:

union item

{

int m;

float x;

char c;

}code;

5 September 2015 ABHISHEK DWIVEDI

UNIONS

Page 111: Learning c - An extensive guide to learn the C Language

We normally use structures, unions, and arrays to create variables of large sizes. The actual size of these variables in terms of bytes may change from machine to machine. We may use the unary operator sizeof to tell us the size of a structure (or any variable).

The expression

sizeof(struct x)

will evaluate the number of bytes required to hold all the members of the structure x. If y is a simple structure variable of type struct x, then the expression

sizeof(y)

would also give the same answer.

5 September 2015 ABHISHEK DWIVEDI

SIZE OF STRUCTURES

Page 112: Learning c - An extensive guide to learn the C Language

Pointers are another important feature of C language. They are a powerful tool and handy to use once they are mastered. There are a number of reasons for using pointers.

9A pointer enables us to access a variable that is defined outside the function.

9Pointers are more efficient in handling the data tables.

9Pointers reduce the length and complexity of a program.

9They increase the execution speed.

9The use of a pointer array to character strings results in saving of data storage space in memory.

5 September 2015 ABHISHEK DWIVEDI

Pointers

Page 113: Learning c - An extensive guide to learn the C Language

The actual location of a variable in the memory is system dependent and therefore, the address of a variable is not known to us immediately. We can determine the address of the variable with the help of the operator & in C. We have already seen the use of this address operator in the scanf function. The operator & immediately preceding a variable returns the address of the variable associated with it.

For example,

p = &quantity;

would assign the address to the variable p. The & operator can be remembered as address of .

5 September 2015 ABHISHEK DWIVEDI

ACCESSING THE ADDRESS OF A VARIABLE

Page 114: Learning c - An extensive guide to learn the C Language

#include<stdio.h> #include<conio.h> void main() { char a; int x; float p, q; clrscr(); a = A ; x = 125; p = 10.25, q = 18.76; printf %c is stored at address %u , a, &a ; printf \n%d is stored at address %u , x, &x ; printf \n%f is stored at address %u , p, &p ; printf \n%f is stored at address %u , q, &q ; getch(); }

5 September 2015 ABHISHEK DWIVEDI

ACCESSING ADDRESSES OF VARIABLES : PROGRAM

Page 115: Learning c - An extensive guide to learn the C Language

In C, every variable must be declared for its type. Since pointer variables contain addresses that belong to a separate data type, they must be declared as pointers before we use them.

The declaration of a pointer variable takes the following form:

datatype *pt_name;

This tells the compiler three things about the variable pt_name.

9The asterisk (*) tells the variable pt_name is a pointer variable.

9pt_name needs a memory location.

9pt_name points to a variable of type datatype.

5 September 2015 ABHISHEK DWIVEDI

DECLARING POINTERS For example, int *p; declares the variable p as a pointer variable that points to an integer data type. Remember that the type int refers to the data type of the variable being pointed to by p and not the type of the value of the pointer. Similarly, the statement float *x; declares x as a pointer to a floating point variable.

Page 116: Learning c - An extensive guide to learn the C Language

Once a pointer variable has been declared, it can be made to point to a variable using an assignment statement such as

p = &quantity;

which causes p to point to quantity.

That is, p now contains the address of quantity.

This is known as pointer initialization.

Before a pointer is initialized, it should not be used.

5 September 2015 ABHISHEK DWIVEDI

INITIALIZING POINTERS A pointer variable can be initialized in its declaration itself. For example, int x, *p=&x; is perfectly valid. It declares x as an integer variable and p as a pointer variable and then initializes p to the address of x. Note carefully that this is an initialization of p, not *p. And also remember that the target variable x is declared first. The statement int *p=&x, x; is not valid.

Page 117: Learning c - An extensive guide to learn the C Language

Once a pointer has been assigned the address of a variable, the question remains as to how to access the value of the variable using the pointer. This is done by using another unary operator * (asterisk), usually known as the indirection operator. Consider the following statements:

int quantity, *p, n;

quantity = 179;

p = &quantity;

n = *p;

5 September 2015 ABHISHEK DWIVEDI

ACCESSING A VARIABLE THROUGH ITS POINTER

Page 118: Learning c - An extensive guide to learn the C Language

The first line declares quantity and n as integer variables and p as a pointer variable pointing to an integer.

The second line assigns the value 179 to quantity.

The third line assigns the address of quantity to the pointer variable p.

The fourth line contains the indirection operator *. When the operator * is placed before a pointer variable in an expression, the pointer returns the value of the variable of which the pointer value is the address.

In this case, *p returns the value of the variable quantity, because p is the address of quantity. The * can be remembered as value of address . Thus the value of n would be 179.

5 September 2015 ABHISHEK DWIVEDI

ACCESSING A VARIABLE THROUGH ITS POINTER (CONTD…)

Page 119: Learning c - An extensive guide to learn the C Language

When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations.

The base address is the location of the first element (index 0) of the array. The compiler also defines the array name as a constant pointer to the first element.

5 September 2015 ABHISHEK DWIVEDI

POINTERS AND ARRAYS If we declare p as an integer pointer,

then we can make the pointer p to point to the array x by the following assignment: p = x; This is equivalent to p = &x[0]; When handling arrays, instead of using array indexing, we can use pointers to access array elements. Note that *(p+3) gives the value of x[3]. The pointer accessing method is much faster than array indexing.

Page 120: Learning c - An extensive guide to learn the C Language

C language requires the number of elements in an array to be specified at compile time. But we may not be able to do so always. Our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space.

Many languages permit a programmer to specify an array s size at run time. The process of allocating memory at run time is known as dynamic memory allocation.

In C language there are four library routines known as memory management functions that can be used for allocating and freeing memory during program execution.

5 September 2015 ABHISHEK DWIVEDI

DYNAMIC MEMORY ALLOCATION

Page 121: Learning c - An extensive guide to learn the C Language

5 September 2015 ABHISHEK DWIVEDI

Memory Allocation Functions Function Task

malloc Allocates requested size of bytes and returns a pointer to the first byte of the allocated space.

calloc Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory.

Free Frees previously allocated space.

realloc Modifies the size of previously allocated space.

Page 122: Learning c - An extensive guide to learn the C Language

A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer.

It takes the following form:

ptr = (datatype *)malloc(byte-size);

ptr is a pointer of type datatype. The malloc returns a pointer (of datatype) to an area of memory with size byte-size.

Example:

x = (int *) malloc (sizeof(int) * n);

5 September 2015 ABHISHEK DWIVEDI

Allocating a Block of Memory Use of malloc Function

#include<stdio.h> #include<conio.h> void main() { int *p, n, i; clrscr(); printf Enter n value: ; scanf %d ,&n); p = (int) malloc(sizeof(int)*n); printf \nEnter %d numbers: ,n ; for(i=0;i<n;i++) scanf %d ,* p+i)); printf \nThe numbers are: ; for(i=0;i<n;i++) printf \n%d ,* p+i)); getch(); }

Page 123: Learning c - An extensive guide to learn the C Language

calloc is another memory allocation function that is normally used for requesting memory space at run time for storing derived data types such as arrays and structures.

While malloc allocates a single block of storage space, calloc allocates multiple blocks of storage, each of the same size, and then sets all bytes to zero.

The general form of calloc is:

ptr = (datatype *) calloc (n,elem-size);

The above statement allocates contiguous space for n blocks, each of size elem-size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space, a NULL pointer is returned.

5 September 2015 ABHISHEK DWIVEDI

Allocating Multiple Blocks of Memory

Page 124: Learning c - An extensive guide to learn the C Language

Compile-time storage of a variable is allocated and released by the system in accordance with its storage class.

With the dynamic run-time allocation, it is our responsibility to release the space when it is not required.

The release of storage space becomes important when the storage is limited. We may release that block of memory for future use, using the free function:

free(ptr);

ptr is a pointer to a memory block which has already been created by malloc or calloc.

5 September 2015 ABHISHEK DWIVEDI

Releasing the Used Space

Page 125: Learning c - An extensive guide to learn the C Language

It is likely that we discover later, the previously allocated memory is not sufficient and we need additional space for more elements.

It is also possible that the memory allocated is much larger than necessary and we want to reduce it.

In both the cases, we can change the memory size already allocated with the help of the function realloc. This process is called the reallocation of memory. For example, if the original allocation is done by the statement

ptr = malloc(size);

then reallocation of space may be done by the statement

ptr = realloc(ptr, newsize);

5 September 2015 ABHISHEK DWIVEDI

Altering the Size of a Block

Page 126: Learning c - An extensive guide to learn the C Language

We know that a string is an array of characters, terminated with a null character.

Like in one-dimensional arrays, we can use a pointer to access the individual characters in a string.

5 September 2015 ABHISHEK DWIVEDI

POINTERS AND CHARACTER STRINGS

Program #include<stdio.h> #include<conio.h> void main() { char *str; int i=0; clrscr(); printf Enter a string: ; gets(str); while(*str!= \ { i++; str++; } printf \nThe length is:%d ,i); getch(); }

Page 127: Learning c - An extensive guide to learn the C Language

In functions we can pass the duplicate values for the actual parameters, but we can pass the address of a variable as an argument to a function in the normal fashion.

When we pass addresses to a function, the parameters receiving the addresses should be pointers. The process of calling a function using pointers to pass the addresses of variable is known as call by address.

5 September 2015 ABHISHEK DWIVEDI

POINTERS AND FUNCTIONS Program : Pointers as function Parameters

#include<stdio.h> #include<conio.h> void main() { int a,b; clrscr(); printf Enter numbers: ; scanf %d %d ,&a,&b); printf \nBefore exchange: a=%d, b=%d ,a, b); swap(&a,&b); printf \nAfter exchange: a=%d, b=%d ,a, b); getch(); } void swap(int *x, int *y) { int z; z = *x; *x = *y; *y = z; }

Page 128: Learning c - An extensive guide to learn the C Language

We know that the name of an array stands for the address of its zeroth element. The same thing is true of the names of arrays of structure variables.

Suppose product is an array variable of struct type. The name product represents the address of its zeroth element.

Consider the following declaration:

struct inventory

{

char name[30];

int number;

} product[3], *ptr;

5 September 2015 ABHISHEK DWIVEDI

POINTERS AND STRUCTURES Program: Pointers to Structure variables #include<stdio.h> #include<conio.h> struct invent { char name[20] ; int number; }product[3], *ptr; void main() { clrscr(); printf )NPUT\n\n ; printf Enter name and number records : ; for(ptr = product;ptr<product+3;ptr++) scanf %s %d ,ptr->name,&ptr->number); printf \n\nOUTPUT ; for(ptr = product;ptr<product+3;ptr++) printf \n%s\t%d ,ptr->name,ptr->number); getch(); }

Page 129: Learning c - An extensive guide to learn the C Language

A file is a place on the disk where a group of related data is stored. Like most other languages, C supports a number of functions that have the ability to perform basic file operations, which include:

9 Naming a file,

9 Opening a file,

9 Reading data from a file,

9 Writing data to a file, and

9 Closing a file.

5 September 2015 ABHISHEK DWIVEDI

File Management in C

Page 130: Learning c - An extensive guide to learn the C Language

5 September 2015 ABHISHEK DWIVEDI

High level I/O functions Function Name Operation

fopen() Creates a new file for use Opens an existing file for use.

fclose() Closes a file which has been opened for use.

Getc() Reads a character from a file.

putc() Writes a character to a file.

fprintf() Writes a set of data values to a file.

fscanf() Reads a set of data values from a file.

getw() Reads an integer from a file.

putw() Writes an integer to file.

fseek() Sets the position to a desired point in the file

Ftell() Gives the current position in the file

rewind() Sets the position to the beginning of the file.

Page 131: Learning c - An extensive guide to learn the C Language

If we want to store data in a file in the secondary memory, we must specify certain things about the file, to the operating system. They include:

Filename.

Data Structure.

Purpose.

Following is the general format for declaring and opening a file:

FILE *fp;

fp = fopen filename , mode ;

5 September 2015 ABHISHEK DWIVEDI

DEFINING AND OPENING A FILE

Page 132: Learning c - An extensive guide to learn the C Language

The first statement declares the variable fp as a pointer to the data type FILE . As stated earlier, FILE is a structure that is defined in the I/O library. The second statement opens the file named filename and assigns as identifier to the FILE the pointer fp. This pointer which contains all the information about the file is subsequently used as a communication link between the system and the program.

The second statement also specifies the purpose of opening this file. The mode does this job. Mode can be one of the following:

r open the file for reading only.

w open the file for writing only.

a open the file for appending (or adding) data to it.

Note that both the filename and mode are specified as strings. They should be enclosed in double quotation marks.

5 September 2015 ABHISHEK DWIVEDI

DEFINING AND OPENING A FILE (CONTD…)

Page 133: Learning c - An extensive guide to learn the C Language

When trying to open a file, one of the following things may happen:

When the mode is writing a file with the specified name is created if the file does not exist. The contents are deleted, if the file already exists.

When the purpose is appending , the file is opened with the current contents safe. A file with the specified name is created if the file does not exist.

)f the purpose is reading , and if it exists, then the file is opened with the current contents safe; otherwise an error occurs.

5 September 2015 ABHISHEK DWIVEDI

DEFINING AND OPENING A FILE (CONTD…)

Consider the following statements: FILE *p1, *p2; p1 = fopen data , r ; p2 = fopen results , w ; Many recent compilers include additional modes of operation. They include: r+ The existing file is opened to the beginning for both reading and writing. w+ Same as w except both for reading and writing a+ Same as a except both for reading and writing. We can open and use a number of files at a time. This number however depends on the system we use.

Page 134: Learning c - An extensive guide to learn the C Language

A file must be closed as soon as all operations on it have been completed. The general form is:

fclose(file_pointer);

5 September 2015 ABHISHEK DWIVEDI

CLOSING A FILE

Page 135: Learning c - An extensive guide to learn the C Language

Once a file is opened, reading out of or writing to it is accomplished using the standard I/O routines that are listed.

The getc and putc Functions

The simplest file I/O functions are getc and putc. These are analogous to getchar and putchar functions and handle one character at a time. Assume that a file is opened with mode w and file pointer fp1. Then, the statement

putc(c, fp1);

writes the character contained in the character variable c to the file associated with FILE pointer fp1. Similarly, getc is used to read a character from a file that has been opened in read mode. For example, the statement

c = getc(fp2);

would read a character from the file whose file pointer is fp2.

The file pointer moves by one character position for every operation of getc or putc. The getc will return an end-of-file marker EOF, when end of the file has been reached. Therefore, the reading should be terminated when EOF is encountered.

5 September 2015 ABHISHEK DWIVEDI

INPUT/OUTPUT OPERATIONS ON FILES

Page 136: Learning c - An extensive guide to learn the C Language

PROGRAM #include<stdio.h> #include<conio.h> void main() { FILE *f1; char c; clrscr(); printf Data )nput\n\n ; f1 = fopen )NPUT , w ; while((c=getchar()!=EOF) putc(c,f1); fclose(f1); printf \nData Output\n\n ; f1 = fopen )NPUT , r ; while((c=getc(f1))!=EOF) printf %c ,c); fclose(f1); getch(); } 5 September 2015 ABHISHEK DWIVEDI

Program : Writing to and Reading from a File

Page 137: Learning c - An extensive guide to learn the C Language

The functions fprintf and fscanf perform I/O operations that are identical to the familiar printf and scanf functions, except of course that they work on files.

The first argument of these functions is a file pointer which specifies the file to be used.

The general form of fprintf is

fprintf(fp, control string , list ;

where fp is a file pointer associated with a file that has been opened for writing. The control string contains output specifications for the items in the list. The list may include variables, constants and strings. Example:

fprintf f , %s %d %f ,name,age,7.5 ;

Here, name is an array variable of type char and age is int variable.

5 September 2015 ABHISHEK DWIVEDI

The fprintf & fscanf Functions

Page 138: Learning c - An extensive guide to learn the C Language

The general format of fscanf is

fscanf(fp, control string , list ;

This statement would cause the reading of the items in the list from the file specified by fp, according to the specifications contained in the control string.

Example:

fscanf f , %s %d , item, &quantity ;

Like scanf, fscanf also returns the number of items that are successfully read. When the end of file is reached, it returns the value of EOF.

5 September 2015 ABHISHEK DWIVEDI

The fscanf Function

Page 139: Learning c - An extensive guide to learn the C Language

It is a parameter supplied to a program when the program is invoked. This parameter may represent a filename the program should process.

For example, if we want to execute a program to copy the contents of a file named X_FILE to another one named Y_FILE, then we may use a command line like

C:\TC>PROGRAM X_FILE Y_FILE

PROGRAM is the filename where the executable code of the program is stored. This eliminates the need for the program to request the user to enter the filenames during execution.

5 September 2015 ABHISHEK DWIVEDI

COMMAND LINE ARGUMENTS

Page 140: Learning c - An extensive guide to learn the C Language

We know that every C program should have one main function and that it marks the beginning of the program.

But what we have not mentioned so far is that it can also take arguments like other functions. In fact main can take two arguments called argc and argv and the information contained in the command line is passed on to the program through these arguments, when main is called up by the system.

The variable argc is an argument counter that counts the number of arguments on the command line. The argv is an argument vector and represents an array of character pointers that point to the command line arguments

5 September 2015 ABHISHEK DWIVEDI

How do these parameters get into the program?

The size of this array will be equal to the value of argc. For instance, for the command line given above, argc is three and argv is array of three pointers to strings as shown below: argv[0]Æ PROGRAM argv[1]Æ X_FILE argv[2]Æ Y_FILE In order to access the command line arguments, we must declare the main function and its parameters as follows: main(argc,argv); int argc; char *argv[]; The first parameter in the command line is always the program name and therefore argv[0] always represents the program name.

Page 141: Learning c - An extensive guide to learn the C Language

#include<stdio.h>

#include<conio.h>

void main(argc,argv)

int argc;

char *argv[];

{

FILE *fp;

int i;

char word[15];

clrscr();

fp = fopen(argv[1],"w");

printf("\nNo.of arguments in Command line=%d\n\n",argc);

5 September 2015 ABHISHEK DWIVEDI

Program : Command line Arguments

for(i=2;i<argc;i++) fprintf(fp,"%s",argv[i]); fclose(fp); printf("Contents of %s file\n\n",argv[1]); fp=fopen(argv[1],"r"); for(i=2;i<argc;i++) { fscanf(fp,"%s",word); printf("%s",word); } fclose(fp); printf("\n\n"); for(i=0;i<argc;i++) printf("%*s\n",i*5,argv[i]); getch(); }

Page 142: Learning c - An extensive guide to learn the C Language

Write your feedback to [email protected]