• No results found

STRING CONSTANTS

In document C Lecture 1 (Page 58-84)

String constants are sequences of characters enclosed in double quotes. The same backslash sequences that are used in character constants can be used in string constants. E.g., "hello there", "a newline: \n", "a string\nwith multiple\nlines". If a string is long and you want to break it up across several lines of code, you can put a backslash just before a (real) newline and the C compiler will throw away both the backslash and the newline, e.g.,

printf("A very long help message\n

that is more readable if it is broken up over\n\several lines.\n"); this string contains one real newline (the \n).

Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some characters can't be represented in this way, so we use a 2 character sequence as follows.

'\n' newline '\t' tab

'\\' backslash '\'' single quote

'\0' null ( Usedautomatically to terminate character string )

OPERATORS IN C

What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator.

C language supports following type of operators. • Arithmetic Operators

Bitwise OperatorsAssignment OperatorsMisc Operators

Arithmetic Operators:

There are following arithmetic operators supported by C language: Assume variable A holds 10 and variable holds 20 then:

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10 * Multiply both operands A * B will give 200 / Divide numerator by denominator B / A will give 2 % Modulus Operator and remainder of after an integer division B % A will give 0

++ Increment operator, increases

integer value by one A++ will give 11 -- Decrement operator, decreases integer value by one A-- will give 9

Try following example to understand all the arithmetic operators. Copy and paste following C program in test.c file and compile and run this program.

main() { int a = 21; int b = 10; int c ; c = a + b; printf("Line 1 - Value of c is %d\n", c ); c = a - b; printf("Line 2 - Value of c is %d\n", c ); c = a * b; printf("Line 3 - Value of c is %d\n", c );

c = a / b; printf("Line 4 - Value of c is %d\n", c ); c = a % b; printf("Line 5 - Value of c is %d\n", c ); c = a++; printf("Line 6 - Value of c is %d\n", c ); c = a--; printf("Line 7 - Value of c is %d\n", c ); }

This will produce following result Line 1 - Value of c is 31 Line 2 - Value of c is 11 Line 3 - Value of c is 210 Line 4 - Value of c is 2 Line 5 - Value of c is 1 Line 6 - Value of c is 21 Line 7 - Value of c is 22

Logical (or Relational) Operators:

There are following logical operators supported by C language Assume variable A holds 10 and variable holds 20 then:

Operator Description Example

==

Checks if the value of two operands is equal or not, if yes then condition becomes true.

(A == B) is not true.

!=

Checks if the value of two

operands is equal or not, if values are not equal then condition becomes true.

(A != B) is true.

>

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

is less than the value of right operand, if yes then condition becomes true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

&&

Called Logical AND operator. If both the operands are non zero then then condition becomes true.

(A && B) is true.

||

Called Logical OR Operator. If any of the two operands is non zero then then condition

becomes true.

(A || B) is true.

!

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is false.

Try following example to understand all the Logical operators. Copy and paste following C program in test.c file and compile and run this program. main() { int a = 21; int b = 10; int c ; if( a == b ) { printf("Line 1 - a is equal to b\n" ); } else {

}

if ( a < b ) {

printf("Line 2 - a is less than b\n" ); }

else {

printf("Line 2 - a is not less than b\n" ); }

if ( a > b ) {

printf("Line 3 - a is greater than b\n" ); }

else {

printf("Line 3 - a is not greater than b\n" ); }

/* Lets change value of a and b */ a = 5;

b = 20; if ( a <= b ) {

printf("Line 4 - a is either less than or euqal to b\n" ); }

if ( b >= a ) {

printf("Line 5 - b is either greater than or equal to b\n" ); }

if ( a && b ) {

printf("Line 6 - Condition is true\n" ); }

if ( a || b ) {

printf("Line 7 - Condition is true\n" ); }

/* Again lets change the value of a and b */ a = 0;

b = 10; if ( a && b ) {

printf("Line 8 - Condition is true\n" ); }

else {

}

if ( !(a && b) ) {

printf("Line 9 - Condition is true\n" ); }

}

This will produce following result

Line 1 - a is not equal to b Line 2 - a is not less than b Line 3 - a is greater than b

Line 4 - a is either less than or equal to b Line 5 - b is either greater than or equal to b Line 6 - Condition is true

Line 7 - Condition is true Line 8 - Condition is not true Line 9 - Condition is true

Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation.

Assume if A = 60; and B = 13; Now in binary format they will be as follows: A = 0011 1100 B = 0000 1101 --- A&B = 0000 1000 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011 Note:

convert decimal 49 to binary: 49/2 = 24 r 1

24/2 = 12 r 0 12/2 = 6 r 0

6/2 = 3 r 0 3/2 = 1 r 1 1/2 = 0 r 1

Now read the remainders from bottom to top: the binary equivalent is 110001

convert binary 1101001 to decimal: 1 + 8 + 32 + 64 = 105

convert decimal 0.7 to binary: 0.7 * 2 = 1.4 0.4 * 2 = 0.8 0.8 * 2 = 1.6 0.6 * 2 = 1.2 0.2 * 2 = 0.4 0.4 * 2 = 0.8 0.8 * 2 = 1.6

0.6 * 2 = 1.2 etc. Note that we have started to repeat previous results. Now read the integer parts occurring on the right side, from the top down: the binary representation of decimal 0.7 is 0.1011001100... where the "1100" repeats forever.

The bit on the far right, in this case a 0, is known as the Least significant bit (LSB).

The bit on the far left, in this case a 1, is known as the Most significant bit (MSB)

There are following Bitwise operators supported by C language

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

| Binary OR Operator copies a bit if it exists in either operand.

(A | B) will give 61 which is 0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

~ Binary Ones Complement Operator is unary and has the

(~A ) will give -60 which is 1100 0011

efect of 'flipping' bits.

<<

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

>>

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

A >> 2 will give 15 which is 0000 1111

Try following example to understand all the Bitwise operators. Copy and paste following C program in test.c file and compile and run this program.

main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0; c = a & b; /* 12 = 0000 1100 */ printf("Line 1 - Value of c is %d\n", c ); c = a | b; /* 61 = 0011 1101 */ printf("Line 2 - Value of c is %d\n", c ); c = a ^ b; /* 49 = 0011 0001 */ printf("Line 3 - Value of c is %d\n", c ); c = ~a; /*-61 = 1100 0011 */ printf("Line 4 - Value of c is %d\n", c ); c = a << 2; /* 240 = 1111 0000 */ printf("Line 5 - Value of c is %d\n", c ); c = a >> 2; /* 15 = 0000 1111 */ printf("Line 6 - Value of c is %d\n", c ); }

