[go: up one dir, main page]

0% found this document useful (0 votes)
77 views16 pages

Data Types & Basic Constructs (If, If-Else, Switch-Case)

This document summarizes data types and basic constructs in C including if, if-else, and switch-case statements. It discusses standard data types like char, int, float, and structured types like arrays, structs, and unions. It also covers operators in C like unary, binary, and ternary operators and their precedence. Finally, it provides examples of common operators like division, modulus, and increment/decrement and how they work in C code.

Uploaded by

abcde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views16 pages

Data Types & Basic Constructs (If, If-Else, Switch-Case)

This document summarizes data types and basic constructs in C including if, if-else, and switch-case statements. It discusses standard data types like char, int, float, and structured types like arrays, structs, and unions. It also covers operators in C like unary, binary, and ternary operators and their precedence. Finally, it provides examples of common operators like division, modulus, and increment/decrement and how they work in C code.

Uploaded by

abcde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 2

Data Types & Basic Constructs


(if, if-else, switch-case)
1. Data Types in C:
Following is the classification of data types in C:
1. Standard data type
a. Simple data type
i. char
ii. int
iii. float
b. Structured/composite data type c. Pointer
i. array
ii. struct
iii. union
2. User Defined data type
a. enum
b. typedef
The char holds a character or a small integer. It hs two modifies:
 unsigned (Explain the program unsignedChar.c)
 signed (Explain the program signedChar.c)
The default char depends upon the setting in the turbo IDE.
The int holds a whole number. It has two types of modifiers:
 Type 1:
o signed
o unsigned
 Type 2:
o short
o int
o long
The float can hold a number with fraction parts. It has three modifiers:
 float
 double
 long double

Name Description Size Range


signed: -128 to 127
char Character. 1byte
unsigned: 0 to 255
short int signed: -32768 to 32767
Short Integer. 2bytes
(short) Integral unsigned: 0 to 65535
data type 2bytes/ signed: -32768 to 32767
int Integer.
4 bytes unsigned:- 0 to 65535
long int signed: -2147483648 to 2147483647
Long integer. 4bytes
(long) unsigned: 0 to 4294967295
float Floating point number. 4bytes 3.4e +/- 38 (7 digits)
Double precision floating point
double 8bytes 1.7e +/- 308 (15 digits)
number.
long double Long double precision floating point 10bytes ??
number.

Exercise: Explore the two header files: values.h, limits.h

Page 1 of 16 [Chapter 2] [Modified – 2]


Note: In C or C++ language character and integer data types use the same internal format.
So from the machine representation point of view both are same. The only difference is the
number of bytes allocated.
:An example will demonstrate the similarity
#include <stdio.h> //char1a.c
int main( )
{
char ch = 97; // char ch = ‘a’;
int x = ‘A’; // int x = 65;

printf(“\nCharacter: %c, Equivalent integer: %d”, ch, ch);


printf(“\nEquivalent Character: %c, integer: %d”, x, x);

return 0;
}
%c is for displaying characters and %d is for displaying integers. First we have displayed the
equivalent integer of the character. Then we have displayed the equivalent character of the
integer.

Character, integer (all their variants) and enumerated data type are called integral data type.
There internal representation is the same.

2. Operators available in C:
There are three types of operators available in C:
 unary – that requires only one operand. For example: &a, ++a, *a
 binary - that requires two operands. For example: a + b, a * b
 ternary - that requires three operands. For example: (a>b) ? a : b [ ?:]

Priority and associativity: The higher priority operator is operated first. If the priority or
precedence is same then associativity is applied.

Following is the operators available in C. Their precedence and associativity are shown.
Associativity Operators Description
1. left-to-right .  () [] Highest priority operators
2. right-to-left ++, --, !, ~, +, -, *, &, sizeof( ) all unary operators
3. left-to-right * / % arithmetic operators
4. left-to-right + - arithmetic operators
5. left-to-right << >> bit shift operators
6. left-to-right <, <=, >, >=, relational operator
7. left-to-right = =, != relational operator
8. left-to-right & ampersand
9. left-to-right ^ caret bit wise operator
10. left-to-right | pipeline
11. left-to-right &&
Logical operator
12. left-to-right ||
13. right-to-left ? : ternary/conditional operator
14. =, +=, -=, *=, /=, %=, &=, ^=, |
right-to-left assignment operator
=, <<=, >>=
15. left-to-right , sequencing operator

