Introduction to c



Download 0.91 Mb.
Page4/13
Date28.05.2018
Size0.91 Mb.
#51782
1   2   3   4   5   6   7   8   9   ...   13
Format Codes

Character

%c

String

%s

Signed Integer

%d

Unsigned Integer

%u

Floating Point (decimal notation)

%f

Floating Point (Scientific notation)

%e

Unsigned Hexadecimal Integer

%x

Unsigned Octal Integer

%o

Signed Long Integer

%ld

Unsigned Long Integer

%lu

Double

%lf

Long double

%Lf

e.g.:- printf(“Name = %s and Age = %d \n”, name, age ) ;

Modifiers for Format Codes

The format commands/codes can have modifiers, to suitably modify the basic conversion specifications. A format can have more than one modifier.

This modifier can be used with int, float, double and string. The field width modifier is an integer value, which defines the minimum field width for the data item. Data items of smaller width will be output right justified by default. Larger data items will be printed as it is.

e.g.:- printf(“[%10d]”,456) will be printed as [ 456].

By default the data item will be printed as right justified within its field width. By using the ‘—’ modifier, the data item will be left justified within its field width.

e.g.:- printf(“[%—d]”,456) will be printed as [456].

e.g.:- printf(“[%—10d]”,456) will be printed as [456 ].

This modifier can be used with float, double or string type data. The modifier is used as ‘.n’, where ‘n’ is an integer. If precision modifier is used with data type float or double the digit string indicates the maximum number of digits to be printed to the right of the decimal. When used with a string it indicates the maximum number of characters to be printed.

If the fractional part of a float or double type data item exceeds the precision modifier, then the number will be rounded. If a string length exceeds the specified field length then the string will be truncated.

e.g.:- printf(“[10.3f]”,456.56); will print [ 456.560]

printf(“[10.3]”, “ajith” ); will print [ aji]

By default the leading zeroes are padded with spaces. If you use 0 (zero) modifier the leading spaces will be padded with zeroes instead of blanks (spaces).

e.g.:- printf(“[010.3f]”,456.56); will print [000456.560]

This modifier can be used to display integers as long int. For example the format code for long int is %ld.

If the user does not want to specify the field width and precision in advance, but wants through the program, this modifier can be used. But along with this modifier an argument, which tells the width or precision, should be included for each * modifier.

e.g.:- printf(“ %*s ”, w, name);

printf(“ %*.*s ”, w, p, name); where w and p are integer values representing field-width and precision.

syntax: scanf(“ control string ”, argument-list);

While printf() uses variable names, constants, expressions(calculations), functions as the arguments scanf() uses the addresses of variables in the memory. Precede the variable name with an &(address of ) operator with all types except string (arrays) because it is a derived data type. All the format codes are exactly same for the scanf() also.

e.g.:- scanf( “ %d %s”, &age, name);

scanf( “%10s”, name);

scanf() uses non-printing characters like blank(space), tab, newline (Enter Key) to decide when an input field ends and another input field begins.

Multi-Dimensional Arrays

A multi-dimensional array requires a separate pair of square brackets for each dimension. i.e., a two dimensional array will require two pairs of square brackets, and a three-dimensional array will require three pairs of square brackets and so on.

A two-dimensional array can be treated as an array of single dimensional arrays.

syntax : data-type array-name [rows][columns] ;

e.g.:- int arr[3][4]; char names[10][25]; etc.

Each dimension of the array is subscripted (indexed) from 0(zero) to its maximum size minus one. The first subscript selects the row and the second subscript selects the column within that row.

Multi-dimensional arrays can be initialised as follows,

int arr[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};

The initialising rule is that the last subscript increases most rapidly, and the first subscript increases least rapidly. Thus the elements of a double-dimensional array will be assigned by rows. i.e., the elements of the first row will be assigned, then the elements of the second row and so on.

The initialisation can be done row by row,

i.e., int arr[3][4]={ {1,2,3,4}, {5,6,7,8}, {9,10,11,12} };

i.e., surrounding the elements of each row by braces.

A two-dimensional array can also initialised in the form of a matrix.

i.e., int arr[3][4]={ {1,2,3,4},

{5,6,7,8},

{9,10,11,12}

};

Commas are required after each brace that closes off a row, except in the case of last row. We can access the elements of a two-dimensional array using row and column subscripts.



