Computer Programming 1 Module 3 (PDF)

Document Details

SereneDalmatianJasper5709

Uploaded by SereneDalmatianJasper5709

Gordon College

Armilyn T. Martinez, MSIT

Tags

computer programming bitwise operators data types programming fundamentals

Summary

This document is about computer programming module 3, covering bitwise operators in C programming like AND, OR, XOR, and left/right shift operators. It also discusses type conversion and casts in the context of C programming.

Full Transcript

53 Bitwise Operator Use to manipulate data at the bit level also referred to as bit level programming. Use to speed up processing of numerical computations. It cannot be directly applied to primitive data types, mostly used with the integer data type because of compatibility. Bitwise logical...

53 Bitwise Operator Use to manipulate data at the bit level also referred to as bit level programming. Use to speed up processing of numerical computations. It cannot be directly applied to primitive data types, mostly used with the integer data type because of compatibility. Bitwise logical operators are bit-by-bit data, starts working with the least significant bit (LSB-rightmost bit), towards the most significant bit (MSB-leftmost bit). Table below summarizes meaning and results of computations using bitwise logical operators. Operator Meaning & Bitwise AND operator | Bitwise OR operator ^ Bitwise exclusive OR operator ~ Binary One's Complement Operator is a unary operator > Right shift operator Table 1. The Bitwise Operators and Meaning and Results x y x&y x|y x^y The bitwise AND (&) operation will result to 1 if both the 0 0 0 0 0 bits have the value 1; otherwise result is 0. 0 1 0 1 1 1 0 0 1 1 Example: Operand 1 = 0000 1101 1 1 1 1 0 Operand 2 = 0001 1001 Result of AND Operation = 0000 1001 The bitwise OR (|) operation will result to 1 if at least one of the operand has the value 1; otherwise the result is always 0. Example : Operand 1 = 0000 1101 Operand 2 = 0001 1001 Result of OR Operation = 0001 1101 The bitwise Exclusive OR (^) operation will result to 1 if only one of the expressions has the value 1; otherwise, the result is always 0. Example : Operand 1 = 0000 1101 Operand 2 = 0001 1001 Result of Exclusive OR Operation = 0001 0100 Bitwise Shift Operators These are used to move/shift the bit patterns either to the left or right side. Operand > x (Right Shift) The operand is an integer expression in which a shift will be performed and ‘x’ is the total number of bit positions to shift the integer expression. Left shift operation will shift the ‘x’ Module 3 54 [COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT Gordon College- College of Computer Studies number bits to the left side. The leftmost bits in the expression will be removed (popped out), and the x bits with the value o will be replaced (filled) on the right side. Right Shift operation will shift the ‘x’ number of bits to the right. The rightmost ‘x’ bits in the expression will be popped out, and the value 0 will be filled on the left side. The shift operators can be used together to extract a data from the integer expression. Example: x is an integer expression with data 111111. After a shift operation the result will be: x >2 = 001111 The Bitwise Complement Operator (1’s complement operator) always takes only one value or an operand, a unary operator, all the 1’s will become 0 and vice versa. It is denoted by the symbol tilde (~). ~ 0000 1111 = 1111 0000 Type Conversions and Casts When an operator has operands of different types, they are converted to a common type according to some rules. Binary expression such as a * b, this rule applies (assuming neither operand is unsigned): RULE: If either operand is long double, convert the other to long double. Otherwise, if either operand is double, convert the other to double. Otherwise, if either operand is float, convert the other to float. Otherwise, convert char and short to int, and, if either operand is long, convert the other to long. If the two operands consist of a signed and an unsigned version of the same type, then the signed operand will be promoted to unsigned, with strange results if the previously signed value is negative. An example of type promotion is shown in code below; short a = 5; int b = 10; float c = 23.1f; double d = c + a*b; Multiplication is performed first, so a is promoted to int and multiplied with b. The integer result of this expression is promoted to float and added to c. This result is then promoted to double and assigned to d. The promotion from char to int is implementation- dependent, since whether a plain char is signed or unsigned depends on the compiler. Some platforms will perform “sign extension” if the left-most bit is 1, while others will fill the high- order bits with zeros—so the value is always positive. Assignment to a “narrower” operand is possible, although information may be lost. Conversion to a narrower type should elicit a warning from good compilers. Conversion from a larger integer to a smaller one results in truncation of the higher-order bits, and conversion from floating-point to integer causes truncation of any fractional part. For example, int result = 0.5 + 3/5.0; The division 3/5.0 is promoted to type double so that the final summation equals 1.1. The result then is truncated to 1 in the assignment to result. A conversion from double to float is implementation dependent and might be either truncated or rounded. MODULE 3 55 Narrowing conversions should be avoided. For the cases where they are necessary, they should be made explicit by a cast. For example, int result = (int)(0.5 + 3/5.0); Casts can also be used to coerce a conversion, such as going against the promotion rules. For example, the expression; result = (float)5.0 + 3.f; will add the two terms as float’s rather than double’s. Array An array is a group of variables of a particular type that occupies a contiguous region of memory. Array elements are indexed from 0. An array of size N is indexed 0 to N-1. Declaring an Array To declare an array, specify the data type of the array elements, the variable name and the size of the array. Example: declare an integer array with 4 elements; int a; This allocates a contiguous block of memory for four (4) elements of type integer with values equal to 0. Array representation in memory: Assigning new values of the array; 1st element : a = 10; 2nd element : a = 20; 3rd element : a = 2; 4th element : a = 18; Representation of the array with new values in memory ; To print array values; printf ("%d %d %d %d\n", a, a, a, a); Alternative way to initialize an Array When you know the array elements like declaring an array with values 40, 50, 60, 100 you may initialize the array in this syntax; int a = { 40, 50, 60, 100}; This will create an array of size 4, and initialize a to 40, a to 50, a to 60 and a to 100. Traversing an Array Array indexes are integers that start at 0 to array size – 1. A loop can be used to visit all the elements in an array. The process of visiting all the elements of an array is called ‘ traversing an array”. Two-Dimensional (2D) Arrays The array examples above are one-dimensional (1D) arrays. Combining two (2) 1D arrays can form a 2D array. Module 3 56 [COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT Gordon College- College of Computer Studies To declare a 2D array, you must know: the data type, the variable name and the size of the ID arrays. Example : int a; This allocates a contiguous block of memory for two 1D arrays that can hold four integers each and all elements are initialized to zero. The representation of the array is shown below. Visualizing 2D arrays as a table is a common approach. The first index is the row number and the second index is the column number. To access the element at the first row, third column, use a; the second row, second column, use a. If you want to create the array in the table representation shown below, write it as follows: int arr = {20,10,40,60}; You may also group the elements of the initializer list by using braces. To initialize a 2D array with two rows and three columns; int arr = {{10,20,30},{40,50,60}}; You may also use loops, print and ask input using scanf() to create an array. Multi Dimensional Arrays An array of more than one dimension is a multidimensional array. A three dimensional (3D) array is a combination of multiple 2D arrays and can be initialized using this syntax; int a; This creates a 3D array with a combination of 3 2x2 2D arrays, allocation is contiguous and all the elements are initialized to zero. Below is the array representation. To access elements in the array you must use the three indices. Say, to access the first 2D array’s second row and second column, you may write; a; You may also use the initializer list to create an array with known elements. int arr = { { {10, 20}, {30, 40}},{ {1, 2},{4, 5} }, { {3, 5},{7, 11} }}; The first 2D array’s first row is initialized to 10, 20, and the second row is initialized to 30, 40. Similarly, the second 2D array’s first row is initialized with 1, 2; the second row is initialized to 4, 5, and so on. To iterate over a 3D array, you need to nest three for loops. The outer loop to change the outermost index. The loop inside it changes the middle index, and the innermost loop changes the last index. MODULE 3 57 Strings An array of characters with the ‘\0’ (NULL character) at its end index. It is a sequence of characters that are treated by the compiler as a single item. Like arrays, a string can be traversed through its indices. Declaring and Initializing Strings Strings are declared similar to an array of characters. data type String_Name[number_of_elements]; example: char sample; Strings can be initialized in several ways but make sure to remember the NULL character. You may declare strings by character array or by string literal. The null character must be added when character array is used. example: char myString = “example”; char myString = { ‘P’,’r’,’o’,’g’,’r’,’a’,’m’,’m’,’i’,’n’,’g’,’\0’ }; char myString[] = “Programming”; char myString[] = { ‘P’,’r’,’o’,’g’,’r’,’a’,’m’,’m’,’i’,’n’,’g’,’\0’ }; Memory Presentation of a String Variable String Traversal To manipulate strings you need to traverse the texts, which is different from traversing an integer array. The null character is important to identify the end of the string and be able to terminate the loop structure. It is also important to know the length of the string. String Library Functions The standard C library has built functions for manipulating strings. These are inside the String.h header file. Make sure to include the String.h header file in your program. Here are some functions; Function Description strcat concatenate two strings strchr string scanning operation strcmp compare two strings strcpy copy a string strlen get string length strncat concatenate one string with part of another strncmp compare parts of two strings strncpy copy part of a string Table 2. Common String Functions Module 3 58 [COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT Gordon College- College of Computer Studies Functions A function is a self-contained modules of codes that accepts inputs, processes computations and produces a result. Functions in C must have a ‘type’, the return type and the type of all the specified parameters in the function definition. Why Use Functions? Functions let you avoid rewriting same logic or code design repeatedly. Functions can be invoked or called several times, anytime and anywhere in a program. Programs are more readable with functions; a large program can be tracked easily when it is divided into multiple functions. Code reusability is achieved with functions. Properties of Functions A function has three (3) essential properties; function declaration, function call and function definition. Function Declaration: It is a must to globally declare a function in a program. The compiler must know about the function name, function parameter, and the return type. Function Call: Functions can be invoked/called from anywhere and anytime in the program. When calling a function, the parameter list must not differ with the function declaration. Function Definition: This contains the block of statements to be executed or performed by the function once invoked. A function can only return one value. Property Syntax Function declaration return_type function_name (parameter list); Function call function_name (argument_list) Function definition return_type function_name (argument list) {function body;} Table 3. Function Property and Syntax Types of Functions There are two (2) types of functions in C: Library and User-defined functions. Library functions are declared in the C header files such as printf(), scanf(),gets() and the like. User- defined functions are created by the programmer and can be invoked several times. Thus, reducing complexity of large programs with codes optimization. Return Value of a Function A function may or may not return a value. A function that does not return a value has a void return type. Functions that return a value must be “typed”. Use any of the data types, int, long, char and the like. The return type depends on the value to be returned by the function. Since functions may or may not return a value, a function may or may not accept any argument when calling/invoking a function. Call By Value and Call By Reference These are the two (2) methods of passing data into the function. Table below presents the differences. MODULE 3 59 Call By Value Call By Reference A copy of the value is passed into the An address of value is passed into the function function Changes made inside the function is limited Changes made inside the function validate to the function only. The values of the actual outside of the function also. The values of parameters do not change by changing the the actual parameters do change by formal parameters. changing the formal parameters. Actual and formal arguments are created at Actual and formal arguments are created at the different memory location the same memory location Table 4. Differences of Call By Value and By Reference Methods Module 3 60 [COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT Gordon College- College of Computer Studies ACTIVITY 1 Name:_________________ Score/Rating:______________ Course:_______________ Date: ____________________ Perform the following tasks: 1. Write the syntax/program statement to create an array similar to the table. A. 1st Array 10 11 12 13 14 15 16 17 18 19 B. 2nd Array 1 2 3 4 5 6 7 8 9 10 11 12 2. Answer the questions below. A. What is the built-in library function for comparing the two strings? _________________________________________________________________________ B. What is passed when we pass an array as a function argument? _________________________________________________________________________ _________________________________________________________________________ C. What function finds the first occurrence of a substring in another string? _________________________________________________________________________ D. What is the keyword used to transfer control from a function back to the calling function? _________________________________________________________________________ E. Is there any difference in the below declarations? Explain your answer. int fun (int arr); int fun(int arr[]); _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ F. What is an array Base Address? Illustrate your answer. _________________________________________________________________________ MODULE 3 61 Bitwise Operators: Program Implementation The program example below uses two variables, 'a' and 'b' with values 6 and 14 respectively. The binary value of 'a' and 'b' are 0110 and 1110. When the AND operator was used between these two variables, the expression will be evaluated as; a AND b = 0110 && 1110 = 0110 #include int main() { int a=6, b=14; // variable declarations printf("The output of the bitwise AND operator a&b is %d.",a&b); return 0; } Program Output: The output of the bitwise AND operator a&b is 6. The code below implements the bitwise OR operation with the values of the variables ‘a’ and ‘b’, 23 and 10 respectively and the binary representation of the values as a = 0001 0111 , b = 0000 1010. Applying the bitwise OR ; a|b, the result would be 0001 1111. #include int main() { int a=23,b=10; printf("The output of the bitwise OR operator a|b is %d.",a|b); return 0; } Output: The output of the bitwise OR operator a|b is 31. Bitwise exclusive OR is denoted by the caret (^) symbol and the tilde (~) symbol for bitwise complement operator. Below is a program example that implements the two operators. #include int main() { int a=12,b=10, c=8; printf("The output of the bitwise exclusive OR operator a^b is %d.",a^b); printf("\n The output of the bitwise complement operator ~c is %d.",~c); return 0; } Output: The output of the bitwise exclusive OR operator a^b is 6. The output of the bitwise complement operator ~a is -9. Bitwise Shift Operators were implemented in the program example below. The shift operator shifts ‘n’ bits as it pop and fills ‘0’ bits. Module 3 62 [COMPUTER PROGRAMMING 1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT Gordon College- College of Computer Studies #include int main() { int a=5, b=7; printf("The value of a2 is : %d. ", b>>2); return 0; } Output: The value of a2 is : 1. Arrays : Program Implementation The program example below accepts a list of data items and finds the second largest and second smallest elements. Program computes average and search average value in the array. A message is displayed on successful search. #include #include void main () { int num; int i,j,a,n,count,ave; clrscr(); printf ("Enter the value of N\n"); scanf ("%d", &n); printf ("Enter the numbers \n"); for (i=0; i

Use Quizgecko on...
Browser
Browser