Examples:

Page 2 of 16 [Chapter 2] [Modified – 2]


1. a+b*c 8. (a + b) * c
2. x=a+b 9. *a++
3. a-b+c
4. a *= b += c
5. a / b*c
6. a+b+c
7. x = a++ ?

Note: Each expression generates a resultant numeric value. This resultant numeric value
has a data type. The data type of the result is the data type of the operand with largest
capacity, participating in the expression. That is why C is called strongly typed language.
int $ int will produce int
char $ int will produce int
int $ float will produce float

Now we shall see the operators in details


The “/” (the division) operator:

op1 / op2
Data type of op1 Data type of op2 Data type of result
int Int int (fractional part truncated)
Float Int float
int Float float
Float Float float

Ex: //div1.c //div2.c


int main( ){ int main( ){
int a = 11, int a = 11,b = 2; Explain div3.c
b = 2; float c;
int c; c = a / b;
c = a / b; printf( “%f ”, c);
printf( “%d”, c); return 0;
}
This property of / operator can also be useful also:
(i) ‘/’ can be used to check whether a number is completely divisible by another number or not.
(ii) ‘/’ can be used to truncate last digit of a number by dividing the number by 10.

Token:
In a C source program, the basic element recognized by the compiler is the “token.” A token is
source-program text that the compiler does not break down into component elements.
token: keyword, identifier, constant, string-literal, operator, punctuator
c = ++a + b; sum = x + pow(3,6)
Note See the introduction to Appendix A, C Language Syntax Summary, for an explanation
of the ANSI syntax conventions.

The keywords, identifiers, constants, string literals, and operators described in this chapter are
examples of tokens. Punctuation characters such as brackets ([ ]), braces ({ }), parentheses
( ( ) ), and commas (,) are also tokens.

Modulus operator
It is represented by %. It gives the remainder after division:
int a, b, c;

Page 3 of 16 [Chapter 2] [Modified – 2]


a b c=a%b
10 2 0
11 2 1
11 7 4
13 7 6
24 8 0
7 21 7
132 10 2
The uses of % are as follows:
(i) The property of modulus operator is used to generate numbers in a restricted range.
The expression a%b will generate number ranging from 0 to b -1. For example:
x %100 will generate numbers from 0 to 99 for any value of x.
(ii) The modulus operator is also used to extract last digit of a number. x%10 will always give
the last digit of the number x.
153 % 10  3
7842 % 10  2
98 % 10  8
4 % 10  4
Increment / Decrement Operators ( ++, - -)
Let ‘a’ is an integer. Following are the possible options:
I). Pre-increment  ++a
II). Post – increment  a++
III). Pre-decrement  - -a
IV). Post-decrement  a--
The following examples will demonstrate the behavior:
/*incr0.c*/ /*incr2.c*/ /*incr3.c*/
void main( ){ void main( ){ void main( ){
int a, b; int a, b; int a, b;
a = 10; a = 10; a = 10;
++a; a++; b = a++; / * a=a+1*/
b = a; b = a; printf(“\n%d %d”, a, b);
printf(“\n%d %d”, a, b); printf(“\n%d %d”, a, b); }
} }

