Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore BCA112_BCA117_Computer Programming

BCA112_BCA117_Computer Programming

Published by Teamlease Edtech Ltd (Amita Chitroda), 2020-10-23 09:57:28

Description: BCA112_BCA117_Computer Programming

Search

Read the Text Version

44 Computer Programming Symbolic Constants A symbolic constant is a name that substitutes for a sequence of characters. The characters may represent a numeric constant, a character constant or a string constant. Thus, a symbolic constant allows a name to appear in place of a numeric constant, a character constant or a string. When a program is compiled, each occurrence of a symbolic constant is replaced by its corresponding character sequence. Symbolic constants are usually defined at the beginning of a program. The symbolic constants may then appear later in the program in place of the numeric constants, character constants, etc. that the symbolic constants represent. A symbolic constant is defined by writing #define name text where name represents a symbolic name, typically written in uppercase letters, and text represents the sequence of characters that is associated with the symbolic name. Since a symbolic constant definition is not a true C statement, text does not end with a semicolon. Moreover, if text were to end with a semicolon, this semicolon would be treated as though it were a part of the numeric constant, character constant or string constant that is substituted for the symbolic name. Preprocessor is also called Macro Definition. # define max 100 Hence # is a preprocessor directive which directs to the compiler that identifier max as a token replaced with the string 100. Hence in the program each occurrence of max is automatically replaced by 100. Examples: # define true 1 # define false 0 # define EoF – 1 # define product (x, y) ((x) * (y)) CU IDOL SELF LEARNING MATERIAL (SLM)

Fundamentals of C 45 2.8 Format specifiers with scanf() and printf() The format string can contain format specifiers like scanf(). %dstands for integer numbers %c stands for character %f stands for float %s stands for string %o stands for octal %x stands for hexadecimal printf Function The printf function writes data to standard output (usually, the terminal). printf( ) function is available in stdio.h (standard input output header file) Syntax of print() function: printf(control_string,arg1,arg2,arg3,..., argn); where control_string refers to a character string containing formatting information, and arg1, arg2, etc., are arguments that represent the individual output data items. The purpose of printf() is to display messages and values on the standard output using format specifiers. The general format of printf() is (1) printf(<msg>); only for displaying the message. (2) printf(<format string>, arguments); only for displaying the value of argument or variable (3) printf(<format string><msg>,arguments)Displaying the message along with the value of argument or variable. Always the format string is defined within the ” ” ( double quotes) Example 1: printf(“Welcome to C programming”); Will display CU IDOL SELF LEARNING MATERIAL (SLM)

46 Computer Programming Welcome to C programming printf() does not automatically print a new line. The programmer has to explicitly do it, by including the \\n in the format string. scanf Function The scanf function reads data from standard input (usually, the terminal). scanf( ) function is available in stdio.h (standard input output header file) For inputting values to your program you can either use getchar() or scanf(). The getchar() returns a single character from a standard input device, the function does not require any argument and it is restricted in the sense that only one character can be read-in at a time and no float/string values can be read and the scanf() function allows more flexible input. Syntax of scanf() is: scanf(control_string, arg1, arg2, arg3, ..., argn); where control_string refers to a character string containing certain required formatting information, and arg1, arg2, etc., are arguments that represent the individual input data items. Example: scanf(”%d”, &n); where the variable n has been declared as an integer. The & is mandatory and stands for “address of”. scanf(”%d %d”, &a, &b); where a,b are integers. 2.9 Variables Variable is a place holder which occupies memory space to store variable value, or a constant value, integer, float, character, string value. In C, all variables must be declared before they are used in executable statements. In C language all variables are to be declared first in local declaration section, i.e., at the beginning of scope. CU IDOL SELF LEARNING MATERIAL (SLM)

Fundamentals of C 47 float per = 92.8; Here, per is a variable of integer type. The variable is holding 92.8 in the above code. The value of a variable can be changed, hence the name ‘variable’. The variable/Identifier name follows following rules: 1. The variable name should always start from any alphabet a – z. 2. The variable name is a combination of alphabets, numbers and underscores. 3. The variable name cannot start with a digit. 4. No special symbol other than underscore can be used in variable name. 5. Variables are case sensitive. 6. No special symbols are allowed other than underscore. 7. Reserved keywords that are not allowed as variable names because they are part of the language’s syntax. C is a strongly typed language. What this means it that, the type of a variable cannot be changed. Suppose, you declared an integer type variable. You cannot store character or a decimal number in that variable. Variable Definition Declaring and Initializing C Variable:  Variables should be declared in the C program before to use.  Memory space is not allocated for a variable while declaration. It happens only on variable definition.  Variable initialization means assigning a value to the variable. CU IDOL SELF LEARNING MATERIAL (SLM)

48 Computer Programming Fig. 2.5: Variable and Constants Sr. No. Type Table 2.2: Variable Syntax Example 1 Variable declaration Syntax Int x, y, z; char flat, ch; 2 Variable initialization Int x = 50, y = 30; Data_typevariable_name; char flag = ‘x’, ch = ‘1’; Data_typevariable_name = value; Scope of Variables in C Program are: 1. Local variable 2. Global variable 1. Local Variable in C:  The scope of local variables will be within the function only.  These variables are declared within the function and can’t be accessed outside the function. 2. Global Variable in C:  The scope of global variables will be throughout the program. These variables can be accessed from anywhere in the program.  This variable is defined outside the main function. So that, this variable is visible to main function and all other sub-functions. Storage classes  Every variable in C programming has two properties: type and storage class.  Type refers to the data type of a variable. And, storage class determines the scope and lifetime of a variable. CU IDOL SELF LEARNING MATERIAL (SLM)