This will produce following result

Line 2 - Value of c is 61 Line 3 - Value of c is 49 Line 4 - Value of c is -61 Line 5 - Value of c is 240 Line 6 - Value of c is 15 Assignment Operators:

There are following assignment operators supported by C language:

Operator Description Example

=

Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B will assign value of A + B into C

+=

Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

C += A is equivalent to C = C + A

-=

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C -= A is equivalent to C = C - A

*=

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

C *= A is equivalent to C = C * A

/=

Divide AND assignment operator, It divides left operand with the right

operand and assign the result to left operand

C /= A is equivalent to C = C / A

%=

Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Try following example to understand all the Assignment Operators. Copy and paste following C program in test.c file and compile and run this program. main()

{

int a = 21; int c ; c = a;

printf("Line 1 - = Operator Example, Value of c = %d\n", c ); c += a;

printf("Line 2 - += Operator Example, Value of c = %d\n", c ); c -= a;

printf("Line 3 - -= Operator Example, Value of c = %d\n", c ); c *= a;

printf("Line 4 - *= Operator Example, Value of c = %d\n", c ); c /= a;

printf("Line 5 - /= Operator Example, Value of c = %d\n", c ); c = 200;

c %= a;

printf("Line 6 - %= Operator Example, Value of c = %d\n", c ); c <<= 2;

printf("Line 7 - <<= Operator Example, Value of c = %d\n", c ); c >>= 2;

printf("Line 8 - >>= Operator Example, Value of c = %d\n", c ); c &= 2;

printf("Line 9 - &= Operator Example, Value of c = %d\n", c ); c ^= 2;

printf("Line 10 - ^= Operator Example, Value of c = %d\n", c ); c |= 2;

printf("Line 11 - |= Operator Example, Value of c = %d\n", c ); }

This will produce following result

Line 1 - = Operator Example, Value of c = 21 Line 2 - += Operator Example, Value of c = 42 Line 3 - -= Operator Example, Value of c = 21 Line 4 - *= Operator Example, Value of c = 441 Line 5 - /= Operator Example, Value of c = 21 Line 6 - %= Operator Example, Value of c = 11 Line 7 - <<= Operator Example, Value of c = 44 Line 8 - >>= Operator Example, Value of c = 11 Line 9 - &= Operator Example, Value of c = 2 Line 10 - ^= Operator Example, Value of c = 0 Line 11 - |= Operator Example, Value of c = 2

Short Notes on L-VALUE and R-VALUE:

x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x. Here x and 1 are known as L-VALUES and R-VALUES respectively L- values can be on either side of the assignment operator where as R-values only appear on the right.

So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y = x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is invalid.

Misc Operators

Operator Description Example sizeof() Returns the size of an

variable.

sizeof(a), where a is interger, will return 4.

& Returns the address of an variable. &a; will give actaul address of the variable. * Pointer to a variable. *a; will pointer to a variable.

? : Conditional Expression If Condition is true? Then value X : Otherwise value Y

