Datatype and Operators used in C Programming

RhishavPoudyal 12 views 79 slides Jul 08, 2024
Slide 1
Slide 1 of 79
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79

About This Presentation

Datatypes and operators in C


Slide Content

DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 1

 The compiler collects the characters of a program into tokens . Tokens make up the basic vocabulary of a computer language.  The compiler then checks the tokens to see if they can be formed into legal strings according to the syntax (the grammar rules) of the language. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 2 2

 Lowercase letters a b c . . . z  Uppercase letters A B C . . . Z  Digits 0 1 2 3 4 5 6 7 8 9  Other characters ◦ + - * / = ( ) { } [ ] < > „ “ ! @ # $ % & _ ^ ~ \ . , ; : ?  White space characters blank, newline, tab, etc. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 3 3

 Keywords  Identifiers  Constants  String Constants  Operators  Special symbol DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 4 4

 A 'C' program consist of two types of elements , user defined and system defined. Identifiers is nothing but a name given to these elements.  An identifier is a word used by a programmer to name a variable , function, or label.  identifiers consist of letters and digits, in any order, except that the first character or label.  Identifiers consist of letters and digits if any order, except that the first character must be letter.  Both Upper and lowercase letters can be used DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 5 5

 Keywords are nothing but system defined identifiers.  Keywords are reserved words of the language.  They have specific meaning in the language and cannot be used by the programmer as variable or constant names  C is case senitive, it means these must be used as it is  32 Keywords in C Programming auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while 6 DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 6

 Variables in C have the same meaning as variables in algebra. That is, they represent some unknown, or variable, value. x = a + b z + 2 = 3(y - 5)  Remember that variables in algebra are represented by a single alphabetic character. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 7

 Variables in C may be given representations containing multiple characters. But there are rules for these representations.  Variable names in C May only consist of letters, digits, and underscores May be as long as you like, but only the first 31 characters are significant May not begin with a number May not be a C reserved word (keyword) DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 8

 An identifier is a token: Composed of a sequence of letters , digits , and the underscore character _ Note: Variable names are identifiers  Lower- and uppercase letters are treated as distinct (different) .  Identifiers should be chosen so that they contribute to the readability and documentation of the program. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 9

 m a i n C programs always begin execution at the function main.  Identifiers that begin with an underscore should be used only by systems programmers Because they can conflict with system names. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 10

 C programmers generally agree on the following conventions for naming variables. Begin variable names with lowercase letters Use meaningful identifiers Separate “words” within identifiers with underscores or mixed upper and lower case. Examples: surfaceArea surface_Area surface_area Be consistent! DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 11

