UNIT 5 C’S PROGRAM STRUCTURE
STRUCTURE OF A C PROGRAM The C programming language was designed by Dennis Ritchie as a systems programming language for Unix. A C program basically has the following structure:  Preprocessor Commands  Functions  Variable declarations  Statements & Expressions  Comments Example: #include <stdio.h> int main() { /* My first program*/ printf("Hello, World! n"); return 0; }
PREPROCESSOR COMMANDS • These commands tell the compiler to do preprocessing before doing actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. The standard input and output header file (stdio.h) allows the program to interact with the screen, keyboard and file system of the computer. • NB/ Preprocessor directives are not actually part of the C language, but rather instructions from you to the compiler.
FUNCTIONS • These are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. When this function is prefixed with keyword int, it means this function returns an integer value when it exits. This integer value is retuned using return statement. • The C Programming language provides a set of built-in functions. In the above example printf() is a C built-in function which is used to print anything on the screen. • A function is a group of statements that together perform a task. A C program can be divide up into separate functions but logically the division usually is so each function performs a specific task.
CONT… • A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. • The general form of a function definition in C programming language is as follows: return_type function_name( parameter list ) { body of the function/Function definition }
VARIABLE DECLARATIONS In C, all variables must be declared before they are used. Thus, C is a strongly typed programming language. Variable declaration ensures that appropriate memory space is reserved for the variables. Variables are used to hold numbers, strings and complex data for manipulation e.g. o int x; o int num; int z;
VARIABLES  A variable is a name assigned to a data storage location.  A variable is a location in a computer's memory in which you can store a value and from which you can later retrieve that value  A variable must be defined before it can be used. A variable definition informs the compiler of the variable's name and the type of data it is to hold. Variable names must adhere to the following rules:  The name can contain letters, digits, and the underscore character (_).  The first character of the name must be a letter . The underscore is also a legal first character , but its use is not recommended.  Case matters (that is, upper- and lowercase letters).Thus, the names count and Count refer to two different variables.  Keywords can't be used as variable names.A keyword is a word that is part of the C++ language
LEGAL & ILLEGAL VARIABLE NAMES VARIABLE NAME LEGALITY STATUS Percent Legal y2x5 fg7h Legal annual_profit Legal _1990_tax Legal but not advised savings#account illegal: contains illegal character # double illegal: Is a C++ keyword 9winter illegal: First character is a digit
LEGAL & ILLEGAL VARIABLE NAMES • Because C is case-sensitive, the names percent, PERCENT, and Percent would be considered three different variables. • C programmers commonly use only lowercase letters in variable names, although this isn't required. • Using all-uppercase letters is usually reserved for the names of constants • For many compilers, a C variable name can be up to 31 characters long. (It can actually be longer than that, but the compiler looks at only the first 31 characters of the name.)
NUMERIC DATA TYPES • You need different types of variables because different numeric values have varying memory storage requirements and differ in the ease with which certain mathematical operations can be performed on them. • C's numeric variables fall into the following two main categories: • Integer variables hold values that have no fractional part (that is, whole numbers only). Integer variables come in two flavors: signed integer variables can hold positive or negative values, whereas unsigned integer variables can hold only positive values (and 0). • Floating-point variables hold values that have a fractional part (that is, real
STATEMENTS & EXPRESSIONS • Expressions combine variables and constants to create new values e.g. x + y; • Statements in C are expressions, assignments, function calls, or control flow statements which make up C programs. • An assignment statement uses the assignment operator “=” to give a variable on the operator’s left side the value to the operator’s right or the result of an expression on the right. z = x + y;
COMMENTS • These are non-executable program statements meant to enhance program readability and allow easier program maintenance - they document the program. They are ignored by the compiler. These are used to give additional useful information inside a C Program. All the comments will be put inside /*...*/ or // for single line comments as given in the example above. A comment can span through multiple lines. /* Author: Mzee Moja */ or /* Author: Mzee Moja Purpose: To show a comment that spans multiple lines. Language: C */ or Fr ui t = ap
ESCAPE SEQUENCES • Escape sequences (also called back slash codes) are character combinations that begin with abackslash symbol used to format output and represent difficult-to-type characters. They include: 1. a Alert/bell 2. b Backspace 3. n New line 4. v Vertical tab 5. t Horizontal tab 6. Back slash 7. ’ Single quote 8. ” Double quote 9. 0 Null
NOTE THE FOLLOWING  C is a case sensitive programming language. It means in C printf and Printf will havedifferent meanings.  End of each C statement must be marked with a semicolon.  Multiple statements can be on the same line.  Any combination of spaces, tabs or newlines is called a white space. C is a free-form language as the C compiler chooses to ignore whitespaces. Whitespaces are allowed in any format to improve readability of the code. Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.  Statements can continue over multiple lines.  A C identifier is a name used to identify a variable, function, or any other user- defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers.  A keyword is a reserved word in C. Reserved words may not be used as constants or variables or any other identifier names
SAMPLE PROGRAM  The program will output (print on screen) the statement “My favorite number is 1 because it is first”.  The %d instructs the computer where and in what form to print the value. %d is a type specifier  used to specify the output format for integer numbers.
KEYWORDS • The following list shows the reserved words in C. These reserved words may not be used asconstants or variables or any other identifier names. case extern return union char float short unsigned const for signed void goto continue sizeof volatile if default static while int do struct _packed double C else Long switch break enum register typedef
SOURCE CODE FILES When you write a program in C language, your instructions form the source code/file. C files havean extension .c. The part of the name before the period is called the extension. Object Code, Executable Code and Libraries • An executable file is a file containing ready to run machine code. C accomplishes this in twosteps.  Compiling –The compiler converts the source code to produce the intermediate object code.  The linker combines the intermediate code with other code to produce the executable file.You can compile individual modules and then combine modules later.
LINKING • Linking is the process where the object code, the start up code and the code for library routines used in the program (all in machine language) are combined into a single file- the executable file. •  NB/ An interpreter unlike a compiler is a computer program that directly executes, • i.e. performs, instructions written in a programming, without previously compiling them into a machine language program.  If the compiled program can run on a computer whose CPU or operating system is different from the one on which the compiler runs, the compiler is known as a cross-compiler. •  A program that translates from a low level language to a higher level one is adecompiler. •  A program that translates between high-level languages is usually called a source- to- source compiler or transpiler.
LIBRARY FUNCTIONS • There is a minimal set of library functions that should be supplied by all C compilers, which your program may use. This collection of functions is called the C standard library. The standard library contains functions to perform disk I/O (input/ output), string manipulations, mathematics and much more. When your program is compiled, the code for library functions is automatically added to your program. One of the most common library functions is called printf() which is a general purpose output function. The quoted string between the parenthesis of the printf() function is called an argument. Printf(“This is a C programn”) • The n at the end of the text is an escape sequence tells the program to print a new line as part ofthe output.
C DATA TYPES • In the C programming language, data types refer to a system used for declaring variables or functions of different types. • A data type is, therefore, a data storage format that can contain a specific type or range of values. • The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.
THE BASIC DATA TYPES IN C ARE AS FOLLOWS: Type Description Char Character data and is used to hold a single character.A character can be a letter, number, space, punctuation mark, or symbol - 1 byte long Int A signed whole number in the range -32,768 to 32,767 - 2 bytes long Float A real number (that is, a number that can contain a fractional part) – 4 bytes Double A double-precision floating point value. Has more digits to the right of the decimal point than a float – 8 bytes Void Represents the absence of type. i.e. represents “no data”
USING C’S DATA TYPE MODIFIERS The five basic types (int, float, char,double and void) can be modified to your specific need using the following specifiers.  Signed • Signed Data Modifier implies that the data type variable can store positive values as well as negative values. • The use of the modifier with integers is redundant because the default integer declaration assumes a signed number. The signed modifier is used with char to create a small signed integer. Specified as signed, a char can hold numbers in the range -128 to 127.  Unsigned • If we need to change the data type so that it can only store positive values, “unsigned” datamodifier is used. • This can be applied to char and int. When char is unsigned, it can hold positive numbers inthe range 0 to 255.
CONT...  Long • Sometimes while coding a program, we need to increase the Storage Capacity of a variableso that it can store values higher than its maximum limit which is there as default. • This can be applied to both int and double. When applied to int, it doubles its length, in bits, of the base type that it modifies. For example, an integer is usually 16 bits long. • Therefore a long int is 32 bits in length. When long is applied to a double, it roughly doubles the precision.
CONT…  Short • A “short” type modifier does just the opposite of “long”. If one is not expecting to see highrange values in a program. • For example, if we need to store the “age” of a student in a variable, we will make use of this type qualifier as we are aware that this value is not going to be very high • The type modifier precedes the type name. For example this declares a long integer. • long int age;
INTEGER TYPES Type Storage size Value range Char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 1 byte signed char -128 to 127 2 or 4 bytes Int -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 2 or 4 bytes unsigned int 0 to 65,535 or 0 to 4,294,967,295 2 bytes Short -32,768 to 32,767 2 bytes unsigned short 0 to 65,535 4 bytes Long -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295 Following table gives you details about standard integer types with its storage sizes and value ranges:
FLOATING-POINT TYPES Type Storage size Value range Precision float 4 byte 1.2E-38 to 3.4E+38 6 decimal places double 8 byte 2.3E-308 to 1.7E+308 15 decimal places long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places Following table gives you details about standard floating-point types with storage sizes and value ranges and their precision:
THE VOID TYPE Types and Description 1 Function returns as void.There are various functions in C which do not return value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status); 2 Function arguments as void.There are various functions in C which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void); 3 Pointers to void A pointer of type void * represents the address of an object, but not its type. For example, a memory allocation function void *malloc(size_t size ); returns a pointer to void which can be casted to any data type. The void type specifies that no value is available. It is used in three kinds of situations:
VARIABLE DECLARATION • Declaring a variable tells the compiler to reserve space in memory for that particular variable. A variable definition specifies a data type and the variable name and contains a list of one or more variables of that type .Variables can be declared at the start of any block of code. A declaration begins with the type, followed by the name of one or more variables. For example, • int high, low; • int i, j, k; • char c, ch; float f, salary;
CONT… • Variables can be initialized when they are declared. This is done by adding an equals sign and the required value after the declaration. • • Int high = 250; • Int low = -40; • Int results[20]; /*Maximum Temperature*/ /*Minimum Temperature*/ /* series of temperature readings*/
TYPES OF VARIABLES The Programming language C has two main variable types  Local Variables  Global Variables
CONT… Local Variables A local variable is a variable that is declared inside a function.  Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block.  When execution of the block starts the variable is available, and when the block ends the variable 'dies’. Global Variables Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it. Global variables are declared outside all functions.
SAMPLE PROGRAM #include <stdio.h> int area; //global variable int main () { int a, b; //local variable /* actual initialization */ a = 10; b = 20; printf("t Side a is %d cm and side b is %d cm longn",a,b); area = a*b; printf("t The area of your rectangle is : %d n", area); return 0;
VARIABLE NAMES • Every variable has a name and a value. The name identifies the variable and the value stores data. Every variable name in C must start with a letter; the rest of the name can consist of letters, numbers and underscore characters. C is case sensitive i.e. it recognizes upper and lower case characters as being different. You cannot use any of C’s keywords like main, while, switch etc as variable names, Examples of legal variable names: X result outfilex1 out_file etc • It is conventional in C not to use capital letters in variable names. These are used for names of constants.
DECLARATION VS DEFINITION • A declaration tells the compiler the name and type of a variable and optionally initializes the variable to a specific value. It provides basic attributes of a symbol, its type and its name. If your program attempts to use a variable that hasn't been declared, the compiler generates an error message.A variable declaration has the following form: • A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored. Often, the compiler only needs to have a declaration for something in order to compile a file into an object file, expecting that the linker can find the definition from another file. If no source file ever defines a symbol, but it is declared, you will get errors at link time complaining about undefined symbols. In the following short code, the definition of variable x means that the storage for the variable is that it is a global variable. int x; int main() { x = 3; }
INPUTTING NUMBERS FROM THE KEYBOARD USING SCANF() • Variables can also be initialized during program execution (run time). • The scanf() function is used to read values from the keyboard. For example, to read an integer value use the following general form: scanf(“%d”, &var_name) As in scanf(“%d”, &num) • The %d is a format specifier which tells the compiler that the second argument will be receiving an integer value. • The & preceding the variable name means “address of”. The function allows the function to place a value into one of its arguments.
THE TABLE BELOW SHOWS FORMAT SPECIFIERS OR CODES USED IN THE SCANF() FUNCTION AND THEIR MEANING. %c Read a single character %d Read an integer %f Read a floating point number %lf Read a double %s Read a string %u Read a an unsigned integer When used in a printf() function, a type specifier informs the function that a different type item isbeing displayed.
SAMPLE PROGRAM USING SCANF() #include <stdio.h> int area; //global variable int main () { int a, b; //local variables /* actual initialization */ printf("Enter the value of side a: "); scanf("%d", &a); printf("Enter the value of side b: "); scanf("%d", &b); printf("n"); printf("t You have entered %d for side a and %d for side bn", a, b); area = a*b; printf("t The area of your rectangle is : %d n", area); return 0; }
CONSTANTS • C allows you to declare constants. When you declare a constant it is a bit like a variable declaration except the value cannot be changed during program execution. • The const keyword is used to declare a constant, as shown below: • int const A = 1; const int A =2; • These fixed values are also called literals. • Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. • The constants are treated just like regular variables except that their values cannot be modified after their definition. • C has two types of constants, each with its own specific uses.
LITERAL CONSTANTS • A literal constant is a value that is typed directly into the source code wherever it is needed. examples: • int count = 20; • float tax_rate = 0.28; • The 20 and the 0.28 are literal constants.The preceding statements store these values in the variables count and tax_rate. • Note that one of these constants contains a decimal point, whereas the other does not. The presence or absence of the decimal point distinguishes floating-point constants from integer constants. • A literal constant written with a decimal point is a floating-point constant and is represented by the C++ compiler as a double-precision number . Floating-point constants can be written in standard decimal notation, as shown in these examples: • 123.456, 0.019,100. • Note that the third constant, 100., is written with a decimal point even though it's an integer (that is, it has no fractional part). The decimal point causes the C++ compiler to treat the constant as a double-precision value. Without the decimal point, it is treated as an integer constant.
CONT… • Floating-point constants also can be written in scientific notation. • Scientific notation is particularly useful for representing extremely large and extremely small values. In C++, scientific notation is written as a decimal number followed immediately by an E or e and the exponent: 1.23E2 0.85e-4 >> >> 1.23 times 10 to the 2nd power , or 123 0.85 times 10 to the -4th power , or 0.000085 • A constant written without a decimal point is represented by the compiler as an integer number . Integer constants can be written in three different notations: • A constant starting with any digit other than 0 is interpreted as a decimal integer (that is, the standard base-10 number system). Decimal constants can contain the digits 0 through 9 and a leading minus or plus sign. (Without a leading minus or plus, a constant is assumed to be positive.) • A constant starting with the digit 0 is interpreted as an octal integer (the base-8 number system). Octal constants can contain the digits 0 through 7 and a leading minus or plus sign. • A constant starting with 0x or 0X is interpreted as a hexadecimal constant (the base-16 number system). • Hexadecimal constants can contain the digits 0 through 9, the letters A through F , and a leading minus or plus sign.
SYMBOLIC CONSTANTS • A symbolic constantis a constant that is represented by a name (symbol) in a program. • Like a literal constant, a symbolic constant can't change. Whenever you need the constant's value in your program, you use its name as you would use a variable name. The actual value of the symbolic constant needs to be entered only once, when it is first defined.
SYMBOLIC CONSTANTS C has two methods for defining a symbolic constant: the #define directive and the const keyword. • #define CONSTANTNAME literal • This creates a constant named CONSTNAME with the value of literal. literal represents a literal constant, as described earlier . CONSTANTNAME follows the same rules described earlier for variable names. By convention, the names of symbolic constants are uppercase. This makes them easy to distinguish from variable names, which by convention are lowercase. Example: • #define PI 3.14159 • Note that #define lines don't end with a semicolon (;). #defines can be placed anywhere in your source code, but they are in effect only for the portions of the source code that follow the #define directive. Most commonly, programmers group all #defines together, near the beginning of the file and before the start of main().
CONST KEYWORD • The second way to define a symbolic constant is with the const keyword. const is a modifier that can be applied to any variable declaration. A variable declared to be const can't be modified during program execution--only initialized at the time of declaration. Here are some examples: • const int count = 100; • const float pi = 3.14159; • const long debt = 12000000, float tax_rate = 0.21; • const affects all variables on the declaration line. In the last line, debt and tax_rate are symbolic constants. If your program tries to modify a const variable, the compiler generates an error message, as shown here: • const int count = 100; • count = 200; /* Does not compile! Cannot reassign or alter */ • /* the value of a constant. */ • The practical differences between symbolic constants created with the #define directive and those created with the const keyword have to do with pointers and variable scope.
THE TYPEDEF KEYWORD • The typedef keyword is used to create a new name for an existing data type. In effect, typedef creates a synonym. E.g, the statement • typedef int integer; • creates integer as a synonym for int. You then can use integer to define variables of type int, as in this example: • integer count; • Note that typedef doesn't create a new data type; it only lets you use a different name for a predefined data type.
TYPE CASTING • Type casting is a way to convert a variable from one data type to another. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator as follows: • (type_name) expression •Consider the following example where the cast operator causes the division of one integer variableby another to be performed as a floating-point operation:
PROGRAM #include <stdio.h> main() { int sum = 17, count = 5; double mean; mean = (double) sum / count; printf("Value of mean is %d n", mean ); }
CONT… • When the above code is compiled and executed, it produces the following result: • Value of mean : 3.400000 • It should be noted here that the cast operator has precedence over division, so the value of sum isfirst converted to type double and finally it gets divided by count yielding a double value. • •Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are necessary. •
NOTE: • DO understand the number of bytes that variable types take for your computer. • DO use typedef to make your programs more readable. • DO initialize variables when you declare them whenever possible. • DON'T use a variable that hasn't been initialized. Results can be unpredictable. • DON'T use a float or double variable if you're only storing integers. Although they will work, using them is inefficient. • DON'T try to put numbers into variable types that are too small to hold them. • DON'T put negative numbers into variables with an unsigned type.
Sub section C PROGRAMMING STATEMENTS, EXPRESSIONS, OPERATORS
STATEMENTS • A statement is a complete directive instructing the computer to carry out a specific task. • InC++, statements are usuallywritten one per line, althoughsome statements span multiple lines. • C++ statements always end with a semicolon (except for preprocessor directives such as #define and #include). • Example: x = 2 + 3;
EXPRESSIONS • An expression is anything that evaluates to a numeric value. • C expressions come in all levels of complexity • Simple Expressions • The simplest C expression consists of a single item: a simple variable, literal constant, or symbolic constant. • Here are four expressions: PI 20 rate - 1.25 A symbolic constant (defined in the program) A literal constant A variable Another literal constant • A literal constant evaluates to its own value. • A symbolic constant evaluates to the value it was given when you created it (using the #define directive on const keyword) • A variable evaluates to the current value assigned to it by the program.
COMPLEX EXPRESSIONS • Complex expressions consist of simpler expressions connected by operators. • For example: 2 + 8 • is an expression consisting of the sub-expressions 2 and 8 and the addition operator +. • The expression 2 + 8 evaluates to 10. • You can also write C expressions of great complexity: 1.25 / 8 + 5 * rate + rate * rate / cost • When an expression contains multiple operators, the evaluationof the expression depends on operator precedence
COMPOUND ASSIGNMENT OPERATORS • Compound assignment operators provide a shorthand method for combining a binary mathematical operation with an assignment operation. • For example, say you want to increase the value of x by 5, or , in other words, add 5 to x and assign the result to x.You could write x = x + 5; • Using a compound assignment operator, which you can think of as a shorthand method of assignment, you would write • x += 5; • In more general notation, the compound assignment operators have the following syntax (where op represents a binary operator): • exp1 op= exp2 ; • This is equivalent to writing • exp1 = exp1 op exp2;
COMPOUND STATEMENT OPERATOR • As with all other assignment statements, a compound assignment statement is an expression and evaluates to the value assigned to the left side. • Thus, executing the following statements results in both x and z having the value 14: • x = 12; • z = x += 2;
OVERALL OPERATOR PRECEDENCE
EVALUATE THE EXPRESSIONS BELOW 1. x = 4, y = 7, z = 9; 2. x = (y < 7); 3. z = x++; 4. y = (z==x) | | (x!=1); 5. x = --y; x = 0, y = 5, z = 6; 6. x = y +1; 7. y = z++; 8. z = ++x; 9. x = (y==1) | | (z==0); 10. z = (x!=y) && (x >1); 11. y = !(z < 2);
FIND THE SOLUTIONS x = 0, y = 5, z = 6; x = 4, y = 7, z = 9; 1. x = y +1; 2. y = z++; 3. z = ++x; 4. x = (y==1) | | (z==0); 5. z = (x!=y) && (x >1); 6. y = !(z < 2); 1. x = (y < 7); 2. z = x++; 3. y = (z==x) | | (x!=1); 4. x = --y;
OPERATOR DEFINITION •Operator is the symbol which operates on a value or a variable (operand). For example: + is an operator to perform addition. • • C programming language has a wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as:
OPERATORS IN C PROGRAMMING 1. Arithmetic Operators 2. Increment and Decrement Operators 3. Assignment Operators 4. Relational Operators 5. Logical Operators 6. Conditional Operators 7. Bitwise Operators 8. Special Operators
ARITHMETIC OPERATORS Operator Description Example + Adds two operands A + B will give 30 - Subtracts second operand from the first A - B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by de-numerator B / A will give 2 Assume variable A holds 10 and variable B holds 20 then % Modulus Operator - remainder of after an integer division B % A will give 0 Note: % operator can only be used with integers.
INCREMENT AND DECREMENT OPERATORS – UNARY OPERATORS In C, ++and --are called increment and decrement operators respectively. Both of these operatorsare unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts 1 to operand respectively. For example: Let a=5 a++; //a becomes 6a--; //a becomes 5 ++a; //a becomes 6 --a; //a becomes 5 •
DIFFERENCE BETWEEN ++ AND -- OPERATOR AS POSTFIX AND PREFIX • When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and then increment it. This can be demonstrated by an example: • #include <stdio.h>int main(){ • int c=2; • • printf("%dn",c++); /*this statement displays 2 then, only c incremented by 1 to 3.*/ printf("%d",++c); /*this statement increments 1 to c then, only c is displayed.*/ • return 0; • } • Output • 2 • 4
ASSIGNMENT OPERATORS – BINARY OPERATORS • The most common assignment operator is =. This operator assigns the value in the right side to the left side. For example: • • var=5 //5 is assigned to var • a=c; //value of c is assigned to a5=c; // Error! 5 is a constant Operator Example Same as = a=b a=b += a+=b a=a+b -= a-=b a=a-b *= a*=b a=a*b /= a/=b a=a/b %= a%=b a=a%b NB/ += means Add and Assign etc.
RELATIONAL OPERATORS - BINARY OPERATORS Relational operators check relationship between two operands. If the relation is true, it returns value1 and if the relation is false, it returns value 0. For example: a>b Here, >is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0. Relational operators are used in decision making and loops in C programming.
CONT… Operator Meaning of Operator Example = = Equal to 5= =3 returns false (0) > Greater than 5>3 returns true (1) < Less than 5<3 returns false (0) != Not equal to 5!=3 returns true(1) >= Greater than or equal to 5>=3 returns true (1) <= Less than or equal to 5<=3 return false (0)
LOGICAL OPERATORS - BINARY OPERATORS • Logical operators are used to combine expressions containing relational operators. In C, there are 3 logical operators: Operator Meaning of Operator Example && Logical AND If c=5 and d=2 then,((c= =5) && (d>5)) returns false. | | Logical OR If c=5 and d=2 then, ((c= =5) | | (d>5)) returns true. ! Logical NOT If c=5 then, !(c= =5) returns false.
LOGICAL AND • The following table shows the result of operator && evaluating the expression a&&b: && OPERATOR (and) a b a && b true true true false true false false true false false false false
BOOLEAN LOGICAL OPERATION OR • The operator | | corresponds to the Boolean logical operation OR, which yields true if either of its operands is true, thus being false only when both operands are false. Here are the possible resultsof a | | b: • Explanation • For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the given example. So, the expression is false. For expression ((c==5) | | (d>5)) to be true, either the expression should be true. • • Since, (c==5)is true. So, the expression is true. Since, expression (c==5)is true, !(c==5)is false. | | OPERATOR (or) a b a | | b true true true true false true false true true false false false
CONDITIONAL OPERATOR – TERNARY OPERATORS Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example: c=(c>0)?10:-10; If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
BITWISE OPERATORS Bitwise operators work on bits and performs bit-by-bit operation.
PRECEDENCE OF OPERATORS • If more than one operator is involved in an expression then, C language has a predefined rule of priority of operators. This rule of priority of operators is called operator precedence. • Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity Postfix () [] -> . ++ - - Left to right Unary + - ! ~ ++ - - (type)* & sizeof Right to left * / % Multiplicative Left to right + - Additive Left to right < <= > >= Relational Left to right == != Equality Left to right & Bitwise AND Left to right ^ Bitwise XOR Left to right | Bitwise OR Left to right && Logical AND Left to right | | Logical OR Left to right ?: Conditional Right to left = += -= *= /= %=>>= <<= &= ^= |= Assignment Right to left Comma , Left to right
ASSOCIATIVITY OF OPERATORS Associativity indicates in which order two operators of same precedence (priority) executes. Let us suppose an expression: a= =b!=c Here, operators == and != have the same precedence.The associativity of both == and != is left to right, i.e., the expression in left is executed first and execution take pale towards right.Thus, a==b!=c equivalent to : (a= =b)!=c Operators may be left-associative (meaning the operations are grouped from the left), right- associative (meaning the operations are grouped from the right)
TABLE SHOWING ORDER OF PRECEDENCE Operator Name Associativity Operators Unary right to left ++ -- ! ~ Multiplicative left to right * / % Additive left to right + - Bitwise Shift left to right << >> Relational left to right < > <= >= Equality 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 | | Conditional right to left ? : Assignment right to left = += -= *= /= <<= >>= %= &= ^= |= Comma left to right ,
END

UNIT 5 C PROGRAMMING, PROGRAM STRUCTURE

  • 1.
  • 2.
    STRUCTURE OF AC PROGRAM The C programming language was designed by Dennis Ritchie as a systems programming language for Unix. A C program basically has the following structure:  Preprocessor Commands  Functions  Variable declarations  Statements & Expressions  Comments Example: #include <stdio.h> int main() { /* My first program*/ printf("Hello, World! n"); return 0; }
  • 3.
    PREPROCESSOR COMMANDS • Thesecommands tell the compiler to do preprocessing before doing actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. The standard input and output header file (stdio.h) allows the program to interact with the screen, keyboard and file system of the computer. • NB/ Preprocessor directives are not actually part of the C language, but rather instructions from you to the compiler.
  • 4.
    FUNCTIONS • These aremain building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. When this function is prefixed with keyword int, it means this function returns an integer value when it exits. This integer value is retuned using return statement. • The C Programming language provides a set of built-in functions. In the above example printf() is a C built-in function which is used to print anything on the screen. • A function is a group of statements that together perform a task. A C program can be divide up into separate functions but logically the division usually is so each function performs a specific task.
  • 5.
    CONT… • A functiondeclaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. • The general form of a function definition in C programming language is as follows: return_type function_name( parameter list ) { body of the function/Function definition }
  • 6.
    VARIABLE DECLARATIONS In C,all variables must be declared before they are used. Thus, C is a strongly typed programming language. Variable declaration ensures that appropriate memory space is reserved for the variables. Variables are used to hold numbers, strings and complex data for manipulation e.g. o int x; o int num; int z;
  • 7.
    VARIABLES  A variableis a name assigned to a data storage location.  A variable is a location in a computer's memory in which you can store a value and from which you can later retrieve that value  A variable must be defined before it can be used. A variable definition informs the compiler of the variable's name and the type of data it is to hold. Variable names must adhere to the following rules:  The name can contain letters, digits, and the underscore character (_).  The first character of the name must be a letter . The underscore is also a legal first character , but its use is not recommended.  Case matters (that is, upper- and lowercase letters).Thus, the names count and Count refer to two different variables.  Keywords can't be used as variable names.A keyword is a word that is part of the C++ language
  • 8.
    LEGAL & ILLEGALVARIABLE NAMES VARIABLE NAME LEGALITY STATUS Percent Legal y2x5 fg7h Legal annual_profit Legal _1990_tax Legal but not advised savings#account illegal: contains illegal character # double illegal: Is a C++ keyword 9winter illegal: First character is a digit
  • 9.
    LEGAL & ILLEGALVARIABLE NAMES • Because C is case-sensitive, the names percent, PERCENT, and Percent would be considered three different variables. • C programmers commonly use only lowercase letters in variable names, although this isn't required. • Using all-uppercase letters is usually reserved for the names of constants • For many compilers, a C variable name can be up to 31 characters long. (It can actually be longer than that, but the compiler looks at only the first 31 characters of the name.)
  • 10.
    NUMERIC DATA TYPES •You need different types of variables because different numeric values have varying memory storage requirements and differ in the ease with which certain mathematical operations can be performed on them. • C's numeric variables fall into the following two main categories: • Integer variables hold values that have no fractional part (that is, whole numbers only). Integer variables come in two flavors: signed integer variables can hold positive or negative values, whereas unsigned integer variables can hold only positive values (and 0). • Floating-point variables hold values that have a fractional part (that is, real
  • 11.
    STATEMENTS & EXPRESSIONS •Expressions combine variables and constants to create new values e.g. x + y; • Statements in C are expressions, assignments, function calls, or control flow statements which make up C programs. • An assignment statement uses the assignment operator “=” to give a variable on the operator’s left side the value to the operator’s right or the result of an expression on the right. z = x + y;
  • 12.
    COMMENTS • These arenon-executable program statements meant to enhance program readability and allow easier program maintenance - they document the program. They are ignored by the compiler. These are used to give additional useful information inside a C Program. All the comments will be put inside /*...*/ or // for single line comments as given in the example above. A comment can span through multiple lines. /* Author: Mzee Moja */ or /* Author: Mzee Moja Purpose: To show a comment that spans multiple lines. Language: C */ or Fr ui t = ap
  • 13.
    ESCAPE SEQUENCES • Escapesequences (also called back slash codes) are character combinations that begin with abackslash symbol used to format output and represent difficult-to-type characters. They include: 1. a Alert/bell 2. b Backspace 3. n New line 4. v Vertical tab 5. t Horizontal tab 6. Back slash 7. ’ Single quote 8. ” Double quote 9. 0 Null
  • 14.
    NOTE THE FOLLOWING C is a case sensitive programming language. It means in C printf and Printf will havedifferent meanings.  End of each C statement must be marked with a semicolon.  Multiple statements can be on the same line.  Any combination of spaces, tabs or newlines is called a white space. C is a free-form language as the C compiler chooses to ignore whitespaces. Whitespaces are allowed in any format to improve readability of the code. Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.  Statements can continue over multiple lines.  A C identifier is a name used to identify a variable, function, or any other user- defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers.  A keyword is a reserved word in C. Reserved words may not be used as constants or variables or any other identifier names
  • 15.
    SAMPLE PROGRAM  Theprogram will output (print on screen) the statement “My favorite number is 1 because it is first”.  The %d instructs the computer where and in what form to print the value. %d is a type specifier  used to specify the output format for integer numbers.
  • 16.
    KEYWORDS • The followinglist shows the reserved words in C. These reserved words may not be used asconstants or variables or any other identifier names. case extern return union char float short unsigned const for signed void goto continue sizeof volatile if default static while int do struct _packed double C else Long switch break enum register typedef
  • 17.
    SOURCE CODE FILES When youwrite a program in C language, your instructions form the source code/file. C files havean extension .c. The part of the name before the period is called the extension. Object Code, Executable Code and Libraries • An executable file is a file containing ready to run machine code. C accomplishes this in twosteps.  Compiling –The compiler converts the source code to produce the intermediate object code.  The linker combines the intermediate code with other code to produce the executable file.You can compile individual modules and then combine modules later.
  • 18.
    LINKING • Linking isthe process where the object code, the start up code and the code for library routines used in the program (all in machine language) are combined into a single file- the executable file. •  NB/ An interpreter unlike a compiler is a computer program that directly executes, • i.e. performs, instructions written in a programming, without previously compiling them into a machine language program.  If the compiled program can run on a computer whose CPU or operating system is different from the one on which the compiler runs, the compiler is known as a cross-compiler. •  A program that translates from a low level language to a higher level one is adecompiler. •  A program that translates between high-level languages is usually called a source- to- source compiler or transpiler.
  • 19.
    LIBRARY FUNCTIONS • Thereis a minimal set of library functions that should be supplied by all C compilers, which your program may use. This collection of functions is called the C standard library. The standard library contains functions to perform disk I/O (input/ output), string manipulations, mathematics and much more. When your program is compiled, the code for library functions is automatically added to your program. One of the most common library functions is called printf() which is a general purpose output function. The quoted string between the parenthesis of the printf() function is called an argument. Printf(“This is a C programn”) • The n at the end of the text is an escape sequence tells the program to print a new line as part ofthe output.
  • 20.
    C DATA TYPES •In the C programming language, data types refer to a system used for declaring variables or functions of different types. • A data type is, therefore, a data storage format that can contain a specific type or range of values. • The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.
  • 21.
    THE BASIC DATATYPES IN C ARE AS FOLLOWS: Type Description Char Character data and is used to hold a single character.A character can be a letter, number, space, punctuation mark, or symbol - 1 byte long Int A signed whole number in the range -32,768 to 32,767 - 2 bytes long Float A real number (that is, a number that can contain a fractional part) – 4 bytes Double A double-precision floating point value. Has more digits to the right of the decimal point than a float – 8 bytes Void Represents the absence of type. i.e. represents “no data”
  • 22.
    USING C’S DATATYPE MODIFIERS The five basic types (int, float, char,double and void) can be modified to your specific need using the following specifiers.  Signed • Signed Data Modifier implies that the data type variable can store positive values as well as negative values. • The use of the modifier with integers is redundant because the default integer declaration assumes a signed number. The signed modifier is used with char to create a small signed integer. Specified as signed, a char can hold numbers in the range -128 to 127.  Unsigned • If we need to change the data type so that it can only store positive values, “unsigned” datamodifier is used. • This can be applied to char and int. When char is unsigned, it can hold positive numbers inthe range 0 to 255.
  • 23.
    CONT...  Long • Sometimeswhile coding a program, we need to increase the Storage Capacity of a variableso that it can store values higher than its maximum limit which is there as default. • This can be applied to both int and double. When applied to int, it doubles its length, in bits, of the base type that it modifies. For example, an integer is usually 16 bits long. • Therefore a long int is 32 bits in length. When long is applied to a double, it roughly doubles the precision.
  • 24.
    CONT…  Short • A“short” type modifier does just the opposite of “long”. If one is not expecting to see highrange values in a program. • For example, if we need to store the “age” of a student in a variable, we will make use of this type qualifier as we are aware that this value is not going to be very high • The type modifier precedes the type name. For example this declares a long integer. • long int age;
  • 25.
    INTEGER TYPES Type Storage sizeValue range Char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 1 byte signed char -128 to 127 2 or 4 bytes Int -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 2 or 4 bytes unsigned int 0 to 65,535 or 0 to 4,294,967,295 2 bytes Short -32,768 to 32,767 2 bytes unsigned short 0 to 65,535 4 bytes Long -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295 Following table gives you details about standard integer types with its storage sizes and value ranges:
  • 26.
    FLOATING-POINT TYPES Type Storagesize Value range Precision float 4 byte 1.2E-38 to 3.4E+38 6 decimal places double 8 byte 2.3E-308 to 1.7E+308 15 decimal places long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places Following table gives you details about standard floating-point types with storage sizes and value ranges and their precision:
  • 27.
    THE VOID TYPE Typesand Description 1 Function returns as void.There are various functions in C which do not return value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status); 2 Function arguments as void.There are various functions in C which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void); 3 Pointers to void A pointer of type void * represents the address of an object, but not its type. For example, a memory allocation function void *malloc(size_t size ); returns a pointer to void which can be casted to any data type. The void type specifies that no value is available. It is used in three kinds of situations:
  • 28.
    VARIABLE DECLARATION • Declaringa variable tells the compiler to reserve space in memory for that particular variable. A variable definition specifies a data type and the variable name and contains a list of one or more variables of that type .Variables can be declared at the start of any block of code. A declaration begins with the type, followed by the name of one or more variables. For example, • int high, low; • int i, j, k; • char c, ch; float f, salary;
  • 29.
    CONT… • Variables canbe initialized when they are declared. This is done by adding an equals sign and the required value after the declaration. • • Int high = 250; • Int low = -40; • Int results[20]; /*Maximum Temperature*/ /*Minimum Temperature*/ /* series of temperature readings*/
  • 30.
    TYPES OF VARIABLES TheProgramming language C has two main variable types  Local Variables  Global Variables
  • 31.
    CONT… Local Variables A localvariable is a variable that is declared inside a function.  Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block.  When execution of the block starts the variable is available, and when the block ends the variable 'dies’. Global Variables Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it. Global variables are declared outside all functions.
  • 32.
    SAMPLE PROGRAM #include <stdio.h> intarea; //global variable int main () { int a, b; //local variable /* actual initialization */ a = 10; b = 20; printf("t Side a is %d cm and side b is %d cm longn",a,b); area = a*b; printf("t The area of your rectangle is : %d n", area); return 0;
  • 33.
    VARIABLE NAMES • Everyvariable has a name and a value. The name identifies the variable and the value stores data. Every variable name in C must start with a letter; the rest of the name can consist of letters, numbers and underscore characters. C is case sensitive i.e. it recognizes upper and lower case characters as being different. You cannot use any of C’s keywords like main, while, switch etc as variable names, Examples of legal variable names: X result outfilex1 out_file etc • It is conventional in C not to use capital letters in variable names. These are used for names of constants.
  • 34.
    DECLARATION VS DEFINITION •A declaration tells the compiler the name and type of a variable and optionally initializes the variable to a specific value. It provides basic attributes of a symbol, its type and its name. If your program attempts to use a variable that hasn't been declared, the compiler generates an error message.A variable declaration has the following form: • A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored. Often, the compiler only needs to have a declaration for something in order to compile a file into an object file, expecting that the linker can find the definition from another file. If no source file ever defines a symbol, but it is declared, you will get errors at link time complaining about undefined symbols. In the following short code, the definition of variable x means that the storage for the variable is that it is a global variable. int x; int main() { x = 3; }
  • 35.
    INPUTTING NUMBERS FROMTHE KEYBOARD USING SCANF() • Variables can also be initialized during program execution (run time). • The scanf() function is used to read values from the keyboard. For example, to read an integer value use the following general form: scanf(“%d”, &var_name) As in scanf(“%d”, &num) • The %d is a format specifier which tells the compiler that the second argument will be receiving an integer value. • The & preceding the variable name means “address of”. The function allows the function to place a value into one of its arguments.
  • 36.
    THE TABLE BELOWSHOWS FORMAT SPECIFIERS OR CODES USED IN THE SCANF() FUNCTION AND THEIR MEANING. %c Read a single character %d Read an integer %f Read a floating point number %lf Read a double %s Read a string %u Read a an unsigned integer When used in a printf() function, a type specifier informs the function that a different type item isbeing displayed.
  • 37.
    SAMPLE PROGRAM USINGSCANF() #include <stdio.h> int area; //global variable int main () { int a, b; //local variables /* actual initialization */ printf("Enter the value of side a: "); scanf("%d", &a); printf("Enter the value of side b: "); scanf("%d", &b); printf("n"); printf("t You have entered %d for side a and %d for side bn", a, b); area = a*b; printf("t The area of your rectangle is : %d n", area); return 0; }
  • 38.
    CONSTANTS • C allowsyou to declare constants. When you declare a constant it is a bit like a variable declaration except the value cannot be changed during program execution. • The const keyword is used to declare a constant, as shown below: • int const A = 1; const int A =2; • These fixed values are also called literals. • Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. • The constants are treated just like regular variables except that their values cannot be modified after their definition. • C has two types of constants, each with its own specific uses.
  • 39.
    LITERAL CONSTANTS • Aliteral constant is a value that is typed directly into the source code wherever it is needed. examples: • int count = 20; • float tax_rate = 0.28; • The 20 and the 0.28 are literal constants.The preceding statements store these values in the variables count and tax_rate. • Note that one of these constants contains a decimal point, whereas the other does not. The presence or absence of the decimal point distinguishes floating-point constants from integer constants. • A literal constant written with a decimal point is a floating-point constant and is represented by the C++ compiler as a double-precision number . Floating-point constants can be written in standard decimal notation, as shown in these examples: • 123.456, 0.019,100. • Note that the third constant, 100., is written with a decimal point even though it's an integer (that is, it has no fractional part). The decimal point causes the C++ compiler to treat the constant as a double-precision value. Without the decimal point, it is treated as an integer constant.
  • 40.
    CONT… • Floating-point constantsalso can be written in scientific notation. • Scientific notation is particularly useful for representing extremely large and extremely small values. In C++, scientific notation is written as a decimal number followed immediately by an E or e and the exponent: 1.23E2 0.85e-4 >> >> 1.23 times 10 to the 2nd power , or 123 0.85 times 10 to the -4th power , or 0.000085 • A constant written without a decimal point is represented by the compiler as an integer number . Integer constants can be written in three different notations: • A constant starting with any digit other than 0 is interpreted as a decimal integer (that is, the standard base-10 number system). Decimal constants can contain the digits 0 through 9 and a leading minus or plus sign. (Without a leading minus or plus, a constant is assumed to be positive.) • A constant starting with the digit 0 is interpreted as an octal integer (the base-8 number system). Octal constants can contain the digits 0 through 7 and a leading minus or plus sign. • A constant starting with 0x or 0X is interpreted as a hexadecimal constant (the base-16 number system). • Hexadecimal constants can contain the digits 0 through 9, the letters A through F , and a leading minus or plus sign.
  • 41.
    SYMBOLIC CONSTANTS • Asymbolic constantis a constant that is represented by a name (symbol) in a program. • Like a literal constant, a symbolic constant can't change. Whenever you need the constant's value in your program, you use its name as you would use a variable name. The actual value of the symbolic constant needs to be entered only once, when it is first defined.
  • 42.
    SYMBOLIC CONSTANTS C hastwo methods for defining a symbolic constant: the #define directive and the const keyword. • #define CONSTANTNAME literal • This creates a constant named CONSTNAME with the value of literal. literal represents a literal constant, as described earlier . CONSTANTNAME follows the same rules described earlier for variable names. By convention, the names of symbolic constants are uppercase. This makes them easy to distinguish from variable names, which by convention are lowercase. Example: • #define PI 3.14159 • Note that #define lines don't end with a semicolon (;). #defines can be placed anywhere in your source code, but they are in effect only for the portions of the source code that follow the #define directive. Most commonly, programmers group all #defines together, near the beginning of the file and before the start of main().
  • 43.
    CONST KEYWORD • Thesecond way to define a symbolic constant is with the const keyword. const is a modifier that can be applied to any variable declaration. A variable declared to be const can't be modified during program execution--only initialized at the time of declaration. Here are some examples: • const int count = 100; • const float pi = 3.14159; • const long debt = 12000000, float tax_rate = 0.21; • const affects all variables on the declaration line. In the last line, debt and tax_rate are symbolic constants. If your program tries to modify a const variable, the compiler generates an error message, as shown here: • const int count = 100; • count = 200; /* Does not compile! Cannot reassign or alter */ • /* the value of a constant. */ • The practical differences between symbolic constants created with the #define directive and those created with the const keyword have to do with pointers and variable scope.
  • 44.
    THE TYPEDEF KEYWORD •The typedef keyword is used to create a new name for an existing data type. In effect, typedef creates a synonym. E.g, the statement • typedef int integer; • creates integer as a synonym for int. You then can use integer to define variables of type int, as in this example: • integer count; • Note that typedef doesn't create a new data type; it only lets you use a different name for a predefined data type.
  • 45.
    TYPE CASTING • Typecasting is a way to convert a variable from one data type to another. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator as follows: • (type_name) expression •Consider the following example where the cast operator causes the division of one integer variableby another to be performed as a floating-point operation:
  • 46.
    PROGRAM #include <stdio.h> main() { int sum= 17, count = 5; double mean; mean = (double) sum / count; printf("Value of mean is %d n", mean ); }
  • 47.
    CONT… • When theabove code is compiled and executed, it produces the following result: • Value of mean : 3.400000 • It should be noted here that the cast operator has precedence over division, so the value of sum isfirst converted to type double and finally it gets divided by count yielding a double value. • •Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are necessary. •
  • 48.
    NOTE: • DO understandthe number of bytes that variable types take for your computer. • DO use typedef to make your programs more readable. • DO initialize variables when you declare them whenever possible. • DON'T use a variable that hasn't been initialized. Results can be unpredictable. • DON'T use a float or double variable if you're only storing integers. Although they will work, using them is inefficient. • DON'T try to put numbers into variable types that are too small to hold them. • DON'T put negative numbers into variables with an unsigned type.
  • 49.
  • 50.
    STATEMENTS • A statementis a complete directive instructing the computer to carry out a specific task. • InC++, statements are usuallywritten one per line, althoughsome statements span multiple lines. • C++ statements always end with a semicolon (except for preprocessor directives such as #define and #include). • Example: x = 2 + 3;
  • 51.
    EXPRESSIONS • An expressionis anything that evaluates to a numeric value. • C expressions come in all levels of complexity • Simple Expressions • The simplest C expression consists of a single item: a simple variable, literal constant, or symbolic constant. • Here are four expressions: PI 20 rate - 1.25 A symbolic constant (defined in the program) A literal constant A variable Another literal constant • A literal constant evaluates to its own value. • A symbolic constant evaluates to the value it was given when you created it (using the #define directive on const keyword) • A variable evaluates to the current value assigned to it by the program.
  • 52.
    COMPLEX EXPRESSIONS • Complexexpressions consist of simpler expressions connected by operators. • For example: 2 + 8 • is an expression consisting of the sub-expressions 2 and 8 and the addition operator +. • The expression 2 + 8 evaluates to 10. • You can also write C expressions of great complexity: 1.25 / 8 + 5 * rate + rate * rate / cost • When an expression contains multiple operators, the evaluationof the expression depends on operator precedence
  • 53.
    COMPOUND ASSIGNMENT OPERATORS •Compound assignment operators provide a shorthand method for combining a binary mathematical operation with an assignment operation. • For example, say you want to increase the value of x by 5, or , in other words, add 5 to x and assign the result to x.You could write x = x + 5; • Using a compound assignment operator, which you can think of as a shorthand method of assignment, you would write • x += 5; • In more general notation, the compound assignment operators have the following syntax (where op represents a binary operator): • exp1 op= exp2 ; • This is equivalent to writing • exp1 = exp1 op exp2;
  • 54.
    COMPOUND STATEMENT OPERATOR •As with all other assignment statements, a compound assignment statement is an expression and evaluates to the value assigned to the left side. • Thus, executing the following statements results in both x and z having the value 14: • x = 12; • z = x += 2;
  • 55.
  • 56.
    EVALUATE THE EXPRESSIONSBELOW 1. x = 4, y = 7, z = 9; 2. x = (y < 7); 3. z = x++; 4. y = (z==x) | | (x!=1); 5. x = --y; x = 0, y = 5, z = 6; 6. x = y +1; 7. y = z++; 8. z = ++x; 9. x = (y==1) | | (z==0); 10. z = (x!=y) && (x >1); 11. y = !(z < 2);
  • 57.
    FIND THE SOLUTIONS x= 0, y = 5, z = 6; x = 4, y = 7, z = 9; 1. x = y +1; 2. y = z++; 3. z = ++x; 4. x = (y==1) | | (z==0); 5. z = (x!=y) && (x >1); 6. y = !(z < 2); 1. x = (y < 7); 2. z = x++; 3. y = (z==x) | | (x!=1); 4. x = --y;
  • 58.
    OPERATOR DEFINITION •Operator isthe symbol which operates on a value or a variable (operand). For example: + is an operator to perform addition. • • C programming language has a wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as:
  • 59.
    OPERATORS IN CPROGRAMMING 1. Arithmetic Operators 2. Increment and Decrement Operators 3. Assignment Operators 4. Relational Operators 5. Logical Operators 6. Conditional Operators 7. Bitwise Operators 8. Special Operators
  • 60.
    ARITHMETIC OPERATORS Operator DescriptionExample + Adds two operands A + B will give 30 - Subtracts second operand from the first A - B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by de-numerator B / A will give 2 Assume variable A holds 10 and variable B holds 20 then % Modulus Operator - remainder of after an integer division B % A will give 0 Note: % operator can only be used with integers.
  • 61.
    INCREMENT AND DECREMENTOPERATORS – UNARY OPERATORS In C, ++and --are called increment and decrement operators respectively. Both of these operatorsare unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts 1 to operand respectively. For example: Let a=5 a++; //a becomes 6a--; //a becomes 5 ++a; //a becomes 6 --a; //a becomes 5 •
  • 62.
    DIFFERENCE BETWEEN ++AND -- OPERATOR AS POSTFIX AND PREFIX • When i++ is used as prefix(like: ++var), ++var will increment the value of var and then return it but, if ++ is used as postfix(like: var++), operator will return the value of operand first and then increment it. This can be demonstrated by an example: • #include <stdio.h>int main(){ • int c=2; • • printf("%dn",c++); /*this statement displays 2 then, only c incremented by 1 to 3.*/ printf("%d",++c); /*this statement increments 1 to c then, only c is displayed.*/ • return 0; • } • Output • 2 • 4
  • 63.
    ASSIGNMENT OPERATORS –BINARY OPERATORS • The most common assignment operator is =. This operator assigns the value in the right side to the left side. For example: • • var=5 //5 is assigned to var • a=c; //value of c is assigned to a5=c; // Error! 5 is a constant Operator Example Same as = a=b a=b += a+=b a=a+b -= a-=b a=a-b *= a*=b a=a*b /= a/=b a=a/b %= a%=b a=a%b NB/ += means Add and Assign etc.
  • 64.
    RELATIONAL OPERATORS -BINARY OPERATORS Relational operators check relationship between two operands. If the relation is true, it returns value1 and if the relation is false, it returns value 0. For example: a>b Here, >is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0. Relational operators are used in decision making and loops in C programming.
  • 65.
    CONT… Operator Meaning ofOperator Example = = Equal to 5= =3 returns false (0) > Greater than 5>3 returns true (1) < Less than 5<3 returns false (0) != Not equal to 5!=3 returns true(1) >= Greater than or equal to 5>=3 returns true (1) <= Less than or equal to 5<=3 return false (0)
  • 66.
    LOGICAL OPERATORS -BINARY OPERATORS • Logical operators are used to combine expressions containing relational operators. In C, there are 3 logical operators: Operator Meaning of Operator Example && Logical AND If c=5 and d=2 then,((c= =5) && (d>5)) returns false. | | Logical OR If c=5 and d=2 then, ((c= =5) | | (d>5)) returns true. ! Logical NOT If c=5 then, !(c= =5) returns false.
  • 67.
    LOGICAL AND • Thefollowing table shows the result of operator && evaluating the expression a&&b: && OPERATOR (and) a b a && b true true true false true false false true false false false false
  • 68.
    BOOLEAN LOGICAL OPERATIONOR • The operator | | corresponds to the Boolean logical operation OR, which yields true if either of its operands is true, thus being false only when both operands are false. Here are the possible resultsof a | | b: • Explanation • For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the given example. So, the expression is false. For expression ((c==5) | | (d>5)) to be true, either the expression should be true. • • Since, (c==5)is true. So, the expression is true. Since, expression (c==5)is true, !(c==5)is false. | | OPERATOR (or) a b a | | b true true true true false true false true true false false false
  • 69.
    CONDITIONAL OPERATOR –TERNARY OPERATORS Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example: c=(c>0)?10:-10; If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
  • 70.
    BITWISE OPERATORS Bitwise operatorswork on bits and performs bit-by-bit operation.
  • 71.
    PRECEDENCE OF OPERATORS •If more than one operator is involved in an expression then, C language has a predefined rule of priority of operators. This rule of priority of operators is called operator precedence. • Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
  • 72.
    Category Operator Associativity Postfix() [] -> . ++ - - Left to right Unary + - ! ~ ++ - - (type)* & sizeof Right to left * / % Multiplicative Left to right + - Additive Left to right < <= > >= Relational Left to right == != Equality Left to right & Bitwise AND Left to right ^ Bitwise XOR Left to right | Bitwise OR Left to right && Logical AND Left to right | | Logical OR Left to right ?: Conditional Right to left = += -= *= /= %=>>= <<= &= ^= |= Assignment Right to left Comma , Left to right
  • 73.
    ASSOCIATIVITY OF OPERATORS Associativityindicates in which order two operators of same precedence (priority) executes. Let us suppose an expression: a= =b!=c Here, operators == and != have the same precedence.The associativity of both == and != is left to right, i.e., the expression in left is executed first and execution take pale towards right.Thus, a==b!=c equivalent to : (a= =b)!=c Operators may be left-associative (meaning the operations are grouped from the left), right- associative (meaning the operations are grouped from the right)
  • 74.
    TABLE SHOWING ORDEROF PRECEDENCE Operator Name Associativity Operators Unary right to left ++ -- ! ~ Multiplicative left to right * / % Additive left to right + - Bitwise Shift left to right << >> Relational left to right < > <= >= Equality 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 | | Conditional right to left ? : Assignment right to left = += -= *= /= <<= >>= %= &= ^= |= Comma left to right ,
  • 75.