sizeof Operator:

Try following example to understand sizeof operators. Copy and paste following C program in test.c file and compile and run this program.

main() { int a; short b; double double c; char d[10];

printf("Line 1 - Size of variable a = %d\n", sizeof(a) ); printf("Line 2 - Size of variable b = %d\n", sizeof(b) ); printf("Line 3 - Size of variable c= %d\n", sizeof(c) ); printf("Line 4 - Size of variable d= %d\n", sizeof(d) );

/* For character string strlen should be used instead of sizeof */ printf("Line 5 - Size of variable d= %d\n", strlen(d) );

}

This will produce following result

Line 1 - Size of variable a = 4 Line 2 - Size of variable b = 2 Line 3 - Size of variable c= 8 Line 4 - Size of variable d= 10 Line 5 - Size of variable d= 10

& and * Operators:

Try following example to understand & operators. Copy and paste following C program in test.c file and compile and run this program.

main() {

int i=4; /* variable declaration */

int* ptr; /* int pointer */

ptr = &i; /* 'ptr' now contains the

address of 'i' */ printf(" i is %d.\n", i);

printf("*ptr is %d.\n", *ptr); }

This will produce following result

i is 4. *ptr is 4.

? : Operator

Try following example to understand ? : operators. Copy and paste following C program in test.c file and compile and run this program.

main() { int a , b; a = 10; b = (a == 1) ? 20: 30; printf( "Value of b is %d\n", b ); b = (a == 10) ? 20: 30; printf( "Value of b is %d\n", b ); }

This will produce following result

Value of b is 30 Value of b is 20

Note : 1's and 2's complement

Generally negative numbers can be represented using either 1's complement or 2's complement representation. 1's complement ---reverse all the bits

2's complement ---reverse all the bits + 1

i.e 1's complement of 2 ( 0000 0010 ) is -2 ( 1111 1101 ) 2's complement of 2 ( 0000 0010 ) is -2 ( 1111 1110 )

Binary numbers do not have signs. So 2's complement is used to represent a negative nos. 2's complement is found in following way :

Step I)

If we have a binary no 00001100(decimal 12) then we have to invert it by replacing all the 1s by 0 and 0s by 1.

So we get 00001100 ---> 11110011 Step II)

Now we have to add 1 to the no which we found in (I) So we get ,

11110011 + 00000001 = 11110100 So the no 11110100 represents -12 .

Operators Categories:

All the operators we have discussed above can be categorised into following categories:

• Postfix operators, which follow a single operand.

• Unary prefix operators, which precede a single operand.

• Binary operators, which take two operands and perform a variety of arithmetic and logical operations.

• The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.

• The comma operator, which guarantees left-to-right evaluation of comma-separated expressions.

C Operator Precedence and Associativity

C operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied.

Operator Description Associativity

() [] . -> ++ --

Parentheses (function call) (see Note 1) Brackets (array subscript)

Member selection via object name Member selection via pointer

Postfix increment/decrement (see Note 2)

left-to-right ++ -- + - ! ~ (type) * & sizeof Prefix increment/decrement Unary plus/minus

Logical negation/bitwise complement Cast (change type)

Dereference/pointer Address

Determine size in bytes

right-to-left

* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right < <=

> >=

Relational less than/less than or equal to Relational greater than/greater than or

equal to

left-to-right

== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

= += -= *= /= %= &= ^= |= Assignment Addition/subtraction assignment Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment

<<= >>= Bitwise shift left/right assignment

, Comma (separate expressions) left-to-right Note 1:

Parentheses are also used to group sub-expressions to force a different precedence; such parenthetical expressions can be nested and are evaluated from inner to

outer. Note 2:

Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed

(to be accomplished sometime before the statement completes execution). So in the statement y = x * z++; the

current value of z is used to evaluate the expression (i.e., z++ evaluates to z) and z only incremented after all else is

done.

C Ternary Operator

C ternary operator is a shorthand of combination of if and return statement. Syntax of ternary operator are as follows:

(expression1 ) ? expression2: expression3

If expression1 is true it returns expression2 otherwise it returns expression3. This operator is a shorthand version of this if and return statement:

if(expression1) return expression2; else

return expression3; Increment operator ++

Prefix: the value is incremented/decremented first and then applied.

Postfix: the value is applied and the value is incremented/decremented. #include<stdio.h> main( ) { int i = 3,j = 4,k; k = i++ + --j; printf("i = %d, j = %d, k = %d",i,j,k); }

Out put : i = 4, j = 3, k = 6 The decrement operator: -- #include <stdio.h> #include <stdlib.h> int main() { char weight[4]; int w;

printf("Enter your weight:"); gets(weight);

w=atoi(weight);

printf("Here is what you weigh now: %i\n",w); w--; printf("w++: %i\n",w); w--; printf("w++: %i\n",w); return(0); }