(used in  Use all uppercase for symbolic constants #define preprocessor directives).  Examples: #define PI 3.14159 #define AGE 52 DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 12

 C is case sensitive It matters whether an identifier , such as a variable name, is uppercase or lowercase. Example: area Area AREA ArEa are all seen as different variables by the compiler. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 13

 Legal variable names ClassSize _previous_value Percent PerC e nt PERCENT Kdff123 kkkkk DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 14

identifiers reasons savings#account Contains the illegal character # Double Is a C keyword rad ius Space is illegal Tax-Rate - is illegal union A reserved word 9winter First character is a digit 15 DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 15

area_under_the_curve num45 #v a l u es pi %done A R EA 3D Las t - C h ance x_yt3 num$ lucky*** DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 16

 Integer Constants 25 and  Floating Constants 3.14159 and 0.1  Character Constants „a‟ and „B‟ and „+‟ and „;‟ but not “a” or “B” DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 17

 The backslash is called the escape character . The newline character „\n‟ represents a single character called newline. Think of \n as “ escaping ” the usual meaning of n. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 18

 A sequence of characters enclosed in a pair of double quote marks, such as “abc” is a string constant , or a string literal .  Character sequences that would have meaning if outside a string constant are just a sequence of characters when surrounded by double quotes.  String constants are treated by the compiler as tokens and the compiler provides the space in memory to store them. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 19

 Before using a variable, you must give the compiler some information about the variable; i.e., you must declare it.  The declaration statement includes the data type of the variable.  Examples of variable declarations: int balls ; float area ; DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 20

There are five basic data types associated with variables:  int - integer: a whole number.  float - floating point value: ie a number with a fractional part.  double - a double-precision floating point value.  char - a single character.  void - valueless special purpose type DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 21

A Data type or simply type is a classification of data which tells the compiler or interpreter how the programmer intends to use the data  Primary Data Types(Fundamental Data Types) Integer: int -3 2,768 to 32,768. Character: char -128 to 127. Floating Point: float 3.4e-38 to 3.4e+38. Double Precision Floating Point: double 1.7e- 308 to 1.7e+308. Void Data Type: void (used for function when no value is to be return) DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 22

Data Types in C

A Data Type A data type is A set of values AND A set of operations on those values A data type is used to Identify the type of a variable when the variable is declared Identify the type of the return value of a function Identify the type of a parameter expected by a function VARIABLES ,INPUT AND OUTPUT 24 Prepared by :Er. Rhishav Poudyal

A Data Type (continued) When the compiler encounters a declaration for a variable, it sets up a memory location for it An operator used on a variable or variables is legal only if The operator is defined in that programming language for a variable of that type The variable or variables involved with the operator are of the same or compatible types VARIABLES ,INPUT AND OUTPUT 25 Prepared by :Er. Rhishav Poudyal

Two Classifications of Data Types Built-in data types Fundamental data types ( int, char, double, float, void, pointer ) Derived data types (array, string, structure) Programmer-defined data types Structure Union Enumeration VARIABLES ,INPUT AND OUTPUT 26 Prepared by :Er. Rhishav Poudyal

VARIABLES ,INPUT AND OUTPUT 27 Prepared by :Er. Rhishav Poudyal

Data types in C Only really four basic types: char int (short, long, long long , unsigned) float double Type Size (bytes) char 1 int 4 short 2 long 4 long long 8 float 4 double 8 VARIABLES ,INPUT AND OUTPUT 28 Prepared by :Er. Rhishav Poudyal

Fundamental Data Types void – used to denote the type with no values int – used to denote an integer type char – used to denote a character type float, double – used to denote a floating point type int * , float * , char * – used to denote a pointer type, which is a memory address type VARIABLES ,INPUT AND OUTPUT 29 Prepared by :Er. Rhishav Poudyal

FIGURE Integer Types VARIABLES ,INPUT AND OUTPUT 30 Prepared by :Er. Rhishav Poudyal

sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long) Note VARIABLES ,INPUT AND OUTPUT 31 Prepared by :Er. Rhishav Poudyal

Table Typical Integer Sizes and Values for Signed Integers VARIABLES ,INPUT AND OUTPUT 32 Prepared by :Er. Rhishav Poudyal

FIGURE Floating-point Types VARIABLES ,INPUT AND OUTPUT 33 Prepared by :Er. Rhishav Poudyal

sizeof (float) ≤ sizeof (double) ≤ sizeof (long double) Note VARIABLES ,INPUT AND OUTPUT 34 Prepared by :Er. Rhishav Poudyal

Characters (char) Roman alphabet, punctuation, digits, and other symbols: Encoded within one byte (256 possible symbols) ASCII encoding In C: char a_char = ’ a ’ ; char newline_char = ’ \n ’ ; char tab_char = ’ \t ’ ; char backslash_char = ’ \\ ’ ; VARIABLES ,INPUT AND OUTPUT 35 Prepared by :Er. Rhishav Poudyal

