Upload
rajesh-gct-n
View
213
Download
0
Embed Size (px)
Citation preview
8/6/2019 c Basopr Ref
1/35
C Basics and Operators
8/6/2019 c Basopr Ref
2/35
Objectives
Understand the need of Programming Language
Understand the structure of a C program
Understand variables and constants
Perform basic input & output operations with correctformat specifiers
Use of operators and applying precedence rules Understand type casting
8/6/2019 c Basopr Ref
3/35
3Programming Languages
What is the need of Programming Languages? What do you expect aprogramming language to do?
>> To express the algorithm for solving a particular problem so
that computer can understand that. What are the intended features?
>> Clarity
>> Simplicity
>> Easy to translate( i.e. compilation should be efficient)>> Support for Abstraction
What are the different kinds of programming languages?
>> Procedural Languages e.g. C>> Object Oriented Languages e.g. Java
>> Functional Languages e.g. LISP
>> Logic Programming Languages e.g. Prolog
8/6/2019 c Basopr Ref
4/35
4Programming Languages
Features of C Programming Language
Low-level access to computer memory by converting
machine addresses to typed pointers
Array indexing as a secondary notion, defined in terms ofpointer arithmetic
A preprocessor for macro definition, source code fileinclusion, and conditional compilation
Complex functionality such as I/O, string manipulation, andmathematical functions consistently delegated to library
routines
8/6/2019 c Basopr Ref
5/35
5Structure of a single file C program
Basic C program Structure
Preprocessor Commands
Type definitions
Function prototypes
Variables
Functions
We must have a main() function
The main function is where a program starts execution. It is generally
the first user-written function run when a program starts.
The value returned from the main function becomes the exit status of
the process, though the C standard only ascribes specific meaning totwo values: for normal exit it is taken as 0 i.e. by specifying return 0;
8/6/2019 c Basopr Ref
6/35
6Basic structure of a C program
Documentation Section..........Link Section..........Definition Section.....
.....Global declaration Section.....
.....main() function section
.....{
..........Declaration Section
.....
..........Executable Section
.....}
.....Sub-program Section .....function1
.....{
..........Statements
.....} .....function2
.....{
..........Statements
.....} .....function3
.....{
..........Statements
.....}
8/6/2019 c Basopr Ref
7/35
Example C program
/*******************************************************************************Example Program
********************************************************************************/
#include
int main(){
printf("hello, world\n");
/*
some very clever code I haven't quite sorted out yet.
*/
printf("the solution to the problem of life, the universe and everythingis");
/*
more very clever code still to be developed
*/
return 0;
}
8/6/2019 c Basopr Ref
8/35
8Identifiers
In computer languages identifiers are textual tokens (also calledsymbols) which name language entities. Some of the kinds of entitiesan identifier denotes include variables, types, labels, subroutines,and packages.
Computer languages usually place restrictions on what charactersmay appear in an identifier.
C Programming Identifier rules
Identifiers must begin with a letter of the alphabet. In C, the underscore
character (_) is considered a letter. The first letter may be followed by a sequence of letters and / or digits.
The compiler regards upper case and lower case
No variable name may be a keyword.
Example
Grosspay, count, _total, PI, top_value, max123
89_var this is not allowed
8/6/2019 c Basopr Ref
9/35
Data types - Variables
Variables are those whose value can be changed during the course ofexecution of the program. That way, the compiler knows what the
variables are called and what type of variables they are (what values theycan contain).
int - data type - int is used to define integer numbers. int Count;
Count = 5;
float - data type - float is used to define floating point numbers.
float Miles;
Miles = 5.6;
double - data type - double is used to define BIG floating point numbers.Generally, it reserves twice the storage for the number.
double Atoms;
Atoms = 2500000;
char - data type - char defines characters.
char Letter;
Letter = 'x';
8/6/2019 c Basopr Ref
10/35
10Data types - Modifiers
Modifiers - The data types above have the following modifiers.
short / long
signed / unsigned
The modifiers define the amount of storage allocated to the variable.The amount of storage allocated is not cast in stone. ANSI has thefollowing rules:
short int
8/6/2019 c Basopr Ref
11/35
11Data Types Modifiers
This table shows size of different data types on some platformNote: You can find out how much storage is allocated to a data type on particularplatform by using the sizeof operator.
9612long double
648Double
324float0 -> +25581unsigned char
-128 -> +12781signed char
-2,147,483,648 -> +2,147,483,647324long int
-2,147,483,648 -> +2,147,483,647324int
0 -> +4,294,967,295324unsigned int
0 -> +65,535162unsigned short int
-32,678 -> +32,767162short intRangeBitsBytesType
8/6/2019 c Basopr Ref
12/35
12Data Types - const
const
The const qualifier is used to tell C that the variable value can not change
after initialization.
const float pi=3.14159; pi cannot be changed at a later time within the program.
Example
#include
main(){
const int Men=10;
Men = 20; /* This will be failed by the compiler. */
}
const int and int const would give the same effect. Try it!!
8/6/2019 c Basopr Ref
13/35
Printing Output
printf()
The printf function allows you to send output to standard outputdevice (consider it to be the screen).
#include int main(){
int num1, num2, sum;num1 = 5;num2 = 7;sum = num1 + num2;printf("%d + %d = %d\n", num1, num2, sum);return 0;
}
Note : %d for integers , %f for float , %c for character,%ld for long int,
8/6/2019 c Basopr Ref
14/35
Accepting Inputs
scanf()
The scanf function allows you to accept input from standard input(generally the keyboard) .
#include int main(){
int num1, num2, sum;printf(\nEnter two intgers :);
scanf(%d%d,&num1, &num2);sum = num1 + num2;printf("%d + %d = %d\n", num1, num2, sum);return 0;
}
%c for character, %f for float, %s for strings
8/6/2019 c Basopr Ref
15/35
15Accepting Inputs
scanf("%d", &num1);
The statement will read in an integer value that the user enters on thekeyboard and place that value into address represented by num1.
num1 must be declared previously as an integer .
Note the & (means scanf will put the value entered in theaddress of the variable)
Example MenRespond and WomenRespond have to be declared. int main()
{
printf(" Men are from");
scanf("%s", MenRespond);
printf(", and women are from"); scanf("%s", WomenRes);
}
8/6/2019 c Basopr Ref
16/35
Operators
C provides rich set of operators to facilitates the computation
Basic Arithmetic Operators (+,-,*,/,%)
Assignment Operators( = , +=, -=,...)
Following programs illustrate the use of the these operatorint main(){
int nX, nY, nZ;
nX = 1; // assign 1 to nXnY = 2; // assign 2 to nYnZ = nX + nY; // assign the sum of nX and nY to nZnX = nX - 2; // subtract 2
nX /= 10; // divide by 10
nZ += nZ; // doubles nZnX = nX * nX; // squarenY *= nY; // squarenZ = nX % nY // assign the remainder after nX / Ny to nZ
nX %= 2; // modulus with 2
}
8/6/2019 c Basopr Ref
17/35
17Operators
Increment(++) & Decrement operators(- - )
PRE means do the operation first followed by any operation. POST
means do the operation after any operation.
Consider the following statements ++count; /* PRE Increment, means add one to count */
count++; /* POST Increment, means add one to count */
--count; /* PRE Decrement, means subtract one from count */
count--; /* POST Decrement, means subtract one from count */
In the above example, because the value of count is not assigned toany variable, the effects of the PRE/POST operation are not clearlyvisible. Now see the next slide for the difference.
8/6/2019 c Basopr Ref
18/35
18Operators
Consider the following program,
#include
int main()
{int count = 0, loop;
loop = ++count; /* same as count = count + 1; loop = count; */
printf("loop = %d, count = %d\n", loop, count);
loop = count++; /* same as loop = count; count = count + 1; */printf("loop = %d, count = %d\n", loop, count);
}
Sample Program Output
loop = 1, count = 1
loop = 1; count = 2
Did you get the difference now??
The same stands true for decrement operators too.
8/6/2019 c Basopr Ref
19/35
19Operators
Relational Operators ( > , < , >= ,
8/6/2019 c Basopr Ref
20/35
20Operators
Logical Operators ( && , | | , !) They compare or evaluate logical and relational expressions.
Logical AND (&&)
This operator is used to evaluate 2 conditions or expressions with relationaloperators simultaneously. If both the expressions to the left and to the right ofthe logical operator is true then the whole compound expression is true.
a > b && x = = 10
Logical OR (||)
The logical OR is used to combine 2 expressions and the condition evaluates
to be true if any one of the 2 expressions is true. a < m || a < n
Logical NOT (!)
The logical not operator takes single expression and evaluates to true if theexpression is false and evaluates to false if the expression is true. In other
words it just reverses the value of the expression. !(x >= y) -The NOT expression evaluates to false only if the value of x is either
greater than or equal to y
8/6/2019 c Basopr Ref
21/35
21Operators
Bitwise operators ( & , | , ^ , > , ~)
| (Bitwise OR) sets a bit to 1 if one or both of the corresponding bits in itsoperands are 1, and to 0 if both of the corresponding bits are 0.
& (Bitwise AND) sets a bit to 1 if and only if both of the corresponding bitsin its operands are 1, and to 0 if the bits differ or both are 0.
^ (Bitwise XOR or exclusive OR) sets the bit to 1 where thecorresponding bits in its operands are different, and to 0 if they are thesame.
~ (Bitwise NOT) takes only one parameter and inverts each bit in theoperand, changing all the ones to zeros and zeros to ones.
int num1 =10,num2 = 20;
num1 ^= num2; num2 ^= num1;
num1 ^= num2;
What would be the output? Just check on your machine and then take bitby bit operation on both the numbers by hand and justify the answer!
8/6/2019 c Basopr Ref
22/35
22Bitwise Operator : example
#includeint main (){int i=64;int j=56;
printf("the result of different bit operations on the data\n")
printf("the AND Operation on i and j=%d\n",i&j); /* results is zero as there is no pair ofones at the same position in the binaryequivalent of the numbers*/
printf("the OR Operation on i and j=%d",i|j); // with the similar calculation it gives 120
printf("the XOR operation on i and j=%d",i^j); // 120 will be the value
printf(" left shifting of i by 3=%d",i
8/6/2019 c Basopr Ref
23/35
23Operators
Unary operators (& , * , + , - sizeof, !, ~, ++, - -)
Operates on single operand.
& : address of operator (will be more clear when pointers will be
discussed )
* : Dereferencing operator (This too is related to pointers)
+ , - : unary plus and minus respectively
10 * (-10)
Sizeof is used to find out memory allocated for the entity
sizeof(int);
sizeof(123);
8/6/2019 c Basopr Ref
24/35
24Shift Operators
are called as shift operators.
If we do a
8/6/2019 c Basopr Ref
25/35
25Shift Operations (Left shift)
What is the decimal equivalent of this number? 54
So left shift multiplies the number by 2 . But what happens if a=4294967295 and youapply the left shift on that. you will get unpredictable results. Why?
Because the value given above is the maximum value which can be represented byunsigned integer. In that case the result after multiplying it by 2 will go beyond therange of the unsigned integer and hence it will give wrong result.
So we have to take one thing in our mind while using left shift as a multiplicative
operation tool that our result should not go beyond the limit of the unsigned integer(Limit can be calculated as Pow(2,8*sizeof(int)-1).
Though Left shift operation can be applied on negative integers also but the resultsmay be unpredictable This is why, they should be applied to unsigned integers only.
8/6/2019 c Basopr Ref
26/35
26Shift Operators
If we do a>>2 (considering the a as unsigned integer), a will be shiftedto right by 2 position. What does it mean? It means every bit of binaryequivalent of the number will be shifted to right . Obviously rightmost bitwill be gone and one place will be created at leftmost position to
maintain the fixed length of the number. See below for example.Let us take a=27;
binary equivalent of it( assuming the size of integer as 4 bytes) is:
00000000000000000000000000011011
If we shift this number by one i.e. a>>1 then the number will be000000000000000000000000000001101.
See, right most 1 has gone and we added one extra 0 at left most
position.
8/6/2019 c Basopr Ref
27/35
27Shift Operations (Right shift)
What is the decimal equivalent of this number? 13
So right shift divides (integer division) the number by 2 .
Fortunately we can apply right shift on any number with in the range ofunsigned integer as by division, result does not go beyond the limit inany case.
Again , right shift operations are also suggested to be applied for
unsigned integers only
A short program is shown to illustrate these operations as below:
8/6/2019 c Basopr Ref
28/35
28Shift Operators( right shift) example
In this example we are printing the power table of 2 i.e. 2, 4,8 andreverse power table of 2 like 1024,512,256..
int main ()
{
unsigned int number=2;int count;
printf("Table of power of 2 using bitwise operator\n");
printf("%u\n",number);for(count=1;count
8/6/2019 c Basopr Ref
29/35
29Precedence and Parentheses
In an expression that contains more than one operator, the order in whichoperations are performed can be confusing.
Usually operator with higher precedence is performed first. But a subexpression enclosed in the parentheses ( ) is evaluated first, without regard
to the operator precedence because parentheses have the highestprecedence.
For example:
Evaluate 25 - (2 * (10 + (8 / 2)));
( 5 + 10 ) == ( 3 * 5 )
so depth of the parentheses is deciding the order of evaluation here andhence 8/2 will be evaluated first
But in expressions like following, order of evaluation is determined byprecedence and associatively rules. (described in the next slide)
-2 * b + b * b 4 * a * c (Root of quadratic equation)
8/6/2019 c Basopr Ref
30/35
Operators Precedence & Associativity
Operator precedence combined with associativity determines the order ofevaluation. Following is the table of precedence and associativity with all operators
Operators Associativity( ) [] -> . Left to right! - ++ -- + * & (type-cast) sizeof Right to left(in the above line, +, - and * are the unary forms)* / % Left to right+ - (Binary) Left to right> Left to right< >= Left to right
== != Left to right& Left to right^ Left to right| Left to right&& Left to right|| Left to right?: Left to right= += -= *= /= %= &= ^= |= = Right to left, Left to right
Now can you describe the order of evaluation in this expression ?.
-2 * b + b * b 4 * a * c
8/6/2019 c Basopr Ref
31/35
Logical Operators
Expressions connected by Logical operators(&& , ||) areevaluated from Left to right and evaluation stops as soon asthe truth or falsehood value of whole expression is known. Forexample in the expression a||b||c, if value of a is non-zero(true)
then the value of whole expression is evaluated as true andb||c will not be evaluated.
Operand to a logical operator is false if it is 0 and true foranything nonzero
Numeric value of relational & logical expressions are 1 or 0
Unary negation(!) converts nonzero operand into 0 and 0 to 1
8/6/2019 c Basopr Ref
32/35
32Type Cast
During the program development, you may encounter the situationswhere you need to convert to the different data type from previouslydeclared variables, as well as having mixed data type in oneexpression.
For example, let say you have declared the following variables:
int total, number;
float average;
But in the middle of your program you encountered the followingexpression:
average = total / number;
This expression has mixed data type, int and float. The value of the
average will be truncated, and it is not accurate anymore. Many compilerswill generate warning and some do not, but the output will be inaccurate.
8/6/2019 c Basopr Ref
33/35
33Type Cast
C provides the unary (take one operand only) typecast operator toaccomplish this task. The previous expression can be re written as
average = (float) total / number;
This (float) is called type cast operator, which create temporary floating-point copy of the total operand. The construct for this typecast operator
is formed by placing parentheses around a data type name as:
(type) such as (int), (float) and (char).
In an expression containing the data types int and float for example, theANSI C standard specifies that copies of int operands are made andpromoted to float.
Implicitly, actually, only a temporary version of each new value (type) iscreated and used for the mixed-type expression, the original value withoriginal type still remain unchanged.
The same is true with mix of char and int and int and unsigned int.
8/6/2019 c Basopr Ref
34/35
34Implicit Type Cast - Example
#includeint main ()
{
int i;int j=65;
float f=87.54;float g;i=f; //here implicit type conversion takes place from float to integer
g=j; // Here implicit type conversion takes place from integer to float
printf ("i = %d; g = %f\n", i, g); // due to implicit type conversion 87 and65.000 will be printed
return 0;}
8/6/2019 c Basopr Ref
35/35
Thank you