Fundamentals of C 49  Every time a variable is defined, its type is mentioned. Along with it, its ‘storage class’ is also required. In other words, not only do all variables have a data type, they also have a ‘storage class’, i.e., Scope.  Most of the variables defined have only data type and a default storage class is used. If the storage class of a variable is not specified in its declaration, the compiler will assume a storage class depending on the context in which the variable is used.  In C programming language, a variable name identifies some physical location within the computer where the variable’s value is stored.  There are basically two kinds of locations in a computer — Memory and CPU registers. It is the variable’s storage class that determines in which of these two locations the value is stored. The storage class of a variable also signifies: (a) Where it will be stored. (b) What will be the initial value; default value (c) What is the scope; availability (d) What is the life, i.e., how long would the variable exist. There are 4 types of storage class: 1. Automatic storage class (Local) 2. External storage class (Global) 2. Static storage class 4. Register storage class 1. Automatic (Local Variable) The variables declared inside the function are automatic or local variables. The local variables exist only inside the function in which it is declared. When the function exits, the local variables are destroyed. This is the default storage class for all local variables. A variable defined with automatic storage class are stored in memory and often initialized with garbage (random) value. CU IDOL SELF LEARNING MATERIAL (SLM)

50 Computer Programming The scope and life of the variable is local to the block it’s defined. The moment the control comes out of the block in which the variable is defined, the variable and its value is forever lost. Syntax: int main() { int n; // n is a local varible to main() function ... .. ... } void func() { int n1; // n1 is local to func() fucntion } Example: void main() { int var1; //default storage class : auto auto int var2; //storage class explicitly mentioned printf(“\\n %d %d”, var1, var2); } In the above example, both the variables are defined with the same storage class. Storage class for var1 is not mentioned and so its initialized with default, i.e., auto. ‘auto’ can only be used within functions, i.e., local variables. Output of the above program is: 1258 1547 Their garbage values, as the variable were not initialized. So always make it a point that you initialize the automatic variables properly, otherwise you are likely to get unexpected results. CU IDOL SELF LEARNING MATERIAL (SLM)

Fundamentals of C 51 2. Extern (Global Variable) Variables that are declared outside of all functions are known as external variables. External or global variables are accessible to any function. A variable defined to have external storage class is stored in memory and initialized to a default value zero. Variables of this storage class are also called “Global variables”. External variables are declared outside all functions, yet are available to all functions that care to use them. Generally, External variables are declared again in the function using keyword extern. In the explicit declaration of variable ‘extern’ keyword is used. Example #1 : External Variable #include <stdio.h> void display(); int n = 5; // global variable int main() { ++n; // variable n is not declared in the main() function display(); return 0; } void display() { ++n; // variable n is not declared in the display() function printf(“n = %d”, n); } Output: n=7 Suppose, a global variable is declared in file1. If you try to use that variable in a different file file2, the compiler will complain. To solve this problem, keyword extern is  used  in file2 to indicate that the external variable is declared in another file. CU IDOL SELF LEARNING MATERIAL (SLM)

52 Computer Programming Example #2 : External Variable int x = 30; // variable definition void showx(void); void main() { extern int x; //explicit declaration printf(“\\n %d”, x++); showx(); } void showx() { extern int x; //explicit declaration printf(“\\n %d”, x); } Output of the program is: 30 31 As seen in the output, the variable x, defined as global, has its value accessible in main() and showx() methods. The value of x is incremented in the main method and its value retains even outside the scope of main method when the showx() method is called and the incremented value is printed. 3. Static Variable A static variable is declared by using keyword static. A variable defined to have static storage class is stored in memory and initialized to a default value zero. The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. The static modifier CU IDOL SELF LEARNING MATERIAL (SLM)

Fundamentals of C 53 may also be applied to global variables. When this is done, it causes that variable’s scope to be restricted to the file in which it is declared. Syntax: static int i; The value of a static variable persists until the end of the program. Example #1: Static Variable #include <stdio.h> void display(); int main() { display(); display(); } void display() { static int c = 0; printf(“%d “,c); c += 5; } Output: 0 5 During the first function call, the value of c is equal to 0. Then, its value is increased by 5. During the second function call, variable c is not initialized to 0 again. It’s because c is a static variable. So, 5 is displayed on the screen. CU IDOL SELF LEARNING MATERIAL (SLM)

54 Computer Programming Example #2: Static Variable //function prototype void call_me(void); void main() { Call_me(); Call_me(); Call_me(); Call_me(); } void call_me() { static int i=5; printf(“\\n %d”, i++); } Output of the above program is: 5 6 7 8 Here the static variable i is initialized with 5 only once. It is never initialized again. During the first call to Call_me( ), i is incremented to 6. Because i is static, this value persists. The next time Call_me( ) is called, i is not re-initialized to 1; on the contrary its old value 6 is still available. This current value of i (i.e., 6) gets printed and then i++ increments i to get a value of 7. When Call_me( ) is called the third time, the current value of i (i.e., 7) gets printed and once again i is incremented. In short, if the storage class is static then the statement static int i = 5 is executed only once, irrespective of how many times the same function is called. CU IDOL SELF LEARNING MATERIAL (SLM)

Fundamentals of C 55 4. Register Variable The register keyword is used to declare register variables. Register variables were supposed to be faster than local variables. Local variable defined using register storage class is stored in CPU registers instead of memory. They are by default initialized to garbage value. This means that the variable has a maximum size equal to the register size (usually one word) and can’t have the unary ‘&’ operator applied to it (as it does not have a memory location). The scope and life of the variable is same as auto variables, i.e., is local to the block it’s defined. Why would a variable be defined with this storage class? The answer is to have quick access. For example, the counter variables may be defined with register storage class. It should also be noted that defining ‘register’ does not mean that the variable will be stored in a register. It means that it might be stored in a register depending on hardware and implementation restrictions like number of free registers. void main() { register int i; for(i=0;i<3;i++) printf(“\\n %d”, i); } Not every type of variable can be stored in a CPU register. For example, if the microprocessor has 16-bit register then they cannot hold float and double variables which require 4 or 8 bytes respectively. In this case the compiler would treat the variable as auto storage class. However, modern compilers are very good at code optimization and there is a rare chance that using register variables will make your program faster. Unless you are working on embedded system where you know how to optimize code for the given application, there is no use of register variables. CU IDOL SELF LEARNING MATERIAL (SLM)

56 Computer Programming Table 2.3: CPU Register Category Automatic Register Static External Storage Memory CPU Register Memory Memory Initial Value Garbage Garbage Zero Zero Life Within Block Within Block Outside Block but active Outside Block and also only in the file declared active in multiple files Scope Local Local Local Global 2.10 Summary C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. C is the most widely used computer language. It keeps fluctuating at number one scale of popularity along with Java programming language, which is also equally popular and most widely used among modern software programmers. Key advantages of learning C Programming:  Easy to learn  Structured language  It produces efficient programs  It can handle low-level activities  It can be compiled on a variety of computer platforms Features of C Language: 1. Simple 2. Machine Independent or Portable 3. Mid-level programming language 4. Structured programming language 5. Rich Library 6. Memory Management 7. Fast Speed CU IDOL SELF LEARNING MATERIAL (SLM)

Fundamentals of C 57 8. Pointers 9. Recursion 10. Extensible Every C program follows the structure of Program Documentation Section/Comment section Definition section Link Section/Include Section Global Declaration void main( ) function section { Local declaration part Executable part } Datatypes in C Data types specify how we enter data into our programs and what type of data we enter. C language has some predefined set of data types to handle various kinds of data that we can use in our program. These datatypes have different storage capacities. C language supports 2 different type of data types: 1. Primary data types: These are fundamental data types in C namely integer(int), floating point(float), character(char) and void. 2. Derived data types: Derived data types are nothing but primary datatypes but a little twisted or grouped together like array, stucture, union and pointer. Data type determines the type of data a variable will hold. If a variable x is declared as int. it means x can hold only integer values. Every variable which is used in the program must be declared as what data-type it is. CU IDOL SELF LEARNING MATERIAL (SLM)

58 Computer Programming 2.11 Key Words/Abbreviations Execution Flow 1. C program (source code) is sent to preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates an expanded source code. 2. Expanded source code is sent to compiler which compiles the code and converts it into assembly code. 3. The assembly code is sent to assembler which assembles the code and converts it into object code. Now a simple.obj file is generated. 4. The object code is sent to linker which links it to the library such as header files. Then it is converted into executable code. A simple.exe file is generated. 5. The executable code is sent to loader which loads it into memory and then it is executed. After execution, output is sent to console. 2.12 Learning Activity 1. What are the rules for writing any program. ....................................................................................... ....................................................................................... 2. Write a program in C to print “HELLO WORLD”. ...................................................................................... ....................................................................................... 2.13 Unit End Questions (MCQ and Descriptive) A. Descriptive Type: Short Answer Type Questions 1. Explain structure of C program in detail with neat diagram. 2. What are the major components of a C program? What significance is attached to the name main( ) function? CU IDOL SELF LEARNING MATERIAL (SLM)

Fundamentals of C 59 3. Explain header section of C program. 4. Explain body section of C program. 5. Explain use of #define section. 6. Explain use of #include section and state which header files can be included. 7. Explain category of different Header Files. 8. Name and describe the four basic data types in C. 9. Write a short note on Use of Comments in C program and state what are different ways to write comments. 10. Explain data types and constants. 11. Explain constants and types of constants. 12. What is a variable? How can variables be characterized? 13. What is a symbolic constant? How is a symbolic constant defined? 14. Differentiate constants and variables. B. Multiple Choice/Objective Type Questions 1.  All keywords in C are in ____________. (a) LowerCase letters (b) UpperCase letters (c) CamelCase letters (d) None of the mentioned 2. Which of the following is not a valid variable name declaration? (a) float PI = 3.14; (b) double PI = 3.14; (c) int PI = 3.14; (d) #define PI 3.14 3. Which is the only function all C programs must contain? (a) start() (b) main() (c) getch() (d) printf() 4. What number should be the shown on the screenafter the following statements of C are executed? char ch; int i; CU IDOL SELF LEARNING MATERIAL (SLM)

60 Computer Programming ch=’G’; (b) 7n i=ch=’A’; (d) 6 printf(“%d”,i); (a) 5 (c) 8 Answers : 1. (a), 2. (d), 3. (b), 4. (d) 2.14 References 1. https://www.studytonight.com/c/datatype-in-c.php 2. https://www.programiz.com/c-programming 3. https://www.tutorialspoint.com/cprogramming/c_data_types.htm 4. http://www-personal.acfr.usyd.edu.au/tbailey/ctext/ctext.pdf 5. http://www.vssut.ac.in/lecture_notes/lecture1424354156.pdf  CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 61 UNIT 3 OPERATORS AND EXPRESSIONS Structure: 3.0 Learning Objectives 3.1 Introduction 3.2 Arithmetic Operators 3.3 Relational Operators 3.4 Logical Operators 3.5 Assignment and Compound Assignment Operators 3.6 Unary Operators and Increment and Decrement Operator 3.7 Conditional Operator or Ternary Operator 3.8 Bitwise and Comma Operator 3.9 Expressions and Evaluation of Expression 3.10 Type Conversion 3.11 Precedence and Associatively (Order of Evaluation) 3.12 I/O Functions: printf( ), scanf( ) 3.13 Summary 3.14 Key Words/Abbreviations 3.15 Learning Activity 3.16 Unit End Questions (MCQ and Descriptive) 3.17 References CU IDOL SELF LEARNING MATERIAL (SLM)

62 Computer Programming 3.0 Learning Objectives After studying this unit, you will be able to:  Describe different types of C operators  Solve expressions having different operators  Change the type of given data and variable  Explain operator precedence and associativity  Discuss I/O functions 3.1 Introduction An operator is a symbol that tells the compiler to perform specific mathematical or logical functions.Operators, functions, constants and variables are combined together to form expressions. Here you will learn about Operators in C Programming (all valid operator’s available in C), expressions (combination of operators, variables and constants) and precedence of operators (which operator has higher priority and which operator has lower priority). 3.2 Arithmetic Operators The operators used to perform arithmetic operations such as addition (+), subtraction (–), multiplication (*), division (/) are called arithmetic operators. These basic operators are known as binary operators as they require two variables to be evaluated. Table 3.1: Arithmetic Operators Sr. No. Operator Meaning (1) + Addition or unary plus (2) – Subtraction or unary minus (3) * Multiplication (4) / Division (5) % Modulo division (Reminder of an Integer division) The variables or constants on which operators are operated are known as operands. The arithmetic in C can be of three types: CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 63 (a) Integer Arithmetic. (b) Real Arithmetic. (c) Mixed Mode Arithmetic. (a) Integer Arithmetic: When both the operands are integers, the operation is called integer arithmetic. For example: 55 – 5 = 50 55 + 5 = 60 14 * 2 = 28 14/2 = 7 (Decimal part truncated integer division) 14% 2 = 0 (Remainder of division) – 14 % 3 = – 2 14 % 3 = 2 6/7 = 0 (b) Real Arithmetic: An arithmetic operation involving only real operands is called real arithmetic. A real operand may assume values either in fractional or exponential form. For e.g., 1.5 – 0.7 = 0.8 1.5 + 0.7 = 2.2 1.5 * 2.0 = 3.0 6.0/7.0 = 0.857143 1.0/3.0 = 0.3333 – 2.0/3.0 = – 0.666667 % (modulo operator) cannot be used with Real numbers x_int/y_int = result_int x_int/y_float = result_float CU IDOL SELF LEARNING MATERIAL (SLM)

64 Computer Programming x_float/y_int = result_float x_float/y_float = result_float (c) Mixed Mode Arithmetic: C++ permits us to mix integer operand with real operand. When one operand is real and the other is integer, the expression is called mixed mode arithmetic expression, i.e., if either of the operand is of the real type, then only real operation is performed and result is always a real number. For e.g., 15/10.0 = 1.5 4 + 3.5 = 7.5 Example of Arithmetic Operators // C Program to demonstrate the working of arithmetic operators #include <stdio.h> void main() { int a = 9,b = 4, c; c = a+b; printf(“a+b = %d \\n”,c); c = a-b; printf(“a-b = %d \\n”,c); c = a*b; printf(“a*b = %d \\n”,c); c=a/b; printf(“a/b = %d \\n”,c); c=a%b; printf(“Remainder when a divided by b = %d \\n”,c ); getch(); } CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 65 Output: a+b = 13 a-b = 5 a*b = 36 a/b = 2 Remainder when a divided by b=1 The operators +, - and * computes addition, subtraction and multiplication respectively as expected. In normal calculation, 9/4 = 2.25. However, the output is 2 in the program. It is because both variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after decimal point and shows answer 2 instead of 2.25. The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the remainder is 1. The % operator can only be used with integers. Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming, a/b = 2.5 // Because both operands are floating-point variables a/d = 2.5 // Because one operand is floating-point variable c/b = 2.5 // Because one operand is floating-point variable c/d = 2 // Because both operands are integers 3.3 Relational Operators Relational Operators: With the help of relational operators we can take a decision by comparing two or more operands values. Relational operators compare values to see if they are equal or if one of them is greater than the other and so on. Operator Meaning < is less than <= is less than equal to > is greater than >= is greater than equal to CU IDOL SELF LEARNING MATERIAL (SLM)

66 Computer Programming expression1 relational_operator expression2 Expression Result 3>4 false 6<=2 false 10 > – 32 True (23 * 7) > = (–67 + 89) True The relational operators are self-explanatory. As far as the explanation of the logical operators is concerned. Consider the following. Any operator which uses two characters as a symbol should have no space between the two characters, that is ==, It will erroneous if it is written as = =. 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. Operator Meaning of Operator Example == Equal to 5 == 3 returns 0 > Greater than 5 > 3 returns 1 < Less than 5 < 3 returns 0 != Not equal to 5 != 3 returns 1 >= Greater than or equal to 5 >= 3 returns 1 <= Less than or equal to 5 <= 3 return 0 3.4 Logical Operators Logical Operators: The logical operators are those which are used to perform logical expression such as logical AND, logical OR and logical NOT. The logical AND and logical OR operators are used when we want to test for more than one condition and make decision. C Logical Operators with Example Operator Meaning of Operator Example && Logial AND. True only if all operands If c = 5 and d = 2 then, expression ((c == 5) are true && (d > 5)) equals to 0. || Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c == 5) operand is true || (d > 5)) equals to 1. ! Logical NOT. True only if the operand is 0 If c = 5 then, expression ! (c == 5) equals to 0. CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 67 The && (AND) operator 1. Evaluates true when both the relational expressions are true. 2. Evaluates false when any one of the relational expressions is false. The following truth table will be useful to understand more clearly Logical AND indicates that compound expression is true when two conditions or expressions are true. Situation Result true && true true true && false false false && true false false && false false The || (OR) operator Logical OR indicates the Results is true if any or all inputs are true. 1. Evaluates true when any one the relational expression is true 2. Evaluates false when both the relational expressions is false. expression1 || expression2 Situation Result true || true true true || false true false || true true false || false false (a < b) || (b > c) true || false true Logical Negation Operator (!): A logical expression can be changed from false to true or from true to false with negation operator (!) CU IDOL SELF LEARNING MATERIAL (SLM)