/*incr4.c*/ /*incr5.c*/
void main( ){ void main( ){
int a, b; int a, b, c;
a = 10; a = 10;
b = ++a; b = 20;
printf(“\n%d %d”, a, b); c = (++a) + (b++);
} printf(“\n%d %d %d”, a, b, c);
}
Note: The expressions in which a variable is incremented and decremented and used more
than once, must be strictly avoided. These are confusing. Moreover, the compiler may
behave in unpredictable manner.
There are some more examples; there result may not be predicted easily, and the results will be
environment dependent also. /*incr6.c*/
void main( ) {
int a, b;
a = 10;
b = (++a) + (a++);
printf(“\n%d %d”, a, b);
}
Page 4 of 16 [Chapter 2] [Modified – 2]
/*incr8.c*/ /*incr7.c*/
void main( ){ void main( ) {
int a, b; int a, b;
a = 10; a = 10;
b = a * 2 + ( ++a); b = (++a * 2 ) + ( a++) * 3;
printf(“\n%d %d”, a, b); printf(“\n%d %d”, a, b);
} }
Explain examples incr9.c, 10, 10A, 12, 13, 14, 15

Assignment Operators:
An assignment statement is used to assign the value of an expression to a single variable. The
syntax is:
Explain a = b = c = 10;
lvalue = rvalue

It can only a variable, a


be a single constant, an
variable expression,
function call
The “lvalue” is that value which can be changed.

/* ass1.c */ /* ass2..c */
void main( ){ void main( )
int a, b, c; {
a = 10; b = 20; c= 30; int a, b, c;
b += a; /* b = b + a a = 10; b = 20; c= 30;
*/ c *= b += a;
c - = a; /* c = c – a */ printf(“\n%d %d %d”, a, b, c);
printf(“\n%d %d %d”, a, b, c); }
}

printf( ): Writes to the standard output (stdout) a sequence of data formatted as the format
argument specifies. After the format parameter, the function expects at least as many additional
arguments as specified in format.
format is a string that contains the text to be written to stdout.
It can optionally contain embedded format tags that are substituted by the values specified in
subsequent argument(s) and formatted as requested. The number of arguments following the
format parameters should at least be as much as the number of format tags.
The format tags follow this prototype:
%[flags][width][.precision][length]specifier
Where specifier is the most significant one and defines the type and the interpretation of the
value of the corresponding argument:
specifie
Output Example
r
C Character a
d or i Signed decimal integer 392
e Scientific notation (mantissa/exponent) using e character 3.9265e+2
E Scientific notation (mantissa/exponent) using E character 3.9265E+2
f Decimal floating point 392.65
g Use the shorter of %e or %f 392.65
G Use the shorter of %E or %f 392.65

Page 5 of 16 [Chapter 2] [Modified – 2]


O Signed octal 610
s String of characters sample
u Unsigned decimal integer 7235
x Unsigned hexadecimal integer 7fa
X Unsigned hexadecimal integer (capital letters) 7FA
p Pointer address B800:0000
Nothing printed. The argument must be a pointer to a signed int, where the
n
number of characters written so far is stored.
% A % followed by another % character will write % to stdout.

The tag can also contain flags, width, .precision and modifiers sub-specifiers, which are
optional and follow these specifications:

Flags description
Left-justify within the given field width; Right justification is the default (see width sub-
-
specifier).
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers.
+
By default, only negative numbers are preceded with a - sign.
(space) If no sign is going to be written, a blank space is inserted before the value.
Used with o, x or X specifies the value is preceded with 0, 0x or 0X respectively for
values different than zero.
# Used with e, E and f, it forces the written output to contain a decimal point even if no
digits would follow. By default, if no digits follow, no decimal point is written.
Used with g or G the result is the same as with e or E but trailing zeros are not removed.
Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see
0
width sub-specifier).
width description
Minimum number of characters to be printed. If the value to be printed is shorter than this
(number) number, the result is padded with blank spaces. The value is not truncated even if the
result is larger.
The width is not specified in the format string, but as an additional integer value argument
*
preceding the argument that has to be formatted.
.precision description
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits
to be written. If the value to be written is shorter than this number, the result is padded
with leading zeros. The value is not truncated even if the result is longer. A precision of 0
means that no character is written for the value 0.
For e, E and f specifiers: this is the number of digits to be printed after the decimal point.
.number For g and G specifiers: This is the maximum number of significant digits to be printed.
For s: this is the maximum number of characters to be printed. By default all characters
are printed until the ending null character is encountered.
For c type: it has no effect.
When no precision is specified, the default is 1. If the period is specified without an
explicit value for precision, 0 is assumed.
The precision is not specified in the format string, but as an additional integer value
.*
argument preceding the argument thas has to be formatted.
length description
The argument is interpreted as a short int or unsigned short int (only applies to integer
h
specifiers: i, d, o, u, x and X).
The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o,
l
u, x and X), and as a wide character or wide character string for specifiers c and s.
The argument is interpreted as a long double (only applies to floating point specifiers: e,
L
E, f, g and G).
Return Value