ASCII From “ man ascii ” : | 0 NUL| 1 SOH| 2 STX| 3 ETX| 4 EOT| 5 ENQ| 6 ACK| 7 BEL| | 8 BS | 9 HT | 10 NL | 11 VT | 12 NP | 13 CR | 14 SO | 15 SI | | 16 DLE| 17 DC1| 18 DC2| 19 DC3| 20 DC4| 21 NAK| 22 SYN| 23 ETB| | 24 CAN| 25 EM | 26 SUB| 27 ESC| 28 FS | 29 GS | 30 RS | 31 US | | 32 SP | 33 ! | 34 " | 35 # | 36 $ | 37 % | 38 & | 39 ' | | 40 ( | 41 ) | 42 * | 43 + | 44 , | 45 - | 46 . | 47 / | | 48 0 | 49 1 | 50 2 | 51 3 | 52 4 | 53 5 | 54 6 | 55 7 | | 56 8 | 57 9 | 58 : | 59 ; | 60 < | 61 = | 62 > | 63 ? | | 64 @ | 65 A | 66 B | 67 C | 68 D | 69 E | 70 F | 71 G | | 72 H | 73 I | 74 J | 75 K | 76 L | 77 M | 78 N | 79 O | | 80 P | 81 Q | 82 R | 83 S | 84 T | 85 U | 86 V | 87 W | | 88 X | 89 Y | 90 Z | 91 [ | 92 \ | 93 ] | 94 ^ | 95 _ | | 96 ` | 97 a | 98 b | 99 c |100 d |101 e |102 f |103 g | |104 h |105 i |106 j |107 k |108 l |109 m |110 n |111 o | |112 p |113 q |114 r |115 s |116 t |117 u |118 v |119 w | |120 x |121 y |122 z |123 { |124 | |125 } |126 ~ |127 DEL| Special control characters VARIABLES ,INPUT AND OUTPUT 36 Prepared by :Er. Rhishav Poudyal

 When we declare a variable Space is set aside in memory to hold a value of the specified data type That space is associated with the variable name That space is associated with a unique address  Visualization of the declaration int balls ; balls DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 37 F E07 garbage

C has three basic predefined data types:  Integers (whole numbers) int , long int, short int, unsigned int  Floating point (real numbers) float , double  Characters char  At this point, you need only be concerned with the data types that are bolded. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 38

 Variables may be be given initial values, or initialized , when declared. Examples: int length = 7 ; float diameter = 5.9 ; char initial = „A‟ ; 7 5.9 „A‟ le n g th diameter i n i t ial DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 39

 Do not “hide” the initialization put initialized variables on a separate line a comment is always a good idea Example: /* rectangle height */ int height ; int width = 6 ; int area ; /* rec ta n g le width */ /* rectangle area */ NOT int height, width = 6, area ; DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 40

 Variables may have values assigned to them through the use of an assignment statement .  Such a statement uses the assignment operator =  This operator does not denote equality. It assigns the value of the righthand side of the statement (the expression ) to the variable on the lefthand side.  Examples: diameter = 5.9 ; area = length * width ; Note that only single variables may appear on the lefthand side of the assignment operator. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 41

#include <stdio.h> int main( ) { int inches, feet, fathoms ; fathoms = 7 ; feet = 6 * fathoms ; inches = 12 * feet ;    inches f ee t f a t ho m s garbage f a t ho m s 7 garbage f ee t 42 garbage 504 inches DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 42

In order to use these characters, escape sequence is used.  Es c a pe S e qu e n ce s Ch a r a c ter  \b  \f  \n  \r  \t  \v  \\  \'  \"  \?  \0 Backspace Form feed Newline Return Horizontal tab Vertical tab Backslash Single quotation mark Double quotation mark Question mark Null character DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 43

 Operator  +  -  *  /  % Meaning of Operator addition or unary plus subtraction or unary minus multiplication division remainder after division( modulo division) DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 44

Operator example Meaning + a + b Addition –unary - a – b Subtraction- unary * a * b Multiplication / a / b Division % a % b Modulo division- remainder DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 45

 An assignment operator is used for assigning a value to a variable. The most common assignment operator is =  Operator  =  +=  -=  *=  /=  %= E x a m pl e a = b a += b a -= b a *= b a /= b a %= b Same as a = b a = a+b a = a-b a = a*b a = a/b a = a%b DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 46

Operator Meaning < Is less than <= Is less than or equal to > Is greater than >= Is greater than or equal to == Equal to != Not equal to DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 47

 A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.  Relational operators are used in decision making and loops. Operator Meaning of Operator Example  == Equal to 5 == 3 returns  > Greater than 5 > 3 returns 1  < Less than 5 < 3 returns  != Not equal to 5 != 3 returns 1  >= Greater than or equal to 5 >= 3 returns 1  <= Less than or equal to 5 <= 3 return DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 48

Logical Operators DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 49 Operator Meaning && Logical AND || Logical OR ! Logical NOT Logical expression or a compound relational expression- An expression that combines two or more relational expressions Ex: if (a==b && b==c)

C supports 2 useful operators namely Increment ++ Decrement -- operators The ++ operator adds a value 1 to the operand The – operator subtracts 1 from the operand ++a or a++ --a or a-- DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 50