68 Computer Programming Situation Result ! (true) false ! (false) true 3.5 Assignment and Compound Assignment Operators Assignment Operator Assignment operators are used to assign the result of an expression or constant to variable. The assignment operators can be used within any valid expression, the usual assignment operator is ‘=’. variable_Name = constant or expression; The arithmetic expression is a combination of variables, constants and operators E.g., x = a + b; z = 0; final = 100; During the assignment operator the value of expression of right hand side is assigned to left side variable. During the assignment operator the value of the expression on right hand side is computed and is assigned to the variable on the left hand side. Compound Assignment OR Short Hand Assignment Operators: The compound assignment operators enable you to abbreviate assignment statements. For example, the statement value = value + 3 which mentions the variable value on both sides of the assignment, can be abbreviated with the addition assignment operator, += as value += 3 The += operator adds the value of the right operand to the value of the left operand and stores the result in the left operand’s variable. CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 69 In addition to the usual assignment operator ‘=’. C++ has short hand assignment operators of the form. variable op = expression; where op is C language is binary arithmetic operator Compound assignment operator Sample expression Explanation Assigns Assume: c = 4, d = “He” += c += 7 c=c+7 11 to c -= c -= 3 c=c-3 1 to c *= c *= 4 c=c*4 16 to c /= c /= 2 c=c/2 2 to c \\= c \\= 3 c=c\\3 1 to c ^= c ^= 2 c=c^2 16 to c &= d &= “llo” d = “kiran” & “llo” “Hello” to kiran Fig. 3.1: Compound Assignment Operators. 3.6 Unary Operators and Increment and Decrement Operator (a) Unary Operators: The unary operators require only a single expression to produce a line. Some unary operators may be followed by the operands such as incremental and detrimental. The most common unary operation is unary minus, where a minus sign precedes a numerical constant, a variable or an expression. Unary Arithmetic Operators The unary operators are unary minus(-), increment operator (++) and decrement operator (—). Unary Minus(-) The symbol is the same as used for binary subtraction. Unary minus is used to indicate or change the algebraic sign of a value. For example: a=-75; b=-a; CU IDOL SELF LEARNING MATERIAL (SLM)