Page 6 of 16 [Chapter 2] [Modified – 2]


On success, the total number of characters written is returned. On failure, a negative number is
returned.
Example
/* fprintf example */
#include <stdio.h>
int main( ) {
printf ("Characters: %c %c \n", 'a', 65);
printf ("Decimals: %d %ld\n", 1977, 650000);
printf ("Preceding with blanks: %10d \n", 1977);
printf ("Preceding with zeros: %010d \n", 1977);
printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
printf ("Width trick: %*d \n", 5, 10);
printf ("%s \n", "A string");
return 0; }

And here is the output:

Characters: a A
Decimals: 1977 650000
Preceding with blanks: 1977
Preceding with zeros: 0000001977
Some different radixes: 100 64 144 0x64 0144
floats: 3.14 +3e+000 3.141600E+000
Width trick: 10
A string

More about printf( ):


//printf1.c //printf2.c
int main( ) { int main( ){
int a = 10; int a = 10;
printf(“%d %d %d”, ++a, ++a, ++a); printf(“%d %d %d”, ++a, a- -, a++);
return 0; return 0;
} }

//printf4.c
int main( ){ Note: We should not change the specifier of
int a=10, b=10; a data type in printf() or scanf() statements.
float c = 3.14; Otherwise, the result may be garbage.

print f (“%d%d%d”, a, b, c); Discuss printf5,6 also.

return 0; printf() returns the number of characters


} displayed by it on the screen.
scanf( ):
scanf( ) statement is used to read data from standard input stream (stdin), the keyboard. The
syntax is:
scanf( format string with specifiers, variable names)
The specifier list is same as that of printf( ).
Example:
char x;
int y;
float z;
scanf(“%c%d%f”, &x, &y, &z);

Page 7 of 16 [Chapter 2] [Modified – 2]


scanf( ) returns the number of values successfully read.
Show scanf.c
3. Expression – There are two types of expressions:
 Arithmetic expression
 Relational / Logical / Conditional Expression
An arithmetic expression returns numeric value.
An relational expression is either true or false.
Arithmetic expression uses arithmetic operator the relational expression uses relational and
logical operators.
Example of arithmetic expression:
a+b
a-b
a+(a/b*d)
Example of relational expression:
a<b
a>b
(a != b) && (c = = d)
! (a>b)
Note: There is almost no difference between a relational expression and arithmetic expression.
Both can be used in place of each-other, there is no syntactical compulsion.
A relational expression is considered to be true or false according to numeric value.
zero – equivalent to “false”
Non Zero – equivalent to “true”
if a relational expression is true, it returns numeric value 1
if a relational expression is false, it returns numeric value 0
Logical Operator -
There are three logical operators && (AND), | | (OR), ! (NOT). These are used to combine the
conditions.
Let there be two conditions c1 and c2.
c1 c2 c1 && c2
F F F
F T F
T F F
T Short circuit
T T
evaluation
c1 c2 c1 | | c2
F F F
F T T
T F T
T T T

C !C
F T
T F
Explain the output of the code:
/*expr0.c*/ /*expr1.c*/
int main( ) { int main ( ) {
int a= 10, int a = 10, b= 5;
b=20;
printf(“%d ”, a < b); printf(“%d %d %d” b, a<b, b=a+20);
printf(“%d ”, a > b); return 0;
} }

Page 8 of 16 [Chapter 2] [Modified – 2]