Let the value of a =5 and b=++a then a = b =6 Let the value of a = 5 and b=a++ then a =5 but b=6 i.e.: a prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left a postfix operator first assigns the value to the variable on left and then increments the operand. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 51

Syntax: exp1 ? exp2 : exp3 Where exp1,exp2 and exp3 are expressions Working of the ? Operator: Exp1 is evaluated first, if it is nonzero(1/true) then the expression2 is evaluated and this becomes the value of the expression, If exp1 is false(0/zero) exp3 is evaluated and its value becomes the value of the expression Ex: m=2; n=3 r=(m>n) ? m : n; DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 52

These operators allow manipulation of data at the bit level DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 53 Operator Meaning & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR << Shift left >> Shift right

& bitwise AND | bitwise OR ^ bitwise XOR ~ 1 ‟ s compliment << Shift left >> Shift right DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 54 All these operators can be suffixed with = For instance a &= b; is the same as a = a & b;

a b a&b a|b a^b ~a 1 1 1 1 1 1 1 1 1 1 1 1 DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 55

The other bitwise operators are: ~ bitwise not & bitwise and ^ bitwise xor | bitwise or DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 56

Algebraic expression C expression ab-c a*b-c (m+n)(x+y) (m+n)*(x+y) ab c a*b/c 3x 2 +2x+1 3*x*x+2*x+1 a b a/b S= a  b  c 2 S=(a+b+c)/2 Chapter 3: DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 57

Algebraic expression C expression area= s ( s  a )( s  b )( s  c ) area=sqrt(s*(s-a)*(s-b)*(s-c)) Sin  b     a 2  b 2  sin(b/sqrt(a*a+b*b))  1    x   y    xy 2  2    tow1=sqrt((rowx-rowy)/2+tow*x*y*y )  1       2  x y    xy 2  2  tow1=sqrt(pow((rowx-rowy)/2,2)+tow*x*y*y) y      x sin  y=(alpha+beta)/sin(theta*3.1416/180)+abs(x) DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 58

BODMAS RULE- B rackets o f D ivision M ultiplication A ddition S ubtraction Brackets will have the highest precedence and have to be evaluated first, then comes of , then comes division, multiplication, addition and finally subtraction. The 2 distinct priority levels of arithmetic operators in c are- Highest priority : * / % Lowest priority : + - DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 59

First parenthesized sub expression from left to right are evaluated. If parentheses are nested, the evaluation begins with the innermost sub expression The precedence rule is applied in determining the order of application of operators in evaluating sub expressions The associatively rule is applied when 2 or more operators of the same precedence level appear in a sub expression. Arithmetic expressions are evaluated from left to right using the rules of precedence When parentheses are used, the expressions within parentheses assume highest priority DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 60

Operator Description Associativity ( ), [ ] Function call, array element reference Left to Right +, -, ++, - - ,!,~,*,& Unary plus, minus, increment, decrement, logical negation, 1’s complement, pointer reference, address Right to Left *, / , % Multiplication, division, modulus Left to Right DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 61

Precedence Associativity ( ) * / % + (addition) - (subtraction) < <= > >= == != && || left to right/inside-out left to right left to right left to right left to right left to right left to right DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 62

Evaluate x1=(-b+ sqrt (b*b-4*a*c))/(2*a) @ a=1, b=-5, c=6 DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 63

Evaluate x1=(-b+ sqrt (b*b-4*a*c))/(2*a) @ a=1, b=-5, c=6 =(-(- 5 )+sqrt((-5)(-5)-4*1*6))/(2*1) =( 5 + sqrt((- 5 )(- 5 )-4*1*6))/(2*1) =( 5 + sqrt(25 -4*1*6))/(2*1) =( 5 + sqrt(25 - 4 *6))/(2*1) =( 5 + sqrt(25 - 24 ))/(2*1) =( 5 + sqrt(1))/(2*1) =( 5 + 1.0)/(2*1) =( 6.0 )/(2*1) = 6.0 /2 = 3.0 DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 64

Given int a = 5, b = 7, c = 17 ; evaluate each expression as True or False. 1. c / b == 2 c % b <= a % b b + c / a != c - a 4. (b < c) && (c == 7) 5. (c + 1 - b == 0) || (b = 5) DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 65