70 Computer Programming assign the value –75 to a and the value 75(-(-75)) to b. The minus sign used in this way is called the unary operator because it takes just one operand. Strictly speaking, there is no unary + in C. Increment and Decrement Operators Increment Operators are used to increased the value of the variable by one and Decrement Operators are used to decrease the value of the variable by one in C programs. Both increment and decrement operator are used on a single operand or variable, so it is called as a unary operator. Unary operators are having higher priority than the other operators it means unary operators are executed before other operators. Syntax ++ // increment operator — // decrement operator Increment and decrement operators cannot apply on constant. x= 4++; // gives error, because 4 is constant C includes two useful operators, which are generally not found in other computer languages. These are the increment operator (+ +) and the decrement operator (—). The operator ++ adds 1 to its operand, whereas the operator – subtracts 1 from its operand. To be precise, x = x + 1; can be written as x++; and x = x –1; can be written as x—; Both these operators may either precede or follow the operand, i.e., x = x + 1; can be represented as 1] ++x; or x++; The first case is known as prefix while the later one is known as postfix operator. Similar operations hold true for – operator. Ie. 1] - –x or x - - The difference between pre and post-fixing the operator is useful when it is used in an expression. When the operator precedes the operand, C performs the increment or decrement CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 71 operation before using the value of the operand. If the operator follows the operand, the value of the operand is used before incrementing or decrementing it. Example: x = 1; i = i +(+ + x); In the above expression, the value of x, which is added to i is 2 On the other hand, x = 1; i = i +(x + +); x =1 is added to i; in both the cases the value of x after evaluating the expression is 2. Type of Increment Operator  pre-increment  post-increment pre-increment (++ variable) In pre-increment first increment the value of variable and then used inside the expression (initialize into another variable). Syntax ++ variable; Example pre-increment #include<stdio.h> #include<conio.h> void main() { int x,i; i=10; x=++i; CU IDOL SELF LEARNING MATERIAL (SLM)