/*expr2.c*/ /*expr4.c*/
int main ( ){ int main ( ){
int a=10, b= 20, c; int a=10, b= 20, c = 1, d;

c = a == b; d = a < b = = c;
printf(“%d %d %d”, a, b, c); printf(“ %d ”, d);
return 0; return 0;
} }
/*expr5.c*/ /*expr6.c*/
int main { int main( ){
float y = 2.56; x = 2.5; floot a = - 1.0, b = 0.5, c = 1.0;
int a, b; int d;
a = (y= = 2.56);
b = (x = = 2.5); d=a< b < c;
printf (“%d, %d” a, b); printf(“%d”, d);
return 0; return 0;
} }

show log0.c Show comma1.c, comma2.c


and log01.c

4. The ‘if’ Statement – It is used to selectively execute a set of statements. The set of
statements is executed, if the condition is true. The syntax is:(Draw the flowchart
corresponding to the code)

s0; s0; s0; s0; s0;


if (c) if (c) if (c) if (c) ; if (c) ;
s1; { s1; s1; {
s2; s1; s2; s2; s1;
s2; s3; s2;
} }
s3; s3;
Indentation does not affect the logic of a program; it is only enhances/increases the clarity of
the program. There can be any valid C statement inside ‘if’. It can be another ‘if’ statement. It
is called nesting of ‘if’.
s0;
if (c1)
{
s1;
if (c2)
s2;
Dangling else case s3;
}
if..else structure:
s4;
Draw the flowchart corresponding to the code:
s0; s0; s0; s0; s0;
if (c) if (c) { if (c) { if (c) if (c1)
s1; s1; s1; s1; if (c2)
else s2; s2; s2; s1;
s2; } } else { else
s3; else { else s3; s2;
s3; s3; s4; s3;
s4; s4; }
} Page 9 s5; s5; – 2]
of 16 [Chapter 2] [Modified
s5;
Example: Read two numbers and display largest of them.
/* larger1.c : program to find the larges of two no. */ Ternary or Conditional Operator in C:
#include <stdio.h> The operator is called ternary or conditional
int main ( ){ operator, if it requires three operands.
int a, b, larger;
/*larger2.c: program to find the larges of two no. */
printf( “\nEnter two numbers:”); #include <stdio.h>
scanf(“%d %d”, &a, &b); int main( )
{
if (a > b) int a, b, larger;
larger = a;
else print f ( “\nEnter two numbers: ”);
larger = b; scanf(“%d%d”, &a, &b);
larger = (a > b) ? a : b;
printf(“Larger number is: %d”, larger); printf(“\nLarger number is : %d”, larger);
return 0; return 0;
} }
Example : Read three numbers and display them.
/*largest3.c: Program to find largest of three numbers */
#include <stdio.h>
int main()
{
int a, b, c, larger;

printf( “\nEnter three number: ”);


scanf(“%d%d%d”, &a, &b, &c);
largest = a; /* Let a is largest */
If ( largest <b) /* b is larger than current largest */
largest =b; /* modify largest */
if (largest <c) /* c is larger than current larger*/
largest =c; /* modify, largest */
printf(“\nThe largest is : %d”, largest);
return 0;
}
Exercise: Read four numbers and display second largest of them.

Example: Give the output of the following:


//ex6.c
Show ex7.c and ex8.c also.
#include <stdio.h>
int main(){
int a = 0, b = 5, c = 0;
if (c=a)
printf(“\n Hello”);
else
printf(“in world”);
if (c = b)
printf(“\nHello”);
else
printf(“\nWorld”);
return 0;
} Page 10 of 16 [Chapter 2] [Modified – 2]
Example: Design a program to display the result of a structure according to the following
scheme.
Marks < 40 - Fail
40  marks < 65 - Second division.
65  marks < 75 - First division.
75  marks - Distinction
The conditions to be checked should be as minimum as possible
/*result1.c: program to display result */ if .. else ladder
#include <stdio.h>
int main( ){ /*result2..c: program to display result */
int marks; #include <stdio.h>
int main( ){
printf(“ \nEnter marks: ”); int marks;
scanf(“%d”, &marks); printf(“ \nEnter marks: ”);
if (marks < 40) scanf(“%d”, &marks);
printf(“Fail”); if (marks < 40)
if ( (marks >= 40) && (marks <65) ) printf(“Fail”);
printf(“Second div”); else if (marks < 65)
if ( (marks >= 65) && (marks <75) ) printf(“Second div”)
printf(“First div”); else if (marks < 75)
if (marks >=75) printf( “First div”);
printf(“Distinction”); else
retun 0; printf(“ Distinction.”);
} return 0;
}
Que: What is the drawback/inefficiency
of the above code?
Note: From efficiency point of view, the condition checking should be as minimum as
possible.

Example : Design program to calculate money accumulated after one years, if the interest rates
are as follows:
initial amt  10,000 rate = 5%
initial amt > 10,000 rate = 10%

/* interest.c: program to find total amount */


# include <stdio.h>
int main ( ){
int rate;
float amount, total;
Find out any
printf(“\nEnter initial amount: “);
error in the above
scanf(“%f“, &amount);
code.
rate= (amount <= 10000) ? 5 : 10; /* decision of rate */

total = amount * (1+ rate /100); /*calculate total amount */


printf(“\nTotal amount is : %f ”, total);
return 0;
}

Page 11 of 16 [Chapter 2] [Modified – 2]


5. Type Conversion:
A variable/value of one type can be converted into variable/value of another type. There are
two cases:
a) Implicit conversion a) narrowing conversion
b) Explicit Conversion – called type casting b) widening conversion
(a) Implicit conversion
Values can be converted by assigning one expression into the other. There are two types:
 widening conversion
 narrowing conversion
char  short  int  long  float  double  long double
Assignment in forward direction is widening conversion; no data is lost in it. Assignment in
backward direction is called narrowing conversion; data loss is possible in this case.
char a = 10;
int b, c;
float d = 2.6;

b = a; // widening conversion, no data loss


c = d; // narrowing conversion, data loss, c gets value only 2
Narrowing conversion must be type casted.
c = (int)d;
(b)Type casting / Explicit conversion:
Type casting is used to convert the data type of an identifier to another data type temporarily.
//div2.c
#inlcude <stdio.h>
int main( ) {
int a=11, b=2;
float c;

c = (float)a / b;
printf(“\n%f”, c);
return 0;
}
During type casting the system creates a temporary memory location for target data type. The
value of casted variable is copied into it. Now this temporary variable takes part in the
calculations of this expression only. After the calculation of expression the temporary memory
location is destroyed automatically.
a: 2 bytes b: 2 bytes c: 4 bytes
11 2

11.0 This location is destroyed after calculation


temp: 4 bytes float type
So, the statement:
c = (float) a / b;
is finally converted into :
c = temp / b;
= 11.0 / b;
= 5.5;
The temporary location is destroyed automatically as soon as the statement ends.
Example 9: Read a float number and display its whole and fractional parts separately.(sep.c)

Page 12 of 16 [Chapter 2] [Modified – 2]


Example 10: Read a float number and display its rounded integer without using round
function.

/* round.c: program to find round of a float */


Ex 10: Read a float number and
int main( )
display its floor and ceiling.
{
float x;
Ex 11: Read three sides of a triangle
int a; /* contains rounded result */
and display its area. Check for open
and closed triangle.
printf( “\nEnter float number: ”);
scanf(“%f”, &x);
a= (int)(x + 0.5);
printf( “\nRounded integer is: %d ”, a);
return 0;
}

6.The switch statement


The C switch is similar to Pascal's case statement and it allows multiple choice of a selection of
items at one level of a conditional where it is a far neater way of writing multiple if statements:
   switch (expression) {
case item1:
statement1;
break;
case item2:
statement2;
break;

case itemn:
statementn;
break;
default:
statement;
break;
}
In each case the value of itemi must be a constant, variables are not allowed. The break is
needed if you want to terminate the switch after execution of one choice. Otherwise the next
case would get evaluated. Note: This is unlike most other languages.
We can also have null statements by just including a ; or let the switch statement fall through
by omitting any statements (see e.g. below).
The default case is optional and catches any other cases.
For example:-
           switch (letter)
{
case `A':
case `E':
case `I':
case `O':
case `U':
numberofvowels++;
break;

Page 13 of 16 [Chapter 2] [Modified – 2]


 
case ` ':
numberofspaces++;
break;
 
default:
numberofconstants++;
break;
}
In the above example if the value of letter is `A', `E', `I', `O' or `U' then number of vowels is
incremented. If the value of letter is ` ' then number of spaces is incremented. If none of these
is true then the default condition is executed, that is number of constants is incremented.
Exercises
1. Write a program to read two characters, and print their value when interpreted as a 2-digit
hexadecimal number. Accept upper case letters for values from 10 to 15.
2. Read an integer value. Assume it is the number of a month of the year; print out the name of
that month.
3. Given as input three integers representing a date as day, month, year, print out the number
day, month and year for the following day's date.
Typical input: 28 2 1992 Typical output: Date following 28:02:1992 is 29:02:1992
4. Write a program which reads two integer values. If the first is less than the second, print the
message up. If the second is less than the first, print the message down If the numbers are
equal, print the message equal If there is an error reading the data, print a message containing
the word Error and perform exit( 0 );

7. The sizeof( ) operator: It returns the size of its argument in bytes.


The argument may be:
- An identifier
- A constant
- A standard data type
- User defines data type
Ex
#include <stdio.h> #include <stdio.h>

int main( ) int main( )


{ int a, b, c; {
double x; int a, b,
float pi = 3.14;
a = sizeof(int);
b= sizeof( 4); a = sizeof(pi);
c= sizeof(x); b = sizeof(3.14);
printf( “%d%d%d%”, a,b,c); printf( “ %d%d%d”, a, b);
return 0; return 0;
} }

//sizeof1.c //sizeof2.c
#include <stdio.h> #include <stdio.h>
int main( )
int main ( ) {
{ int a, b; int a, b, c;
b= 10;
a= sizeof( ++ b ); b=10, c = 20;
printf( “%d%d”, a, b); a = sizeof(b + c);
return 0; printf( “%d”, a);
} Page 14 of 16 [Chapter 2] return 0; – 2]
[Modified
}
9. Low Level Operators and Bit Fields
Many programs (e.g. systems type applications) must actually operate at a low level where
individual bytes must be operated on.
Bitwise Operators
The bitwise operators of C a summarised in the following table:

Table: Bitwise operators


& AND
OR

XOR
One's Compliment
 
 
<< Left shift
>> Right Shift
The is a unary operator -- it only operates on one argument to right of the operator.
The shift operators perform appropriate shift by operator on the right to the operator on the left.
The right operator must be positive. The vacated bits are filled with zero (i.e. There is NO
wrap around).
For example: x << 2 shifts the bits in x by 2 places to the left.
So:
if x = 00000010 (binary) or 2 (decimal)
then:
or 0 (decimal)
Also: if x = 00000010 (binary) or 2 (decimal)
or 8 (decimal)
Therefore a shift left is equivalent to a multiplication by 2.
Similarly a shift right is equal to division by 2
NOTE: Shifting is much faster than actual multiplication (*) or division (/) by 2. So if you
want fast multiplications or division by 2 use shifts.
//bit1.c
#include <stdio.h>
int main() {
char x = 12, y=10, a, b, c, d;
clrscr();
a = x | y;
printf("\n%d", a);
b = x & y;
printf("\n%d", b);

c = x ^ y;
printf("\n%d", c);

d = ~x;
printf("\n%d", d);

return 0;
}
Page 15 of 16 [Chapter 2] [Modified – 2]
// Discuss exercises asked on campus & CDEC

Page 16 of 16 [Chapter 2] [Modified – 2]

You might also like