Variable Scope

Variable Scope When you declare a variable, that name and value is only “ alive ” for some parts of the program We must declare variables before we use them, so the scope of a variable starts when it is declared If the variable is declared within a block (compound statement, { } ) it only stays alive until the end of the block If the block is the one surrounding the entire function body, the variable is alive from where it is declared until the end of the function If the block defines a loop body or if-statement body, the variable only lives till the end of loop/if You can add a block anywhere you want in the code, and it will define the scope for any variables declared within it VARIABLES ,INPUT AND OUTPUT 67 Prepared by :Er. Rhishav Poudyal

Variable Scope Example scopes int main ( ) { int i ; for ( i =0; i < 10; i ++ ) { int total = i ; } int j = total; // error! total out of scope { int k; // use k } int m = j; … } i j m total k VARIABLES ,INPUT AND OUTPUT 68 Prepared by :Er. Rhishav Poudyal

Variable Scope In C, we can reuse names, as long as they are not in overlapping scopes In fact, we can reuse names in a scope which is nested inside another scope int main ( ) { int i = 5, j = 0; for (j = 0; j < 10; j++) { int i = j; // OK, this is new i int k = 5; doSomething ( i ); } int sum = k; // compile error, no k in scope j = i ; // sets j to 5 for (j = 0; j < 100; j++ ) { int i = j; // yet another new i } int i = 0; // compile error –redefined variable } VARIABLES ,INPUT AND OUTPUT 69 Prepared by :Er. Rhishav Poudyal

Variable Scope All local scope defined by blocks There is another kind of scope, called global scope This is for variables defined outside of functions Global variables have scope from the point they are defined throughout the rest of file Local variables of same name can be nested inside global variables int total = 5; int main ( ) { int total = 4; // OK, this is nested scope …. } int sub1 ( ) { int i = total; // OK, i set to 5 } VARIABLES ,INPUT AND OUTPUT 70 Prepared by :Er. Rhishav Poudyal

Variable Scope Style rules Try to minimize scope Only use global variables if you really, really have to !!! 2 different approaches for local variables inside a function Declare all variables at the top of the function This is the way you used to have to do it in C Helps the reader to know where to look for the variable declaration Declare variables as they are needed Minimizes scope Allows you to set the value only once, rather then once at declaration and then again at first use Either approach is OK – probably the most common in industry is to declare as needed Don’t re-use names heavily, except for maybe i , j, k VARIABLES ,INPUT AND OUTPUT 71 Prepared by :Er. Rhishav Poudyal

PROGRAM Print Sum of Three Numbers VARIABLES ,INPUT AND OUTPUT 72 Prepared by :Er. Rhishav Poudyal

PROGRAM Print Sum of Three Numbers (continued) VARIABLES ,INPUT AND OUTPUT 73 Prepared by :Er. Rhishav Poudyal

PROGRAM Print Sum of Three Numbers (continued) VARIABLES ,INPUT AND OUTPUT 74 Prepared by :Er. Rhishav Poudyal

 Failure to correctly terminate a comment.  Leaving off a closing double quote character at the end of a string.  Misspelling or not declaring a variable.  Misspelling a function name.  Omitting the ampersand ( & ) with scanf( ). DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 75

/* This is a comment */ //This is also a comment The compiler first replaces each comment with a single blank . Thereafter, the compiler either disregards white space or uses it to separate tokens. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 76

Single line of comment: // comment here More than single line of comment or expanded: /* comment(s) here */ // for printf() #include <stdio.h> #include <string.h> // for strcpy_s() and their family /* main() function, where program execution starts */ int main() { /* declares variable and initializes it*/ int i = 8; … DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 77

 Syntax (Compile -Time) Errors Syntax errors are caught by the compiler. The compiler attempts to identify the error and display a helpful error message.  Run-Time Errors Errors that occur during program execution. Memory errors caused by not using the address operator & with a scanf ( ) argument. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 78

 Use white space and comments to make your code easier to read and understand. Indent logical subgroups of code by 3 spaces .  Choose variable names that convey their use in the program.  Place all # includ e , # de f ine , m ai n () , and braces { } -- that begin and end the body of a function. DATA TYPES, OPERATORS AND SOME STATEMENT Prepared by : Er. Rhishav Poudyal 79
Tags