72 Computer Programming printf(“x: %d”,x); printf(“i: %d”,i); getch(); } Output: x: 11 i: 11 In above program first increase the value of i and then used value of i into expression. post-increment (variable ++) In post-increment first value of variable is used in the expression (initialize into another variable) and then increment the value of variable. post-increment (variable ++) In post-increment first value of variable is used in the expression (initialize into another variable) and then increment the value of variable. Syntax variable ++; Example post-increment #include<stdio.h> #include<conio.h> void main() { int x,i; i=10; x=i++; printf(“x: %d”,x); printf(“i: %d”,i); CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 73 getch(); } Output: x: 10 i: 11 In above program first used the value of i into expression then increase value of i by 1. Type of Decrement Operator  pre-decrement  post-decrement Pre-decrement (— variable) In pre-decrement first decrement the value of variable and then used inside the expression (initialize into another variable). Syntax — variable; Example pre-decrement #include<stdio.h> #include<conio.h> void main() { int x,i; i=10; x=—i; printf(“x: %d”,x); printf(“i: %d”,i); getch(); } CU IDOL SELF LEARNING MATERIAL (SLM)

74 Computer Programming Output: x: 9 i: 9 In above program first decrease the value of i and then value of i used in expression. post-decrement (variable —) In Post-decrement first value of variable is used in the expression (initialize into another variable) and then decrement the value of variable. Syntax variable —; Example post-decrement #include<stdio.h> #include<conio.h> void main() { int x,i; i=10; x=i—; printf(“x: %d”,x); printf(“i: %d”,i); getch(); } Output: x: 10 i: 9 In above program first used the value of x in expression then decrease value of i by 1. CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 75 Difference Between Pre/Post Increment and Decrement Operators in C: Below table will explain the difference between pre/post increment and decrement operators in C programming language. Operator Operator/Description Pre increment operator (++i) value of i is incremented before assigning it to the variable i Post increment operator (i++) value of i is incremented after assigning it to the variable i Pre decrement operator (–i) value of i is decremented before assigning it to the variable i Post decrement operator (i–) value of i is decremented after assigning it to variable i 3.7 Conditional Operator or Ternary Operator Conditional operator (?:): C includes a very special operator called the ternary or conditional operator. It is called ternary operator because it uses three expressions. It is short hand version of if_else construct. A conditional operator is a ternary operator, that is, it works on 3 operands. The format of the ternary operator is conditionalexpression1?expression2:expression3 If expression1 evaluated is true then expression2 is evaluated otherwise expression3 is evaluated. The conditional operator works as follows:  The first expression conditionalExpression is evaluated at first. This expression evaluates to 1 if it’s and evaluates to 0 if it’s false.  If conditionalExpression is true, expression1 is evaluated.  If conditionalExpression is false, expression2 is evaluated. Example: (1) if (i % 2 = = 0) even = true else even = false even = (i % 2 = = 0)? true : false; CU IDOL SELF LEARNING MATERIAL (SLM)