e.g.:- arr[2][3]++; printf(“%d”, arr[1][3]); scanf(“%d”, &arr[2][2]); etc.

A string (character) array can be initialised as follows,


char names[3][10]={{‘H’,’e’,’l’,’l’,’o’,’\0’},{‘E’,’v’,’e’,’r’,’y’,’\0’},{‘B’, ’o’, ’d’, ’y’, ’\0’} };

OR

char names[3][10]={“Hello”, ”Every”, ”Body”};



OR

char names[3][10]={ “Hello”,

“Every”,

“Body”


};

You can access each character (element) in the array using subscripts.


e.g. :- printf(“%c”, names[1][2]); will return e.

To access the contents as strings use the row subscript only


e.g.: - printf(“%s”, names[1]); will print Every and
scanf(“%s”, names[2]); will read data to the third row.

Operators

Operators are used in programs to manipulate data and variables. An operator is a symbol that tells the computer to perform certain mathematical or logical operation. Operators operate on constants or variables, which are called operands. In ‘C’ operators are classified Unary, Binary and Ternary operators act on three data elements.

They are classified into two classes, binary arithmetic operators and unary arithmetic operators.

They are,



+ Addition

— Subtraction



/ Division

* Multiplication

% Modulus (remainder)

The modulus operator, % is used to obtain the remainder after integer division.



e.g.:- printf(“ %d “, 13%5); will print 3.

Both the operands of modulus operator must be integer.

They are unary minus (—), unary plus (+), the increment operator (++) and the decrement (– –). The unary plus and minus operators used to show the signs of the numeric data elements. e.g.:- a= –12; b= –a;

The increment operator (++) adds 1 to the operand while the decrement operator (– –) subtracts 1. These can be placed on both sides of the operands. i.e., ++m; m++;

When they form statements independently they mean the same. ie., ++m; and m++; both are equivalent to m=m+1.But the behave differently when they are used in expressions on the right-hand side of an assignment statement. i.e., prefixing & post-fixing.

eg:- m =5;



y =++m; The value of y and m would be 6.

but in the case of,



m = 5;

y = m++; The value of m would be 6 and y would be 5.

This difference is because a prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. But a post-fix operator first assigns the value to the variable on left and then increments the operand. ie.,



m =5; m=5;

y =++m; is equivalent to m=m+1;

y=m;


m = 5; m=5;

y = m++; is equivalent to y=m;

m=m+1;


sizeof is an unary operator, which returns size of the expression given as the argument.

e.g.:- a = sizeof(int); will store 2 to the variable a.

printf(“ %d ”, sizeof(long int) ); will print 4.

char name[10]; int marks[10];

printf(“ %d -- %d ”, sizeof(name), sizeof(marks) ); will print 10 – 20.

The assignment operators are used to assign the result of an expression to a variable. The default assignment operator is “=”. Turbo C also allows a set of shorthand assignment operators.



syntax : variable operator= numeric_expression

Operator can be any of the binary arithmetic operators. The operator, operator= is known as the shorthand assignment operator.

e.g.:- a += 2; is equivalent to a = a + 2;

a –= 2; is equivalent to a = a – 2;

a *= 2; is equivalent to a = a * 2;

a /= 2; is equivalent to a = a / 2;

a %= 2; is equivalent to a = a % 2;

They are <, <=, >, >=, == (is equal to), != (is not equal to).

A relational expression consists of a combination of relational operators and operands, where an operand can be a constant, a variable or an arithmetic expression.

Every relational expression has a value, which is true or false. If the relation is true, the expression has a value of 1(one) and if the relation is false, it has a value of 0(zero).

They are , && (logical AND),

|| (logical OR) and

! (logical NOT).

Where && and || are binary operators and, ! is an unary operator. These operators can be used to create compound conditions. The && and || have two operands and are usually relational expressions, which have either a true or a false value.

(expr1 && expr2) is true only if both expr1 and expr2 are true, otherwise it is false. (expr1 || expr2) is true if either or both expr1 and expr2 are false, is false only if both expr1 and expr2 are false. ( !expr1) is true if expr1 is false, is false if expr1 is true.



Statements in ‘C’

A statement is a complete instruction to the computer. It indicates a specific action. Statements can be classified into two, i) Simple Statements ii) Compound Statements.

A semicolon at the end indicates simple statements. Simple statements can be either declaration statements like int count, num;, assignment statements like count=10; and function statements like printf( “Hello” );, getch(); etc.

A compound statement is two or more statement grouped together by enclosing them in braces. It is also called a code block. The grouping ensures that either all the statements in the block are executed or none of them are executed. A compound statement is syntactically equivalent to a single statement. But there is never a semicolon after the right brace that ends a block.



If Statement

syntax : if(expression)



statement1;

next statement;

The expression is a relational expression and it should always be enclosed in parentheses. If the expression is true (non-zero), then statement1 is executed. And after that the next statement is executed. If the expression is false (zero), statement1 is not executed and the control passes directly to the next statement.

The statement part of the if (statement1) may be a simple statement or it may be a compound statement. i.e., if more than one statements are to be executed, when the expression becomes true, then you should enclose that set of statements within braces to create a code block or a compound statement.

syntax : if(expression)

{

staement1;



statement2;

…………

statement-n;

}

next statement;

When expression is true, the block of statements are executed sequentially after that, next statement is executed. When condition is false the compound statement block is skipped and next statement is executed.

syntax: if( expression )

statements1;

else


statements2;

The statements, statements1 and statements2 both can be a simple statement or a compound statement enclosed in braces. If the expression evaluates to true (non-zero), statements1 is executed. If it is false (zero) then statements2 is executed.

eg:-

# include



main()

{

int x;


printf(“Enter a number : ”);

scanf(“%d”, &x);

if(x>10)

printf(“x is greater than 10”);

else

{

printf(“The condition is false”);

printf(“ x is less than or equal to 10”);

}

getch();


}

The While Loop

syntax : while( condition )



statement1;

next statement;

The condition to be tested must be enclosed in parentheses. The loop continues until the condition becomes false. Then the control goes to the statement immediately follow the code block. ie., next statement;



e.g.(1)

# include

main()


{

int i=0;


while(i<=10)

{

printf(“%d \n”, i);

i++;

}

printf(“loop completed”);

getch();

}
e.g.:- (2)
# include

main()


{

char name[20];

int x=0;

printf(“Enter your name : “);

scanf(“%s”, name);

while(name[x]!=NULL)



{

printf(“%c\n”,name[i]);

i++;

}

printf(“That is the loop”);

getch();

}

The for loop

syntax : for( initialise counter; conditional test; re-evaluation parameter)



statements ;

The for statement specifies three expressions in a single line, to control the looping process. These expressions should be separated by semicolons and should be enclosed in parentheses.

The three expressions are,

(i) The initial value of the counter

(ii) The conditional test for exiting the loop

(iii) The expressions used to give the counter a new value.

The statement, which forms the body of the loop, can be either a simple statement or a compound statement. The initialise counter is executed only once, before any of the loop statements are executed. Then the conditional test is performed. If this expression is true (non-zero), the statements of the loop are executed once. Then counter is assigned new value using the re-evaluation parameter. The conditional test is repeated again, using the new value of the counter. The loop is repeated until the conditional test becomes false (zero).

The while loops and for loops is entry-condition loops. i.e., The condition will be checked before the statements of loop are executed (pre-checking). Therefore there is a possibility that the loop is never traversed.

Any of the three parts of the for loop can be omitted. Although the semicolons must remains. If all the three are omitted then the loop becomes an infinite loop.

e.g.:- for( ; ; )

statements;

The body of the loop can be empty. ie., all of the work is done in the test and increment parts. But the grammatical rules of ‘C’ require that loop statements have a body. Then you can use only a semicolon, called the NULL statement as the body of the loop.

e.g.:- for(x=1; x<=10; x++)

;

This loop will work until the value of x becomes greater than 10 and no other result will be produced. This can be also represented as

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

Therefore placing a semicolons at the end of a for loop will not create an error in ‘C’.

You can include more than one initialisation or re-evaluation expressions in the for loop using the comma operator.

eg:- for(x=1, j=1; str[x]!=NULL; x++, j++)

statements;

BREAK Statement

The break statement in ‘C’ provides an early exit (ie., exit from the loop without testing the loop condition) from the for, while and the dowhile loops, and also from the switch statement.



syntax : break;

When the break statement is encountered in a ‘C’ program, control passes immediately to the first statement after the loop. Usually break statement is associated with an if statement which enables a condition to be tested.



CONTINUE Statement

syntax : continue;

The continue statement causes the next iteration of the enclosing loop to begin. When this statement is encountered, the remaining statements in the body of the loop are skipped and the loop starts again after checking the condition. Usually continue statement is used with an if statement.



The DO…WHILE Loop

syntax :

do

statement1;

while(condition);



next statement;

The statement can be either simple statement or compound statement. This loop is also called do loop/statement. do..while loop is an exit condition loop(post-test).i.e., the test condition is evaluated only after the loop has been executed. Thus the loop will be executed at least once.

The statement is first executed, then the condition is checked. If it is true (non-zero), the control is transferred to the do statement and the process is repeated. When the condition becomes false (zero), then control is transferred to the next statement following the loop statement.

The Switch Statement

The switch statement is a special multi-way decision-maker that tests whether an expression matches, one of a number of constant values, and branches accordingly.

syntax :

switch(expression/variable)



{

case value1 :



statement1;

break;


case value2 :

statements2;

break;


…………….

[default :

statements-n;]

}

next statement;

Where switch, case and default are the keywords and statements1, statements2, statements-n can be simple statements or a compound statement, which need not be enclosed in braces.

The expression following the switch must be enclosed in a pair of parentheses and the body of switch should be enclosed within braces. The body consists of many case labels (i.e., value1, value2, etc.) each one of which has an action associated with it. The type of the expression given and type of case labels should be compatible. Each case must be labelled by an integer or character constant or constant expression, which does not consist of any variable names. Case labels must be unique.

In the switch statement, the expression is evaluated, and the value is compared with the case labels in the given order. If a label matches with the value of expression, the statement(s) mentioned against it will be executed. The break statement at the end of each block signals the end of the particular case and causes an exit from the switch statement, transferring the control to the next statement following the closing brace of the switch statement.

If you don’t use the break statement after each action. The execution falls through to the next. i.e., every statement from the matched label to the end of the switch will be processed.

The statements against default will be executed, if none of the other cases is satisfied. The default part is optional.



The Conditional Operator (?:)

This operator provides conditional execution of statements and it has two parts, ‘?’ and ‘:’. This operator is a ternary operator and operates upon three operands.



syntax: condition?expression1:expression2

The condition is evaluated and if the result is true (non-zero) expression1 is evaluated, else if the condition becomes false (zero) then the expression2 is evaluated. Only of the expressions will be executed. You can mix this operator to create complex equations.



E.g.: - To find out the largest among the three numbers.

# include

void main()



{

int a=10,b=20,c=16,large;

large = (a>b)?(a>c)?a: c: (b>c)? b: c;

printf(“largest number : %d”, large);



}

Functions

A function is a self-contained program segment that carries out a specific, well- defined task. C functions can be classified into two categories, Library functions and User-defined functions. Printf and scanf are examples of library functions and main() is an example of user-defined functions.

A program can be modularised through the use of user-defined functions. Large and complicated programs can be divided into functional parts, then make it easy for testing, debugging and maintaining. Functions should be written independent of system dependent feature, making more portable. The same function can be called from many points, there by avoiding repetition of code.

A function definition is subdivided into three main components



  • Function header

  • Argument declarations

  • Body of the function

General form of function definition is as follows

data-type name(arguments)

argument declarations;

{

statements;

return(<expr>);

}

The function header consists of function storage class, function Datatype, function name and set of arguments separated by commas, enclosed in parentheses. A pair of empty parentheses must follow the function name if the function definition does not include any arguments. Arguments are declared outside the body of the functions, before the first compound statement.



e.g.:-

int max(m, n)

int m, n;

{

statements;

return;

}

But ANSI standard allows the user to combine the function header and argument declarations all in one line.



e.g.:-

int max(int m, int n)



{

statements;

return;

}

These arguments allow data to be transferred from the calling statement to the function. Function body consists of a compound statement, which must be enclosed within braces. A function can be called by using the function name followed by a list of actual arguments enclosed in parentheses in a statement.




Download 0.91 Mb.

Share with your friends:
1   2   3   4   5   6   7   8   9   ...   13




The database is protected by copyright ©ininet.org 2024
send message

    Main page