Enter your weight:123

Here is what you weigh now: 123 w++: 122

1's complement and 2's complement

Generally negative numbers can be represented using

either 1's complement or 2's complement representation. 1's complement ---reverse all the bits

2's complement ---reverse all the bits + 1

i.e 1's complement of 2 ( 0000 0010 ) is -2 ( 1111 1101 ) Examples Original number: 0111011 1's complement: 1000100 2's complement: 1000101 Original number: 1111111 1's complement: 0000000 2's complement: 0000001

Original number: 1111000 1's complement: 0000111 2's complement: 0001000 Use of clrscr

Usually you want to clear the screen prior to writng to the terminal. Use;

#include < conio.h> /* as in console I/O */ ...

main() { ... clrscr();

Note that as this is a command, it must appear after your variable declarations.

requires the header file conio.h i.e #include <conio.h>

clrscr(); :- This is use to clear the output screen i.e console

suppose you run a program and then alter it and run it again you may find that the previous output is still stucked there itself, at this time clrscr(); would clean the previous screen.

One more thing to remember always use clrscr(); after the declaration like int a,b,c;

float total; clrscr();

getch()/ getche()

getch(); :- getch is used to hold the screen in simple language, if u dont write this the screen

getch() takes one char from keyboard but it will be invisible to us. in other words we can say that it waits until press any key from keyboard.

getch() is a function which has its protype defined in conio.h header file.

it is basically used to take input a single characterfrom keyboard. and this char is not displayed at the screen.

it waits untill itn gets a input thats why it can be used as a screen stopper. getch() returns to the program after hitting any key.

getche() waits for the character, read it and then returns to the program

getch() waits for the user to input a character and displays the output till the user enters a character.As soon as the user enters a character it transfers the

control back to the main function, without displaying what character was entered.

getche() does the same thin but it displays the chacter entered.here e stands for echo.

Use of getch(),getche() and getchar() in C

Most of the program is ending with getch(),and so we think that getch() is used to display the output...but it is wrong.It is used to get a single character from the console.

Just see the behaviors of various single character input functions in c.

 getchar()  getche()  getch()

getchar() is used to get or read the input (i.e a single character) at run time. Library:

<CONIO.H>

Example Declaration: char ch;

ch = getchar();

Example Program: void main() { char ch; ch = getchar(); printf("Input Char Is :%c",ch); }

Here,declare the variable ch as char data type, and then get a value through

getchar() library function and store it in the variable ch.And then,print the value

of variable ch.

During the program execution, a single character is get or read through the

getchar(). The given value is displayed on the screen and the compiler wait for

another character to be typed. If you press the enter key/any other characters and then only the given character is printed through the printf function.

getche() is used to get a character from console, and echoes to the screen. Library:

<CONIO.H>

Example Declaration: char ch;

ch = getche();

getche reads a single character from the keyboard and echoes it to the current text window, using direct video or BIOS.

This function return the character read from the keyboard. Example Program: void main() { char ch; ch = getche(); printf("Input Char Is :%c",ch); }

Here,declare the variable ch as char data type, and then get a value through

getche() library function and store it in the variable ch.And then,print the value of

variable ch.

During the program execution, a single character is get or read through the

getche(). The given value is displayed on the screen and the compiler does not

wait for another character to be typed. Then,after wards the character is printed through the printf function.

getch() is used to get a character from console but does not echo to the screen. Library:

<CONIO.H>

Example Declaration: char ch;

ch = getch(); (or ) getch();

getch reads a single character directly from the keyboard, without echoing to the screen.

This function return the character read from the keyboard. Example Program: void main() { char ch; ch = getch(); printf("Input Char Is :%c",ch); }

Here,declare the variable ch as char data type, and then get a value through

getch() library function and store it in the variable ch.And then,print the value of

variable ch.

During the program execution, a single character is get or 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 is printed through the printf function.

# C Tips:

3>2 ? printf(“True”):printf(“False”); // prints Truez=x*++y // it will increment first then multiplies The sizeof Operator

The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.

The sizeof program uses the C sizeof() call to display the size (in bytes) of the standard C data types (char, int, long,...).

Printf(sizeof(x)); // prints 2 (bytes) Printf(sizeof(y)); // prints 4(bytes)

& operator

Prints the address of the variable in the memory #include <stdio.h> int main() { int x = 0; printf("Address of x "); printf("= 0x%p \n", &x); return 0; } Output: Address of x = 0x0065FDF4 int a; /* a is an integer */

printf( "The address of a is %p”, &a )//prints address of variable a -8907 TIP

printf(“\n10==10 :%5d”,10==10);// prints 1 for trueprintf(“\n10==10 :%5d”,10>=10); // prints 1

printf(“\n10==10 :%5d”,10!=10);//prints 0

In document C Lecture 1 (Page 58-84)

Related documents