• No results found

c notes 2-1

N/A
N/A
Protected

Academic year: 2021

Share "c notes 2-1"

Copied!
28
0
0

Loading.... (view fulltext now)

Full text

(1)

Tokens: In a passage of text, individual words and punctuation marks are called tokens or lexical units. Similarly, the smallest individual unit in a c program is known as a token or a lexical unit. C tokens can be classified as follows:

1. Keywords 2. Identifiers 3. Constants 4. Strings 5. Special Symbols 6. Operators

Variables: A variable is a name given to the memory location. EX: For-is a valid variable

for-is a invalid variable.

Data Type:

C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location.

(2)

provide useful output. The task of data processing is accomplished by executing series of commands called program. A program usually contains different types of data types (integer, float, character etc.) and need to store the values being used in the program. C language is rich of data types. A programmer has to employ proper data type as per his requirements. C has different data types for different types of data and can be broadly classified as:

1. Primary Data Types(Primitive) 2. Secondary Data Types(non Primitive) 3. User defined data types

Integer Data Types:

Integers are whole numbers with a range of values, range of values are machine dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for number. To control the range of numbers and storage space, C has three classes of integer storage namely short int, int and long int. All three data types have signed and unsigned forms. A short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned integers are always positive and use all the bits for the magnitude of the number. Therefore, the range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a longer range of values and it occupies 4 bytes of storage space.

Syntax:

int <variable name>; int num1;

short int num2; long int num3; Example: 5, 6, 100, 2500.

Integer Data Type Memory Allocation:

Floating Point Data Types:

The float data type is used to store fractional numbers (real numbers) with 6 digits of precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision and takes double space (8 bytes) than float. To extend the precision further we can use long double which occupies 10 bytes of memory space. Syntax:

(3)

float <variable name>; float num1;

double num2;

long double num3; Example: 9.125, 3.1254.

Floating Point Data Type Memory Allocation:

Character Data Type:

Character type variable can hold a single character and are declared by using the keyword char. As there are singed and unsigned int (either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have values between 0 and 255, signed characters have values from –128 to 127.

Syntax:

char <variable name>; char ch = ‘a’;

Example: a, b, g, S, j.

Void Type:

The void type has no values therefore we cannot declare it as variable as we did in case of integer and float. The void data type is usually used with function to specify its type.

User defined Data Type

User can create his own data type for handling data that does not fit in one of the existing data types. Programmer can create an identifier that denotes an already existing data type with the help of a user defined data type. The programmer defined data type identifier is then used in a program to declare variables. In short its purpose is to redefine the name of an existing data type. Syntax: typedef;

Enumerated Data Types

Enumerated data types are a user defined ordinal data type. The main purpose of the enumerated data type is to allow numbers to be replaced by words. This is intended to improve the

(4)

Enumerated Data Type (enum) : An Enumerated data type consists of an ordered set of distinct constant values defined in a data type in a program. The format of en-um is:-

enum name {

value-l,value-2,value-3, ... ,value-4; };

where., name is the name of the enumerated data type, also known as tag and value-l,value-2,value-3,……,value-n are values that variable of type name can take.

enum fruit {

a pple,orange,mango, pineapple; };

This declaration states that a variable of type fruit can have any of the four values namely apple, orange, mango and pineapple, but no other value. Once the type fruit has been defined then variable of that type can be defined in the following manner :-fruit a,b;

Now, the variable a and b are of type fruit and can assume value from the list : (apple, orange, mango, pineapple).

Example (2): -

Part-1 enum days

{

mon,tue,wed,thu,fri,sat,sun;

};

Part-2 days holiday,wdays;

The first part defines an enumeration named days. The second part declares the variables holiday and wdays to be enumeration variable of type days. Thus each variable can be assigned any one of the constants mon,tue,wed,thu,fri,sat,sun.

The two parts in example-2 can be combined if desired, resulting in enum days

{

mon,tue,wed,thu,fri,sat,sun; } holiday,wdays; or without the name(tag), simply enum { mon,tue,wed,thu,fri,sat,sun; } holiday,wdays;

Enumeration constants are automatically assigned equivalent integer values, beginning with 0 for the first constant, with each successive constant increasing by 1. Therefore in example-1, the enumeration constants will represent the following integer values: -

Mon 0 Tue 1 Wed 2

(5)

Thu 3 Fri 4 Sat 5 Sun 6

These automatic assignments can be overridden by assigning explicit integer values which differ from the default values. Those constants are not assigned explicit values will automatically be assigned values which increase successively by 1 from the last explicit assignment.

enum days { mon=10; tue=ll; wed=12; thu=13 fri=20; sat=21; sun=50; };

Operations on Enumerated Data Types • Assignment

example: - holiday=sun; 2. Comparing using Relational Operators Example: - Consider the enumerated data types defined in previous example: -

Expression values

sun<tue false

mon!=fri true

Advantages of Enumerated Data Types  Simplifies the Program.

 enhances the readability of the program.  Help to locate more errors at the compile time.  Helps us to express a program in a more natural way.

OR

 enum is short form of enumeration

 enumeration consists of a set of named integer constants. ieenumeration is a list of constant integer values.

(6)

 Syntax for enum declaration is

Enum identifier {value1,value2,...value n}

 The identifier is a user defined enumerated datatype which can be used to declare variables that have one of the values enclosed with in the braces.

 after the declaration,we can define variables with this new type as enum identifier v1,v2,v3....vn

 The enumerated variables v1,v2,v3...vn can have only one of the values value1,value2....value n.

 Example declaration

enum day {Monday,Tuesday,Wednesday,Thursday,Friday,Saturday}; definition

enum day day1,day2,day3;

day1=Monday; day2=Friday;

day3=Sunday;//Error because sunday is not in the enum definition

 The first name in an enum has value 0, the next has value 1 and so on,unless explicit values are specified.

 In the above example Monday is assigned to 0,Tuesday is assigned to 1 and so on and Saturday is assigned to 5 internally.

 we can also explicitly assign a value to the set

enum day {Monday,Tuesday=0,Wednesday,Thursday,Friday,Saturday};

The value 0 is associated with Monday by default.ThenTuesday is explicitly set to 0.so Wednesday is set to 1 and so on.

Points to consider:

1. To explicitly assign an integer value to a variable of an enumerated data type,use a type cast

enum day today;

today=(enum day)Monday; now today has value 0

2. In declaration, enum identifier {value1,value2,...value

n};value1,value2...valuen must all be distinct from each other and different from ordinary variable names,but the values need not be distinct.

enum student1 {Anand=0,Ashok,Alex} Boys; enum student2 {skippy=0,slowvy,Ashok} Girls;

(7)

The above code will create an compiler error because 'Ashok' is available in both the list.

3. Enum is a set of named integer constant.so while printing the enum members the integer values only printed, Sometimes we need to print the actual name of the enum value for troubleshooting.But we cant directly print the enum members using %s.we can use switch statement or if-else to print the enum values.But if the enum consist of more than 100 constants then the program becomes very large. A simple strategy is to use array of strings(char *)

Example program to print the enum data #include<stdio.h>

enum new_enum{sunday,monday,tuesday,wednesday,thursday,friday,saturday}; const char *enum_names[]={"sunday","monday","tuesday","wednesday","thursday","f

riday","saturday"};

int main()

{

enum new_enum e1,e2; e1=sunday; e2=monday; printf("day1=%s\n",enum_names[e1]); printf("day2=%s\n",enum_names[e2]); return 0; } Output day1=sunday day2=monday

Redefining Data Types with typedef

The type definition statement is used to allow user defined data types to be defined using other already available data types.

Basic Format:

typedef existing_data_type new_user_define_data_type; Examples:

typedef int Integer;

The example above simply creates an alternative data type name or “alias” called Integer for the built in data type called “int”. This is generally not a recommended use of the typedef statement.

typedef char Characters [ WORDSIZE ]; /* #define WORDSIZE 20 */

The example above creates a user defined data type called Characters. Characters is a data type that supports a list of “char” values. The fact that this user defined data type is an array of WORDSIZE is now built into the data type.

(8)

Characters One_String; /* [ ] and WORDSIZE are not specified */ /* this also applies to argument list use */

A string value is different from an array of characters in that it can be processed as a list of individual characters like an array of characters or it can be processed as a string of characters or a single word unlike an array of characters. In order to be processed as a string value the list of characters must be terminated by placing a special character in the array just after the last character in the string value. This character is called the NULL character and is represented by „\0‟ in C.

typedef char String [ WORDSIZE + 1 ];

The user defined data type called String has a maximum size of WORDSIZE + 1.

The extra position is so that there is room to store the NULL character in addition to the other characters in the string value.

String Word_1; /* uninitialized array of characters – no „\0‟ */

String Word_2 = { „\0‟ }; /* initialized empty string – „\0‟ position 0 */ String Word_3 = { “” }; /* initialized empty string – „\0‟ position 0 */

String Word_4 = { „H‟, „I‟, „\0‟ }; /* initialized „H‟ „I‟ „\0‟ – positions 0, 1, 2 */ String Word_5 = { “HI” }; /* initialized „H‟ „I‟ „\0‟ – positions 0, 1, 2 */

Using the “…” double quotation marks tells the compiler that you are using a string value. When assigning string values to string variables using the double quotation marks the NULL character is automatically inserted at the end of the string value.

Word_1 = “Hello”; /* „H‟ „e‟ „l‟ „l‟ „o‟ „\0‟ – positions 0, 1, 2, 3, 4, 5 */ /* string assignment not supported – strcpy required */

scanf( “%s”, Word_3 ); /* Stores character sequence typed at the keyboard */ /* NULL character is added to the end */

fscanf( InFile, “%s”, Word_4 ); /* Value read from external file */ /* Terminates with white space or end-of-line */

printf ( “Hello” );

printf ( “%s”, Word_4 ); /* Works the same way as outputting a string value */

In order to correctly process string values in C you must include “string.h”. This contains a special set of functions/operations that work with arrays of characters that contain string values that are terminated by the NULL character.

strcpy ( string_value_variable, string_value ); /* String Copy */ strcpy ( Word_1, “Happy” ); /* Word_1 = “Happy”; */

strcpy ( Word_1, Word_5 ); /* Word_1 = Word_5; */

The strcpy function is required because the assignment of any kind of array is not supported with C.

(9)

The strcmp function returns a value based upon the result of the comparison of the two string values.

Negative – if the first string value is less than the second string value.

Result = strcmp ( “Apple”, “Baker” ); /* „A‟ (65) < „B‟ (66) */ Zero – if the first string value is equal to the second string value. Result = strcmp ( “Apple”, “Apple” ); /* all characters match */

Positive – if the first string value is greater than the second string value. Result = strcmp ( “Baker”, “Apple” ); /* „B‟ (66) > „A‟ (65) */

The strcmp function is required because relational operations are not supported with strings.

int strlen ( string_value ); /* String Length */

The strlen function returns the length of the string value. The strlen function returns the number of individual characters contained in the string value. The length is indicated by the position that the NULL character is stored in.

Basic structure of C program

C language is very popular language among all the languages. The basic structure of a Clanguage. The structure of a C program is a protocol (rules) to the programmer, while writing a C program. The general basic structure of C program is shown in the figure below. The whole program is controlled within main ( ) along with left brace denoted by “{” and right braces denoted by “}”. If you need to declare local variables and executable program structures are enclosed within “{” and “}” is called the body of the main function. The main ( ) function can be preceded by documentation, preprocessor statements and global declarations.

(10)

Documentations

The documentation section consist of a set of comment lines giving the name of the program, the another name and other details, which the programmer would like to use later.

Preprocessor Statements

The preprocessor statement begin with # symbol and are also called the preprocessor directive. These statements instruct the compiler to include C preprocessors such as header files and symbolic constants before compiling the C program. Some of the preprocessor statements are listed below

Preprocessor statements are processed before the source program is handed over to the compiler. They are placed in a source program before the function main. The various preprocessor

directories are:

1) Symbolic Names:

An identifier is replaced by sequence of characters which may represent a constant or string. These identifiers (also called symbolic names) are associated with constants and hence they are called symbolic constant. The syntax of macro definition for symbolic name is

#define Name String Ex: #define PI 3.142

This instructs the compiler that whenever PI is used in the program, it is replaced by the constant 3.142.

2) Macro Substitution:

The symbolic names can also be used to define the macros. Ex: consider the macro definition as shown below

#define square(x) (x*x)

Whenever square appears in the program with the x as a parameter it is replaced by (x) (x*x)

(11)

#include<stdio.h> #include<conio.h> Void main() {

int m=10,n=5;

printf(“5 square is =%d\n”,square(n)); printf(“10 square is=%d\n”,square(m)); printf(“10+5 square is =%d\n”,square(m+n)); getch(); } Output: 5 square is=25 10 square is=100 10+5 square is =65

The two answers are correct and the square of 10+5 is 65 which is wrong. The correct answer is 225. Note that when macro SUARE (m+n) is called the actual replacement will be (10+5*10+5). To get the correct square the actual definition can be modified by placing the brackets as shown below

#define square((x)*(x))

By doing these changes to the macro definition if we execute the above program the output is

5 square is=25 10 square is=100 10+5 square is =225

3) File inclusion:

It is a process using which the external files containing functions and definitions are included in C programming. This avoids the rewriting of functions and macros. Any external file can be include #include directory.

This syntax is #include file name EX: #include<fact.c)

Ex:#include<stdio.h>

The above information instructs the compiler to include an entire file into the user program.

Ex: let us write a small program to find square of number with the file inclusion. Type the following program; assume the name of the file “square.c”. This file contains only one statement as shown below

(12)

Type the following program by including the previous file square.c as shown below #include<stdio.h> #include “square.c” Void main() { int m=10,n=5;

printf(“5 square is =%d\n”,SQUARE(n)); printf(“10 square is=%d\n”,SQUARE(m)); printf(“10+5 square is =%d\n”,SQUARE(m+n)); getch();

}

4) Conditional Compilation:

Enables the coder to control the execution of preprocessor directives and the compilation of the program code. Conditional preprocessor directives evaluate constant integer expression. The one that cannot be evaluated in the preprocessor directives are size of expressions and Enumeration constants.

Global declaration:

The variables are declared before the main ( ) function as well as user

defined functions are called global variables. These global variables can be accessed by all the user defined functions including main ( ) function.

Main ():

Each and Every C program should contain only one main ( ). The C program execution starts with main ( ) function. No C program is executed without the main function. The main ( ) function should be written in small (lowercase) letters and it should not be terminated by semicolon. Main ( ) executes user defined program statements, library functions and user defined functions and all these statements should be enclosed within left and right braces.

Execution of C program starts from main (). No program is executed without main () function. Main is collective name given to a set of statements. All statements belonging to main are enclosed within braces. The main function does not terminate with a semicolon. Their must be one and only one main function in every C program.

Braces:

Every C program should have a pair of curly braces ({, }). The left braces indicates the beginning of the main ( ) function and the right braces indicates the end of the main ( ) function. These braces can also be used to indicate the user-defined functions beginning and ending. These two braces can also be used in compound statements.

(13)

Local Declarations

The variable declaration is a part of C program and all the variables are used in main ( ) function should be declared in the local declaration section is called local variables. Not only variables, we can also declare arrays, functions, pointers etc. These variables can also be initialized with basic data types. For examples.

main() { int sum=0; int x; float y; }

Here, the variable sum is declared as integer variable and it is initialized to zero. Other variables declared as int and float and these variables inside any function are called local variables.

Program statements

These statements are building blocks of a program. They represent instructions to the computer to perform a specific task (operations). An instruction may contain an input-output statements, arithmetic statements, control statements, simple assignment statements and any other statements and it also includes comments that are enclosed within /* and */ . The comment statements are not compiled and executed and each executable statement should be terminated with semicolon.

User defined functions

These are subprograms, generally, a subprogram is a function and these functions are written by the user are called user ; defined functions. These functions are performed by user specific tasks and this also contains set of program statements. They may be written before or after a main () function and called within main () function. This is an optional to the programmer.

(14)

Operators:

C has a large number of built in operators. An operator is a symbol which acts on

operands to produce certain result as output. The data items on which operators act

upon are called „operands‟ For example in the expression a+b; + is an operator, a

and b are operands. The operators are fundamental to any mathematical

computations.

Based on the number of operands the operator acts upon, Operators

can be classified as follows:

Unary operators: acts on a single operand. For example: unary minus(5,

-20, etc), address of operator (&a)

Binary operators: acts on two operands. Ex: +, -, %, /, *, etc

Ternary operator: acts on three operands. The symbol ?: is called ternary

operator in C language. Usage: big= a>b?a:b; i.e if a>b, then big=a else

big=b.

Based on the functions, operators can be classified as given below

Arithmetic Operators: Arithmetic operators are used to perform numerical

operators in C. They are divided into two classes namely, Unary and Binary

arithmetic operators.

Unary operators:

An operator which adds on only one operand to produce the result is called unary operator.

EX: *a, -9, &c are all expressions with unary operators.

Binary operator: An operator which adds on two operands to produce the result is called binary operator.

(15)

EX: c+d, d%c, x/y are all expressions with binary operators.

Arithmetic Operators: C provides all the basic arithmetic operators, they are +, -, *, /, % Integer division truncates any fractional part. The modulo division produces the remainder of an integer division.

Eg: a + b a – b a * b -a * b a / b a % b

Here „a‟ and „b‟ are variables and are known as operands. % cannot be used for floating point data. C does not have an operator for exponentiation.

Integer Arithmetic: When the operands in an expression are integers then the expression is an integer expression and the operation is called integer arithmetic. This always yields an integer value. For Eg. a = 14 and n = 4 then

a - b = 10 Note : During modulo division,the a + b = 18 sign of the result is always the sign a * b = 56 of the first operand (the dividend ) a / b = 3 - 14 % 3 = -2

a % b = 2 -14 % - 3 = 2 14 % -3 = 2

Write a program to illustrate the use of all Arithmetic operator main ( )

{

int sum, prod , sub, div, mod, a, b ; printf(“Enter values of a, b :”) ; scanf(“ /.d %d”, & a, & b) ; sum = a+b ; printf(“sum = %d”, sum); sub = a-b; printf(“sub = %d”, sub); prod = a * b ; printf(“prod = %d”, a* b); div = a/b;

printf(“ Div = %d”, div); mod = a % b ;

printf(“ mod = %d”,a % b); }

Real Arithmetic / Floating Pont Arithmetic:

Floating Point Arithmetic involves only real operands of decimal or exponential notation. If x, y & z are floats, then

(16)

y = -1.0/3.0 = 0.333333 z = 3.0/2.0 = 1.500000

% cannot be used with real operands

Mixed mode Arithmetic: When one of the operands is real and the other is integer the expression is a mixed mode arithmetic expression.

Eg: 15/10.0 = 1.500000 15/10 = 1

10/15 = 0

-10.0/15 = -0.666667

Type conversion:

In C language we can convert the data from one data type to another data type. Sometimes the compiler itself converts the data from one data type to another data type. This type of processing one data type to another data type is called type conversion. It is done using 2 methods:

 Implicit conversion  Explicit conversion

The process of conversion of lower data type to higher data type automatically by the compiler is called promotion or implicit conversion. The rules followed by compiler during implicit conversion as shown in below table

Operand 2 Lower

data type

Char int long int float double Higher data type char Char int long int float double

int int int long int float double long int long int long int long int float double float float float float float double double double double double double double Higher data type Lower data type

If operand 1 is =int and operand 2=double observe from table that the operand is promoted to double. Lower data type is converted to higher data type.

Modes of expressions:

 Integer expression  Floating point expression  Mixed mode expression

(17)

Arithmetic Operator Procedure:

BODMAS: Bracket Of Division Multiplication Addition Subtraction. Ex:

2*(a%5)*(4+ (b-3)/(c+2)) Where a=8 b=15 & c=4 2*(8%5)*(4+ (15-3)/ (4+2)) 2*3*4+ (12/6) 2*3*4+2 2*3*6 36

Relational Operators:

Relational operators Priority Associativity < 1 LR <= 1 LR > 1 LR >= 1 LR = 2 LR != 2 LR

Precedence of operators:

1. Evaluate the expressions within the brackets. 2. Evaluate unary operator.

3. Evaluate arithmetic expressions. 4. Evaluate relational expression. Ex: 100/20<=10-5+100%10-20=5>=1! =20 5<=10-5+100%10-20=5>=1! =20 5<=10-5+0-20=5>=1! =20 5<=-15=5>=1! =20 0=5>=1! =20 0=1! =20 0! =20 1

Logical operators:

Logical operators Priority Associtaivity

(18)

|| 3 LR

! 1 LR

Relational and logical expressions:

1. Evaluate the expression within brackets. 2. Evaluate unary operators.

3. Evaluate arithmetic expressions. 4. Evaluate relational expressions. 5. Evaluate logical expressions. Ex:

Evaluate a+2>b&&! c||a! =d&&a-2<=e where a=11 b=6 c=0 d=7 e=5 a+2>b&&!c||a!=d&&a-2<=e 11+2>6&&! 0||11! =7&&11-2<=5 13>6&&! 0||11! =7&&9<=5 1&&! 0||1&&0 1&&! 0||0 1&&! 0 1

Assignments operator:

An assignment operator is used to form an assignment expression which assigns the value to the identifier.

OR

An operator which is used to copy the data or result of an expression into memory location is called assignment operator. Copy or storing into memory location is called assigning and hence the name. The assignment operator is denoted by „=”.

The syntax is

Variable=expression;

Ex: a=b; //The value of b is stored in a.

A=L*B //compute the expression L*B and store result in A.

Pi=3.1416 //store the number 3.1416 in Pi or assigning a constant value.

Various form of assignment operators:

Operator Expression Output

+= i=i+1 i+=1 -= i=i-1 i-=1 *= i=i*1 I*=1 /= i=i/12 i/=12 %= i=i%5 i%=5

Multiple assignments:

Assigning a value or set of values to different variables in one statement is called multiple assignment statement. The assignment operator along with shorthand assignment operator can be assigned a single value more than one variable using single statement.

(19)

Ex: a=b=c=10;

The value of 10 is copied into variable c, b and a from right to left. The statement which uses multiple assignment operator is evaluated from right to left. The following table shows various multiple assignment statements and corresponding values of those variables after the execution. Assume d=10 and a=5

Multiple statement Result

a=(b=c=d=d+1) d=11, c=11, b=11, a=11

a+=b=(c=d) d=10, c=10, b=10, a=15

b=a+=d d=10, a=15, b=15

Since evaluation always starts from right to left when the multiple assignments operators are used, multiple assignment operators are right associatively operators.

Increment and decrement operators:

These operators are unary operators and have only one operand. If increment or decrement operator is placed after the variable they are referred as post increment or post decrement operators respectively. In pre incrementing a variable causes the variable to be incremented (decremented) by 1. Then the new value of variable is used in expression in which it appears. Post incrementing (decrementing) the variable causes the current value of the variable to be used in an expression in which it appears then the variable value is incremented by 1.

Post increment:

If an increment operator ++ is placed after the operand then the operator is called post increment. Ex: Void main ( ) { int a=20; a++; Printf(“%d”,a); } Output: a=21

Pre increment:

If an increment operator placed before the operator then the operator is called pre increment.

(20)

Void main ( ) { int a=20; ++a; Printf(“%d”,a); } Output: a=21

Observe that in the above post increment and pre increment example outputs of the program are same. In this context there is no difference between pre increment and post increment if pre increment and post increment operators along with the operand and not the part of the expression then there is no difference in the fixed value but there is difference if they are part of an expression or part of an assignment statement.

In a post increment the value of „a‟ is used in the below example, first „a‟ is copied into „b‟ then „a‟ is added by 1. Void main ( ) { int a=20, b; b=a++; Printf(“%d”,a); Printf(“%d”,b); } Output: a=20 b=21

In case of pre increment the value of „a‟ is used first, „a‟ is added by 1 and then value is copied into „b‟. Void main ( ) { int a=20, b; b=++a; Printf(“%d”,a); Printf(“%d”,b); } Output: a=21 b=21

Conditional operators:

Conditional operator is used in conjunction with relational expression. There is only one such operator in C that takes 3 operands. It is also called as ternary operator. The symbol ? is used as conditional operator in C.

(21)

The general syntax of a conditional operator is given below <Expression>? <Value 1> :< value 2>

Expression is an expression evaluated to true or false. Value 1: value to be assigned when the result of expression is true. Value 2: value to be assigned when the result of expression is false. Ex: max= (a>b)? a:b;

Whenever „a‟ is greater then „b‟ the value of „a‟ is assigned to max. Otherwise the value of b is assigned to max.

Bitwise operators: Ex: AND, OR & XOR Comma operator: Ex: int a=10, b=20, c=40;

Hierarchy of operators:

To evaluate any expression we should know the hierarchy or precedence of all types of operators. In C language each operator is associated with priority value. Based on the priority of each operator is predefined in C language. The predefined priority or precedence order given to each of the operator is called precedence of the operator. The operations that are carried out based on the precedence of operators are called hierarchy of operators.

The below table shows precedence and associativity of the operators.

SL.NO Operator Operators precedence

(highest to lowest)

Associativity

1 ( ) Inner most brackets/function calls LR

2 [ ] Array element reference LR

3 Unary operators ++,--,size of(),+,-,&,* RL

4 Member access  or * LR

5 Arithmetic operators *,/,%,+,- LR

6 Shift operators << ,>> LR

7 Relational operators < , <=, >, >=,=, != LR

8 Bitwise operators AND, OR, XOR LR

9 Logical operators &, | LR

10 Conditional operators ? : RL 11 Assignment operators =,+=,-=,*=,/=,%=,<<=,<<,>> RL 12 Comma operator , LR

INPUT/ OUTPUT FUNCTIONS:

Input functions help us to accept the data from the input devices such as keyboard or mouse or any other input devices & store the data in memory with the help of variables. The output function helps to display the data stored in the memory on the output devices such as screen, monitor and any other output devices using the variable.

(22)

C language does not have keywords to perform I/O operations. These operations are performed by I/O functions such as scanf(), printf(), getch(), putch() etc. These functions are called standard I/O functions & are supplied in the form of standard I/O library along with every C compiler.

It is necessary to include the following header files in the beginning of the program # include <stdio.h> // Standard input output header file

# include <conio.h> // Console input output header file

The #include directive gives direction to the compiler to place the file stdio.h or conio.h at the beginning of the program during compilation the I/O functions are classified as follows.

UNFORMATED I/O FUNCTIONS:

These are classified into

1. getchar () and putchar ():

getchar () [single character input]

Single characters can be entered in to the computer using C library function getchar(). getchar() is a part of the standard C I/O library. It returns single characters from standard input devices. The function does not require any arguments through a pair of empty parenthesis must follow the getchar () function. The syntax is

Character variable = getchar();

Where, character variable refers to some previously declared character variable.

NOTE:The getchar function can also be used to reading Multi character strings by reading first character at a time within a multi pass loop

putchar()[single character output)

Single characters can be displayed using c library function putchar ().this function is complementary to the character input function getchar ().

The putchar () function is a part of standard C I/O library it transmits a single character to a standard output device (usually monitor).

The character being transmitted will normally represent as a character type variable. It must be expressed as an agreement to the function enclosed in a parenthesis. The syntax is

Putchar (character variable);

Where, character variable refers to some previously declared character variable. Ex: void main ()

{

Char ch ; Ch = getchar (); Putchar(ch); }

2. getch() ,getche() and putch():

getch():

The standard device is the one used to start a program. There are 2 files attached to this device they are the standard input file (stdin) the standard output file (stdout). These files are sequential files. The frequently used functions for input, output operations are:

For input : getch(),getche(), gets(), scanf(), sscanf() For output: putch(), puts(), printf(), sprintf().

(23)

getch() reads without echoing a character when a character is input from the keyboard ,the key may have an ASCII code or special function attached.

Ex: Void main() {

Char ch; Ch=getch();

Printf(“input character is= %c”, ch); }

getche() :

Getche() function must be invoked twice. At the first it returns the value zero and at the second call it returns a specific value for the pressed key.

The difference between getch() and getche() function is that the getche() reads character is echoed.

Ex: Void main() {

Char ch; Ch=getche();

Printf(“input character is= %c”, ch); }

During the program execution, a single character is read through the getch().the given value is not displayed on the screen and the compiler does not wait for another character to be typed and then the given character through printf function.

Both getch() and getche() functions are used to read a single character. There is a little difference between them i.e., getche() function does not display output to screen if used without Lvalue.

Putch():

Putch() sends to the output device ( Ex: screen) a character which corresponds to ASCII code used as its argument ,printable characters have ASCII code in the range 32 to 126.codes outside this range cause various image patterns to be displayed. This function returns its arguments. the prototype for these functions are in the header file conio.h.

Ex:

(24)

#include<conio.h> Void main() {

Char S[200];

Printf(“enter character string and press ENTER\n”); gets(S);

Printf(“\n the character string \n”); Puts(S);

getch(); }

3. gets() and puts():

C contains a number of functions of other library functions that permits some form of data transfer into or out of the computer. The gets () and puts () functions which facilitates the transfer of strings between the computer and standard I/O.

Each of these functions accepts single argument. The argument must be data item that represents a string (character array).the string may include white spaces. In case of gets (),a string will be entered from the keyboard and will terminate with new line character. The string will end when the user press the „ENTER‟ key.

gets() and puts() functions offer simple alternatives to the use of scanf() and printf() for reading and displaying the strings. The syntax is

Char ch[20];

Gets(ch); //Reads set of characters into memory

Puts(ch); //Displays set of characters from the memory. Ex: Void main()

{

Char ch[20]; gets(ch); puts(ch); }

FORMATTED I/O FUNCTIONS:

Formatted input function:

Scanf():

Input data can be entered into the computer from the standard input device by means of C library function scanf(). This function can be used to enter any combination of numerical values, single characters and strings. The function returns the number of data items that have been entered by the user. The syntax is

(25)

The format string consists of one or more format specifiers beginning with % symbol. &V1,&V2…….&Vn represent the list of variables. Here the symbol „&‟ refers to the address of the variable. In the memory locations identified by these addresses, the respective values are stored.

The various format specifiers are used in a scanf statement as shown below table

DATA TYPE FORMAT MEANING Int Float Character Double Long int %d %o %x %i %u %h %e %f %g %c %s %lf %ld

Reads decimal integer value. Reads octal integer value. Reads hex integer value. Reads dec, oct, hex value. Reads unsigned integer value Reads short integer value.

Reads floating point value. Reads floating point value. Reads floating point value.

Reads character value. Reads string value.

Reads long floating point number.

Reads long integer number.

Formatted output function:

Printf():

The data stored in the memory area can be displayed on monitor or output devices. This can be performed by using printf() in C. The user can display numerical values such as integer, floating point, characters, strings using this function. The syntax is

Printf(“format string/control string”, V1,V2…….Vn);

The format string consists of one or more format specifiers beginning with % symbol. The variables V1, V2..…Vn represents the value of the variables specified in the printf function. The various format specifiers are used in a scanf statement as shown below table

(26)

Int Float Character Double Long int %d %o %x %i %u %h %e %f %g %c %s %lf %ld

Reads decimal integer value. Reads octal integer value. Reads hex integer value. Reads dec, oct, hex value. Reads unsigned integer value Reads short integer value.