76 Computer Programming (2) if (i > j) max = i else man = j max = (i > j)? i : j; (3) if (x > y) x=x+3 else x=x–3 x = (x > y)? x + 3 : x – 3; Example: C conditional Operator #include <stdio.h> void main() { char February; int days; printf(“If this year is leap year, enter 1. If not enter any integer: “); scanf(“%c”,&February); // If test condition (February == ‘l’) is true, days equal to 29. // If test condition (February ==’l’) is false, days equal to 28. days = (February == ‘1’) ? 29 : 28; printf(“Number of days in February = %d”,days); getch(); } CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 77 Output: If this year is leap year, enter 1. If not enter any integer: 1 Number of days in February = 29 3.8 Bitwise and Comma Operator Bitwise Operators During computation, mathematical operations like: addition, subtraction, addition and division are converted to bit-level which makes processing faster and saves power. Bitwise operators are used in C programming to perform bit-level operations. Operators Meaning of operators & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR ~ Bitwise complement << Shift left >> Shift right (a) Bitwise AND: The bitwise AND operation will be carried out between the two bit patterns of the two operands. Variable Value Binary pattern x 5 0101 y 2 0010 x&y 0 0000 a 6 0110 b 3 0011 a&b 2 0010 To generate a 1 bit in the result, bitwise AND need a one in both numbers. Bitwise AND operator & The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0. CU IDOL SELF LEARNING MATERIAL (SLM)

78 Computer Programming Let us suppose the bitwise AND operation of two integers 12 and 25. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bit Operation of 12 and 25 00001100 & 00011001 ————— 00001000 = 8 (In decimal) Example #1: Bitwise AND #include <stdio.h> void main() { int a = 12, b = 25; printf(“Output = %d”, a&b); getch(); } Output: Output = 8 (b) Bitwise OR: The bitwise OR operations result 1 if any one of the bit value is 1. Variable Bitwise OR Binary pattern x Value 0101 y 0010 x|y 5 0111 a 2 0110 b 7 0001 a|b 6 0111 1 7 CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 79 Bitwise OR operator | The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C Programming, bitwise OR operator is denoted by |. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise OR Operation of 12 and 25 00001100 | 00011001 ________ 00011101 = 29 (In decimal) Example #2: Bitwise OR #include <stdio.h> void main() { int a = 12, b = 25; printf(“Output = %d”, a|b); getch( ); } Output: Output = 29 (c) Bitwise Exclusive OR: The bitwise exclusive OR will be carried out by the notation ^. To generate a 1 bit in the result, a bitwise exclusive OR needs a one in either number but not both. Bitwise EX – OR Variable Value Binary pattern x 5 0101 y 2 0011 x^y 25 11001 a 6 0110 b 3 0011 a^b 216 11011000 CU IDOL SELF LEARNING MATERIAL (SLM)

80 Computer Programming Bitwise XOR (exclusive OR) operator ^ The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^. 12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise Xor Operation Of 12 And 25 00001100 | 00011001 ________ 00010101 = 21 (In decimal) Example #3: Bitwise XOR #include <stdio.h> void main() { int a = 12, b = 25; printf(“Output = %d”, a^b); getch( ); } Output: Output = 21 (d) Bitwise complement: The complement operator ~ switches all the bits in a binary pattern, that is all the zeroes become ones and all ones become zeroes. It acts as a 1’s complement. Variable Value Binary pattern x 23 0001 0111 ~x 132 1110 1000 y Ff 1111 1111 ~y 00 0000 0000 CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 81 Bitwise complement operator ~ Bitwise complement operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. It is denoted by ~. 35 = 00100011 (In Binary) Bitwise complement Operation of 35 ~ 00100011 ________ 11011100 = 220 (In decimal) Twist in bitwise complement operator in C Programming The bitwise complement of 35 (~35) is -36 instead of 220, but why? Example #4: Bitwise complement #include <stdio.h> void main() { printf(“complement = %d\\n”,~35); printf(“complement = %d\\n”,~-12); getch( ); } Output: Complement = -36 Output = 11 (e) Shift Operators in C programming There are two shift operators in C programming:  Right shift operator  Left shift operator. Bitwise Right shift: The right shift >> operator is used for right shifting. For y = 41 binary pattern is 0010 1001. CU IDOL SELF LEARNING MATERIAL (SLM)

