Comp1 Module - Three
Comp1 Module - Three
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
<< Left shift operator
>> Right shift operator
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
These are used to move/shift the bit patterns either to the left or right side.
Operand << x (Left Shift)
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’
Example: x is an integer expression with data 111111. After a shift operation the result will
be:
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 (~).
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;
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
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[4];
This allocates a contiguous block of memory for four (4) elements of type integer with values
equal to 0.
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”.
The array examples above are one-dimensional (1D) arrays. Combining two (2) 1D
arrays can form a 2D array.
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.
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[2][3] = {{10,20,30},{40,50,60}};
You may also use loops, print and ask input using scanf() to create an array.
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[0][1][1];
You may also use the initializer list to create an array with known elements.
int arr[3][2][2] = { { {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.
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[10] = “example”;
char myString[30] = { ‘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’ };
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.
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 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.
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.
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.
These are the two (2) methods of passing data into the function. Table below presents
the differences.
MODULE 3
59
ACTIVITY 1
Name:_________________ Score/Rating:______________
Course:_______________ Date: ____________________
B. 2nd Array
1 2 3 4
5 6 7 8
9 10 11 12
A. What is the built-in library function for comparing the two strings?
_________________________________________________________________________
D. What is the keyword used to transfer control from a function back to the calling function?
_________________________________________________________________________
MODULE 3
61
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 <stdio.h>
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;
}
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 <stdio.h>
int main()
{
int a=23,b=10;
printf("The output of the bitwise OR operator a|b is %d .",a|b);
return 0;
}
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 <stdio.h>
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;
}
Bitwise Shift Operators were implemented in the program example below. The shift operator
shifts ‘n’ bits as it pop and fills ‘0’ bits.
#include <stdio.h>
int main()
{
int a=5, b=7;
printf("The value of a<<2 is : %d . ", a<<2);
printf("\nThe value of b>>2 is : %d . ", b>>2);
return 0;
}
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 <stdio.h>
#include <conio.h>
void main ()
{
int num[30];
int i,j,a,n,count,ave;
clrscr();
MODULE 3
63
{
printf ("%d\n",num[i]);
}
getch();
}
Output:
Enter the value of N
6
Enter the numbers
30
80
10
40
70
90
The numbers arranged in descending order :
90
80
70
40
30
10
The 2nd largest number is = 80
The 2nd smallest number is = 30
The average of 80 and 30 is = 55 : not in the array
The C program below finds the sum of two matrices of order 2*2. It displays the elements in
both matrices and sum of the elements in the matrices.
#include <stdio.h>
int main()
{
if (j == 1)
printf("\n");
}
return 0;
}
Output
MODULE 3
65
Sum Of Matrix:
2.2 0.5
-0.9 25.0
The program example below accepts a string input using scanf. Simulate the program, try to
input a name separated by a space, a name more than twenty (20) characters then observe
the output.
#include <stdio.h>
#include <string.h>
int main()
{
char name[20]; //string declaration
scanf("%s", name);
return 0;
}
Output:
Enter your name: Armi
Armi
The program below uses gets() and puts() functions to accept and display a string input.
Again, simulate the program. Input a name separated by a space, a name more than twenty
(20) characters then observe the output.
#include <stdio.h>
#include <string.h>
int main()
{
char name[20];
return 0;
}
#include <stdio.h>
#include <string.h>
int main()
{
char str1[25] = "C Programming is fun.";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[25] = " C Programming is fun ";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
return 0;
}
Output:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[25] = "C Programming";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
#include<stdio.h>
#include <string.h>
int main(){
char str1[30],str2[30];
printf("Enter 1st string: ");
gets(str1); //reads string from console
MODULE 3
67
Output:
Enter 1st string: Hi
Enter 2nd string: Hello
Strings are not equal
In example below, sayhi() function was invoked with the parameter 5. This function receives
an input value and assigns it to count variable before starting execution of function body.
sayhi() function will then print a hello message count 5 times on the screen.
#include<stdio.h>
/* use function prototypes */
sayhi(int count);
main()
{
sayhi(5);
}
sayhi(int count)
{
int c;
for(c=0;c<count;c++)
printf("Hi\n");
}
The function below returns the value of variable c as the return value of function. You may
also use expressions in return command. Replace two last lines of function with return a-b; If
you forget to return a value in a function you will get a warning message in most of C
compilers. This message will warn you that your function must return a value. Warnings do
not stop program execution but errors stop it.
int sum()
{
int a,b,c;
a=5;
b=4;
c=a-b;
reurn c;
}
The program below calculates factorial of a number and is an example of a recursive
function. Recursive function is like a process being performed where one of the instructions
#include<stdio.h>
int recur(int);
main()
{
int a, fact ;
printf("\nInput a number ");
scanf ("%d", &a);
fact = rec(a);
printf ("Factorial value = %d", fact);
}
int recur (int x)
{
int f;
if (x == 1)
return (1);
else
f = x * recur (x - 1) ;
return (f) ;
}
Program Examples
#include <stdio.h>
MODULE 3
69
Output:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
if(checkAnagram(str1, str2) == 1)
{
str1[strlen(str1)-1] = '\0';
str2[strlen(str2)-1] = '\0';
printf(" %s and %s are Anagram.\n\n",str1,str2);
}
else
{
str1[strlen(str1)-1] = '\0';
str2[strlen(str2)-1] = '\0';
printf(" %s and %s are not Anagram.\n\n",str1,str2);
}
return 0;
}
MODULE 3
71
Activity 2
Name:_________________ Score/Rating:______________
Course:___ _____________ Date: ____________________
1. Give the output of the program and show the process on how the output values were
derived (conversion process and shifts).
#include <stdio.h>
int main()
{
int a=30, b=40;
printf("The value of a<<3 is : %d . ", a<<3);
printf("\nThe value of b>>4 is : %d . ", b>>4);
return 0;
}
2. Create a program to compute sum of array elements of three (3) matrices (2x2x2).
Program must accept input (elements) and displays the sum.
3. Type the source code in your editor. Try out the program a few times to ensure that it
accepts only hello as the proper password. Next, eliminate the match variable from your
code and use the strcmp() function directly in the if comparison. That is how most
programmers do it. Then, replace the strcmp() function with strcasecmp(). Run the program
to confirm that both hello and HELLO are accepted as the password.
#include <stdio.h>
#include <string.h>
int main()
{
char password[]="hello";
char input[15];
int match;
printf("Password: ");
scanf("%s",input);
match=strcmp(input,password);
if(match==0)
puts("Password accepted.");
else
puts("Invalid password!");
return(0);
}
4. Write a C programming to check an array of numbers and outputs the maximum (largest)
and minimum (smallest) of the values using function.