Reads floating point value. Reads floating point value. Reads floating point value.

Reads character value. Reads string value.

Reads long floating point number.

Reads long integer number.

Field width specification

Field width specification for Integers:

The printf() function uses field width to know the number of columns used on the screen while printing a value %wd. Where w indicates total number of columns required to print the valued specifies data type of the given variable.

Ex: printf(“%5d”,a);

In the above statement the number of columns is 5 and it is of type integer and the value of a=678.The output will be printed as follows.

6 7 8 Right justification

Ex: Printf(“%-5d”,a);

6 7 8 Left justification

(27)

Printf(“%2d”,a);

Even though in the above statement the space specified is less than the actual requirement. The computer provides enough space for the number to print.

Debugging Techniques:

The syntactic and execution errors usually produce error messages when compiling or executing a program. Syntactic errors are relatively easy to find and correct execution errors can be much more troublesome (difficult to find) when an execution error occurs,1st determine its location within the program .Once the location of the execution error has been identified the source of the error must be determined knowing where occurred. Execution errors are logical errors .Here the program executes correctly. But the programmer has supplied the computer with instructions that are logically incorrect. Logical errors are very difficult to detect. Since the output resulting from a logically incorrect program may appear to be error free. Logical error is hard to locate even when they are known to exist.

There are methods which are available for finding the location of execution error sand logical errors within the program such methods is generally referred as debugging techniques. The following debugging techniques are used in C program

1. Error isolation 2. Tracing 3. Watch value 4. Break points 5. Stepping

Error isolation:

It is used for locating an error resulting in a diagnostic message. If the general location of the error is not known it can be frequently found by temporarily deleting a portion of the program and the rerunning the program to see if the error disappears. The temporary deletion is accomplished by surrounding instructions with the comment causing the enclosed instructions to become comments if an error message then disappears the deleted portion of program contain the source of the error.

Tracing:

Tracing involves the use of printf() statements to display the values assigned to certain key variables are to display the variables that are calculated internally at various locations within the program. This information serves several purposes.

Ex:-It verifies the values actually assigned to certain variables are the values that should be assigned to those values. It is not uncommon to find that the actual assigned values are different than those expected.

I will add example later

Watch values:

Watch values in the value of the variable or an expression displayed continuously as the program executes. Thus we can see the changes in watch value as they occur in response to the program logic by monitoring a few carefully selected watch values. We can often determine where the program begins to generate in correct and unexpected values. In turbo C watch values can be defined by selecting Add watch from the debug menu and then specifying one or more

(28)

variables or expressions in the resulting dialog box. The watch values will then display within a separate window as the program executes.

Break points:

It is a temporary stopping point within a program. Each break point is associated with particular instruction within the program. When the program is executed the program execution will temporarily stop at the break point before an instruction is execution. An execution may then resume until the next break point is encountered. Break points are often used in conjunction with watch values by observing the current watch value at each break point as the program executes. To set a break point in turbo C select Add break point from the debug menu and then provide the requested information in the resulting dialog box or select a particular line within a program and designate it a break point by pressing function key F5.The breaking point may later be disabled by again pressing F5 function.

Stepping:

Stepping refers to the execution of one instruction at a time typically by pressing a function key to execute each instruction. In turbo C stepping can be carried out by pressing either function key F7 or F8.Stepping is used with a watch value allowing to trace the entire history of program as it executes. Thus we can observe changes to watch values as they happen. This allows to determine which instruction generates erroneous results.

References

Related documents

THE TABLE BELOW COMPARES AVERAGE ACT SCORES FOR STUDENTS WHO REPORTED THEY COMPLETED OR PLANNED TO COMPLETE THE RECOMMENDED CORE COLLEGE PREPARATORY CURRICULUM WITH THOSE

DiIorio, by improperly giving the Jensen facilities and procedures a “superior” rating in his audit, erroneously represented to Jensen that Jensen Farms’

The Department of Life Sciences was formed on 1 August 2007 by the linking of the Divisions of Biology, Cell and Molecular Biology, and Molecular Biosciences. The statistics for

store a copy of data1 in temporary storage copy data2 to location of data1.. copy data in temporary storage to location of

The Data Engine is designed to directly integrate with Tableau’s existing “live connection” technology, allowing users to toggle with a single click between a direct connection to

Application performance depends not only on the resources the application has available, but also on the network latency between the user and the application. An application and

With the development of MEMS inertial sensors and high- speed and large memory microprocessor, complex data fusion algorithms and multi- state sensor error dynamic models

This study was conducted at Orang Asli settlement in Ulu Kuang Village, Rawang in order to evaluate the impacts of the redevelopment of the settlement towards