82 Computer Programming y >> 3 will result 0010 1001 00010100 *****shift 00001010 *****shift 00000101 *****shift y >> is 0000 0101 Right Shift Operator other Example:- Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>. 212 = 11010100 (In binary) 212>>2 = 00110101 (In binary) [Right shift by two bits] 212>>7 = 00000001 (In binary) 212>>8 = 00000000 212>>0 = 11010100 (No Shift) Bitwise Left Shift: The << operator is used for left shifting. For y = 41 binary pattern is 0010 1001. Variable Value Binary pattern x 33 0010 0001 x << 3 0010 0001 shift *** 01000010 shift *** 10000100 shift *** 00001000 x << 3 is 00001000 Left Shift Operator: Left shift operator shifts all bits towards left by certain number of specified bits. It is denoted by <<. CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 83 212 = 11010100 (In binary) 212<<1 = 110101000 (In binary) [Left shift by one bit] 212<<0 =11010100 (Shift by 0) 212<<4 = 110101000000 (In binary) =3392(In decimal) Example #5: Shift Operators #include <stdio.h> void main() { int num=212, i; for (i=0; i<=2; ++i) printf(“Right shift by %d: %d\\n”, i, num>>i); printf(“\\n”); for (i=0; i<=2; ++i) printf(“Left shift by %d: %d\\n”, i, num<<i); getch( ); } Right Shift by 0: 212 Right Shift by 1: 106 Right Shift by 2: 53 Left Shift by 0: 212 Left Shift by 1: 424 Left Shift by 2: 848 (f) Comma Operator: Comma operators are used to link related expressions together. For example: int a, c = 5, d; CU IDOL SELF LEARNING MATERIAL (SLM)

84 Computer Programming comma (,) works as a separator and an operator too and its behaviour is little different according to the place where it is used. (1) Comma (,) as separator While declaration multiple variables and providing multiple arguments in a function, comma works as a separator. Example: int a,b,c; In this statement, comma is a separator and tells to the compiler that these (a, b, and c) are three different variables. (2) Comma (,) as an operator Sometimes we assign multiple values to a variable using comma, in that case comma is known as operator. Example: a = 10,20,30; b = (10,20,30); In the first statement, value of a will  be  10,  because assignment operator (=) has more priority more than comma (,), thus 10 will be assigned to the variable a. In the second statement, value of b will be 30, because 10, 20, 30 are enclosed in braces, and braces has more priority than assignment (=) operator. When multiple values are given with comma operator within the braces, then right most value is considered as result of the expression. Thus, 30 will be assigned to the variable b. Consider the program: #include <stdio.h> int main() { int a,b; a = 10,20,30; b = (10,20,30); CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 85 //printing the values printf(“a= %d, b= %d\\n”,a,b); return 0; } Output a=10, b=30 3.9 Expressions and Evaluation of Expression A statement causes the computer to carry out some action. There are three different classes of statements in C. They are expression statements, compound statements and control statements. An expression statement consists of an expression followed by a semicolon. The execution of an expression statement causes the expression to be evaluated. a = 23; //Assignment statement Sum=a+b; //calculative assignment statement ++i; // Incremental statement The first two expression statements are assignment-type statements. Each causes the value of the expression on the right of the equal sign to be assigned to the variable on the left. The third expression statement is an incrementing-type statement, which causes the value of i to increase by 1. A compound statement consists of several individual statements enclosed within a pair of braces { }. Decision statement is also called as compound statement. The individual statements may themselves be expression statements, compound statements or control statements. Thus, it is the compound statement provides a capability for embedding statements within other statements. A typical compound statement is shown below: If(c==0) { total = 600; CU IDOL SELF LEARNING MATERIAL (SLM)

86 Computer Programming Percentage=(marks/total)*100; } Control statements are used to create special program features, such as logical tests, loops and branches. Many control statements require that other statements be embedded within them. for(i=1;i<=10;i++) { printf(“%d”,i); } 3.10 Type Conversion When variables and constants of different types are combined in an expression then they are converted to same data type. The process of converting one predefined type into another is called type conversion or type casting. Type conversion in C can be classified into the following two types: Implicit Type Conversion When the type conversion is performed automatically by the compiler without programmers intervention, such type of conversion is known as implicit type conversion or type promotion. The compiler converts all operands into the data type of the largest operand. The sequence of rules that are applied while evaluating expressions are given below: All short and char are automatically converted to int, then, 1. If either of the operand is of type long double, then others will be converted to long double and result will be long double. 2. Else, if either of the operand is double, then others are converted to double. 3. Else, if either of the operand is float, then others are converted to float. 4. Else, if either of the operand is unsigned long int, then others will be converted to unsigned long int. CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 87 5. Else, if one of the operand is long int, and the other is unsigned int, then (1) if a long int can represent all values of an unsigned int, the unsigned int is converted to long int. (2) otherwise, both operands are converted to unsigned long int. 6. Else, if either operand is long int then others will be converted to long int. 7. Else, if either operand is unsigned int then others will be converted to unsigned int. It should be noted that the final result of expression is converted to type of variable on left side of assignment operator before assigning value to it. Also, conversion of float to int causes truncation of fractional part, conversion of double to float causes rounding of digits and the conversion of long int to int causes dropping of excess higher order bits. Explicit Type Conversion The type conversion performed by the programmer by posing the data type of the expression of specific type is known as explicit type conversion. The explicit type conversion is also known as type casting. Type casting in C is done in the following form: (data_type)expression; where, data_type is any valid C data type, and expression may be constant, variable or expression. For example, 1 x=(int)a+b*d; The following rules have to be followed while converting the expression from one type to another to avoid the loss of information: 1. All integer types to be converted to float. 2. All float types to be converted to double. 3. All character types to be converted to integer. CU IDOL SELF LEARNING MATERIAL (SLM)

