0% found this document useful (0 votes)
43 views

Comp1 Module - Three

Bitwise operators allow manipulation of data at the bit level and are useful for speeding up numerical computations. Common bitwise operators include AND, OR, XOR, and shift operators. Bitwise operators work on integer data types by performing logical operations on corresponding bits. Arrays store a collection of related data and can have one, two, or more dimensions laid out in contiguous memory locations. Multidimensional arrays extend the concept of arrays to multiple indices.

Uploaded by

Sonic Hedgehog
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Comp1 Module - Three

Bitwise operators allow manipulation of data at the bit level and are useful for speeding up numerical computations. Common bitwise operators include AND, OR, XOR, and shift operators. Bitwise operators work on integer data types by performing logical operations on corresponding bits. Arrays store a collection of related data and can have one, two, or more dimensions laid out in contiguous memory locations. Multidimensional arrays extend the concept of arrays to multiple indices.

Uploaded by

Sonic Hedgehog
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

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
<< Left shift 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 (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’

2nd Segment, A.Y. 2020-2021



54

[COMP1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


BHMC

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 (left shift) = 111111<<2 = 111100


x>>2 (right shift) = 111111>>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[4];

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[0] = 10;
2nd element : a[1] = 20;
3rd element : a[2] = 2;
4th element : a[3] = 18; Representation of the array with new values in memory ;

To print array values;

printf ("%d %d %d %d\n", a[0], a[1], a[2], a[3]);

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[4] = { 40, 50, 60, 100}; This will create an array of size 4, and initialize a[0] to 40,
a[1] to 50, a[3] to 60 and a[4] 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.

2nd Segment, A.Y. 2020-2021



56

[COMP1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


BHMC

To declare a 2D array, you must know: the data type, the variable name and the size
of the ID arrays.

Example : int a[2][4];

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[0][2]; the second row, second
column, use a[1][1].
If you want to create the array in the table representation shown below, write it as follows:

int arr[2][2] = {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[2][3] = {{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[3][2][2]; 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[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.

Declaring and Initializing Strings


Strings are declared similar to an array of characters.
data type String_Name[number_of_elements];

example: char sample[21];

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’ };

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

2nd Segment, A.Y. 2020-2021



58

[COMP1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


BHMC

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

2nd Segment, A.Y. 2020-2021



60

[COMP1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


BHMC

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[5]);
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 <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;
}

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 <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;
}

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 <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;
}

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.

2nd Segment, A.Y. 2020-2021



62

[COMP1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


BHMC

#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;
}

Output: The value of a<<2 is : 20.


The value of b>>2 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 <stdio.h>
#include <conio.h>

void main ()
{
int num[30];
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<n; ++i)
scanf ("%d",&num[i]);

for (i=0; i<n; ++i)


{
for (j=i+1; j<n; ++j)
{
if (num[i] < num[j])
{
a = num[i];
numb[i] = num[j];
numb[j] = a;
}
}
}

printf ("The numbers arranged in descending order:\n");


for (i=0; i<n; ++i)

MODULE 3

63

{
printf ("%d\n",num[i]);
}

printf ("The 2nd largest number is = %d\n", num[1]);


printf ("The 2nd smallest number is = %d\n", num[n-2]);

ave = (num[1] +num[n-2])/2;


counter = 0;

for (i=0; i<n; ++i)


{
if (ave == num[i])
{
++count;
}
}
if (count == 0 )
printf ("The average of %d and %d is = %d : not in the array\n", num[1], num[n-2], ave);
else
printf ("The average of %d and %d in array is %d in numbers\n",num[1], num[n-2],
count);

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()
{

2nd Segment, A.Y. 2020-2021



64

[COMP1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


BHMC

float a[2][2], b[2][2], sum[2][2];

// Takes input thru nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input thru nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding elements of two arrays


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
sum[i][j] = a[i][j] + b[i][j];
}

// Displays the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", sum[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}
Output

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;

MODULE 3

65

Enter b22: 23;

Sum Of Matrix:
2.2 0.5
-0.9 25.0

Strings : Program Implementation

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

printf("Enter your name:");

scanf("%s", name);

printf("%s", name);//displays the string input

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];

/* Console display using puts */


puts("Enter your name:");

/*Input using gets*/


gets(name);
puts(name);

return 0;
}

2nd Segment, A.Y. 2020-2021



66

[COMP1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


BHMC

The following program examples implement some of the String Functions. Make time to
simulate the program and observe the output.

#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:

Length of string str1: 21

#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:

Length of string str1 when maxlen is 30: 21


Length of string str1 when maxlen is 10: 10

#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:

Output string after concatenation: HelloC Programming

#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

printf("Enter 2nd string: ");


gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}

Output:
Enter 1st string: Hi
Enter 2nd string: Hello
Strings are not equal

Functions : Program Implementation

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

2nd Segment, A.Y. 2020-2021



68

[COMP1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


BHMC

is to "repeat the process". This may be similar to a loop because it repeats the same code.
Loop in C refers to a set of statement getting executed repeatedly ,also called iteration.
Recursion is a technique of a function giving birth to itself. That is, calling itself again and
again until some condition gets fulfilled.

#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

This example shows the simple structure of a function.

#include <stdio.h>

int sum (int, int); //function declaration


int main (void)
{
int total;
printf("\n\n A simple structure of function \n");
printf("------------------------------------------------\n");
total = sum (10, 12); //function call
printf ("The SUM is : %d\n", total);
return 0;
}

int sum (int a, int b) //function definition


{
int s;
s=a+b;
return s; //function returning a value
}

MODULE 3

69

Output:

A simple structure of function


------------------------------------------------
The SUM is : 22

This program example checks whether a string is an anagram. An anagram is a word or


phrase that is formed by rearranging the letters of another word or phrase.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int checkAnagram(char *str1, char *str2);


int main()
{
char str1[30], str2[30];
printf("\n\n Checks whether two given strings are anagram \n");
printf("\n\n Example : Listen = Silent \n");
printf("-------------------------------------------------------\n");
printf(" Input the first String : ");
fgets(str1, sizeof str1, stdin);
printf(" Input the second String : ");
fgets(str2, sizeof str2, stdin);

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;
}

//Function to check whether two passed strings are anagram or not


int checkAnagram(char *str1, char *str2)
{
int str1ChrCtr[256] = {0}, str2ChrCtr[256] = {0};
int ctr;
/* check the length of equality of the Strings */
if(strlen(str1) != strlen(str2))
{
return 0;
}
//count frequency of characters in str1
for(ctr = 0; str1[ctr] != '\0'; ctr++)
{

2nd Segment, A.Y. 2020-2021



70

[COMP1 MODULE] BY : ARMILYN T. MARTINEZ, MSIT


BHMC

str1ChrCtr[str1[ctr]]++;
}
//count frequency of characters in str2
for(ctr = 0; str2[ctr] != '\0'; ctr++)
{
str2ChrCtr[str2[ctr]]++;
}
//compare character counts of both strings
for(ctr = 0; ctr < 256; ctr++)
{
if(str1ChrCtr[ctr] != str2ChrCtr[ctr])
return 0;
}
return 1;
}
Checks whether two given strings are anagram
Example : listen = silent
-------------------------------------------------------
Input the first String : listen
Input the second String : silent
listen and silent are Anagram.

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.

Sample Output: (Test Data>> (input) 3 ( 4,5,6)

Number of values you want to input: 3


Minimum value is: 4
Maximum value is: 6

2nd Segment, A.Y. 2020-2021

You might also like