88 Computer Programming 3.11 Precedence and Associatively (Order of Evaluation) C Operator Precedence Table This page lists C operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied. Operator Description Associativity () Parentheses (function call) (see Note 1) left-to-right [] Brackets (array subscript) right-to-left . Member selection via object name -> Member selection via pointer ++ — Postfix increment/decrement (see Note 2) ++ — Prefix increment/decrement left-to-right +- Unary plus/minus left-to-right !~ Logical negation/bitwise complement Cast (convert value to temporary value of type) (type) Dereference * Address (of operand) & Determine size in bytes on this implementation Multiplication/Division/Modulus sizeof Addition/Subtraction */% +- << Bitwise shift left left-to-right >> Bitwise shift right left-to-right left-to-right < <= Relational less than/less than or equal to > >= Relational greater than/greater than or equal to == != Relational is equal to/is not equal to left-to-right & Bitwise AND left-to-right ^ Bitwise exclusive OR left-to-right | Bitwise inclusive OR left-to-right && Logical AND left-to-right | | Logical OR left-to-right CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 89 ? : Ternary conditional right-to-left = Assignment right-to-left += -= Addition/Subtraction assignment *= /= Multiplication/Division assignment %= &= Modulus/Bitwise AND assignment ^ = |= Bitwise exclusive/inclusive OR assignment <<= >>= Bitwise shift left/right assignment , Comma (separate expressions) left-to-right Note 1: Parentheses are also used to group sub-expressions to force a different precedence; such parenthetical expressions can be nested and are evaluated from inner to outer. Note 2: Postfix increment/decrement have high precedence, but the actual increment or decrement of the operand is delayed (to be accomplished sometime before the statement completes execution). So in the statement y = x * z++; the current value of z is used to evaluate the expression, (i.e., z++ evaluates to z) and z only incremented after all else is done. See postinc.cfor another example. Notes: Precedence and associativity are independent from order of evaluation. The C language standard doesn't specify operator precedence. It specifies the language grammar, and the precedence table is derived from it to simplify understanding. There is a part of the grammar that cannot be represented by a precedence table: assignment is never allowed to appear on the right hand side of a conditional operator, so e = a < d ? a++ : a = d is an expression that cannot be parsed, and, therefore, relative precedence of conditional and assignment operators cannot be described easily. However, many C compilers use non-standard expression grammar where ?: is designated higher precedence than =, which parses that expression as e = ( ((a < d) ? (a++) : a) = d ), which then fails to compile due to semantic constraints: ?: is never lvalue and = requires a modifiable lvalue on the left. This is the table presented on this page. Note that this is different in C++, where the conditional operator has the same precedence as assignment. CU IDOL SELF LEARNING MATERIAL (SLM)

90 Computer Programming Associativity specification is redundant for unary operators and is only shown for completeness: unary prefix operators always associate right-to-left (sizeof ++*p is sizeof(++(*p))) and unary postfix operators always associate left-to-right (a[1][2]++ is ((a[1])[2])++). Note that the associativity is meaningful for member access operators, even though they are grouped with unary postfix operators: a.b++ is parsed (a.b)++ and not a.(b++). 3.12 I/O Functions: printf( ), scanf( ) printf Function The printf function writes data to standard output (usually, the terminal). printf( ) function is available in stdio.h (standard input output header file) Syntax of print() function: printf(control_string, arg1, arg2, arg3, ..., argn); where control_string refers to a character string containing formatting information, and arg1, arg2, etc., are arguments that represent the individual output data items. The purpose of printf() is to display messages and values on the standard output using format specifiers. The general format of printf() is (1) printf(<msg>); only for displaying the message. (2) printf(<format string>, arguments); only for displaying the value of argument or variable (3) printf(<format string> <msg>, arguments) Displaying the message along with the value of argument or variable. Always the format string is defined within the \" \" ( double quotes) Example 1: printf(\"C is fun\"); Will display C is fun printf() does not automatically print a new line. The programmer has to explicitly do it, by including the \\n in the format string. CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 91 Example 2: printf(\"The rain in Spain\"); printf(\"stays mainly on the plains\"); Output: The rain in Spain stays mainly on the plains. If you change the above to: printf(\"The rain in Spain\"); printf(\"\\nstays mainly on the plains\"); Output: The rain in Spain Stays mainly on the plains The control string consists of individual groups of characters, with one character group for each output data item. In its simplest form, each character group consists of a percent sign (%), followed by a conversion character which controls the format of the corresponding data item. The most useful conversion characters are as follows: The format string can contain format specifiers like scanf(). %d stands for integer numbers %c stands for character %f stands for float %s stands for string %o stands for octal %x stands for hexadecimal Example 1: void main() { int n; CU IDOL SELF LEARNING MATERIAL (SLM)

92 Computer Programming n = 7; printf(\"There are %d days in a week. \\n\",n); } Output: There are 7 days in a week. Example 2: void main() { int num=0; printf(\"Enter number :\"); scanf(\"%d\\n\" &num); printf(\"The number is %d.\\n\",num); } Output: Enter number: 20 The number is 20. Example 3: void main() { int num=0; printf(\"Enter number :\"); scanf(\"%d\\n\" &num); printf(\"The number is %4d.\\n\",num); } CU IDOL SELF LEARNING MATERIAL (SLM)

Operators and Expressions 93 Output: Enter number: 12 The number is 12  Indicates a Blank Space Example 4: void main() { int a, b,c; a= 10; b=20; c = a*b; printf(\"The Product of Two numbers %d & %d is = %d \\n\", a,b,c); } Output: The Product of Two numbers 10 and 20 is = 200 scanf Function The scanf function reads data from standard input (usually, the terminal). scanf( ) function is available in stdio.h (standard input output header file) For inputting values to your program you can either use getchar() or scanf(). The getchar() returns a single character from a standard input device, the function does not require any argument and it is restricted in the sense that only one character can be read-in at a time and no float/string values can be read and the scanf() function allows more flexible input. Syntax of scanf() is: scanf(control_string, arg1, arg2, arg3, ..., argn); where control_string refers to a character string containing certain required formatting information, and arg1, arg2, etc., are arguments that represent the individual input data items. CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook