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

CS112 Programming Languages 1 (Lecture 11 - Spring 2020)

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

CS112 Programming Languages 1 (Lecture 11 - Spring 2020)

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

CS112 – Level 1

Programming Languages 1
( General Division – Software Engineering Program – Medical Informatics Program )

Lecture 11
Revision; Basic / Simple Solved Examples [ 3 ]

Spring 2020 (Semester 2)


Week 12
Course & Lectures are based on their counterparts in the following courses:
o Harvard University's CS50; An introduction to the intellectual enterprises of
computer science and the art of programming, Harvard School of
Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New
South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++
(2011), and 6.S096 Introduction to C and C++ (2013), MIT (Massachusetts
1
Institute of Technology) OpenCourseWare.
• Solved Examples
Write a C Program to :
• 11.1: .. Calculate Permutation (nPr) and
Combination (nCr).
• 11.2: .. Find the Transpose of a given Matrix.
• 11.3: .. Check whether an array is a subset of
another array.
•O11.4: .. Sort an array of 0s, 1s and 2s.
•u11.5: .. Find the Binary Representation of an
t Integer using Bitwise Operators.

Outline •l 11.6: .. Compare the Contents of Two Files (their


i names should be passed as Command-Line
nArguments)
e
• 11.7: .. Read and Print a Student’s Details using a
Structure Pointer.
• 11.8: .. Read an entire string – with whitespace(s)
– using scanf() versus gets()
• 11.9: Regarding Command-Line Arguments ..
What is the output of the following C Program
2
for each of the given cases.
Revision ..
Solved
Examples [ 3 ]

3
11.1: Write a C Program to Calculate ..
Permutation (nPr) .. and .. Combination (nCr)
nC and nPr are statistical quantities regarding possible subsets of a
r
set of objects, and they are defined as:
nP ( n, r ) = n! / ( n − r )!
r
nC ( n, r ) = nP ( n, r ) / r! = n! / ( r! ( n − r )! )
r r

Using sets to help define them:


o nPr is the formula to find permutations of n objects taking r at a
time. This answers the question of how many possible groups of
r objects from a set of n objects. And, ..
o nCr is the formula to find the unique permutations, otherwise
known as combinations, of n objects taking r at a time. This
answers the question of how many unique possible groups of r
objects can be made from n objects.
11.1: Write a C Program to Calculate ..
Permutation (nPr) .. and .. Combination (nCr)
Example: Take the set { 1, 2, 3, 4} and find all combinations and
permutations taking 2 at a time:

We can make this set of sets making every possible combination of


the 4 objects in the set taking 2 at a time (we aren't allowed to
reuse an object once we've use it):
------- {2, 1} {3, 1} {4, 1}
{1, 2} ------- {3, 2} {4, 2}
{1, 3} {2, 3} ------- {4, 3}
{1, 4} {2, 4} {3, 4} -------

This result of 12 sets is the calculation of nPr( 4, 2), the total number
of permutations of 4 objects taking 2 at a time. We can confirm that
the formula produces 12:
nP ( 4, 2) = 4! / ( 4 − 2 )! = ( 4 ∗ 3 ∗ 2 ∗ 1 ) / ( 2 ∗ 1 ) = 24 / 2 = 12
r
11.1: Write a C Program to Calculate ..
Permutation (nPr) .. and .. Combination (nCr)
Example: Take the set { 1, 2, 3, 4} and find all combinations and
permutations taking 2 at a time:

Now, if we want to look at unique sets, then { 1, 2} = { 2, 1} and


likewise for all sets with the same numbers in them. Or, for this
case, we can remove half of the grid we've created.

------- {2, 1} {3, 1} {4, 1}


------- ------- {3, 2} {4, 2}
------- ------- ------- {4, 3}
------- ------- ------- -------

This leaves us with 6 unique groups, and we can confirm with


the nCr formula that we get 6:
nC ( 4, 2) = nP ( 4, 2) / r! = 12 / ( 2 ∗ 1 ) = 12 / 2 = 6
r r
11.1: Write a C Program to Calculate ..
Permutation (nPr) .. and .. Combination (nCr)
#include<stdio.h>

// Function Prototype Declarations


long factorial( int );
long find_npr( int, int ); Enter the values of n and r respectively :
long find_ncr( int, int ); 42

int main() { 4C2 = 6


int n, r; 4P2 = 12
long npr, ncr;
printf("Enter the value of n and r respectively: \n");
scanf("%d%d", &n, &r);
// Function Calls
npr = find_npr( n, r );
ncr = find_ncr( n, r );
printf("\n\t %dC%d = %ld\n", n, r, ncr );
printf("\n\t %dP%d = %ld\n", n, r, npr );
return 0;
}
// Function for Calculating nCr
long find_ncr( int a, int b )
{
return ( factorial( a ) / ( factorial( b ) * factorial( a - b ) ) );
}

// Function for Calculating nPr


long find_npr( int a, int b )
{
return ( factorial( a ) / factorial( a - b ) );
}

// Recursive Function for Calculating the Factorial


long factorial( int c )
{
if( c == 1 || c == 0 )
return 1;
else
return c * factorial( c - 1 );
}
11.2: Write a C Program to find the Transpose
of a given Matrix.

In linear algebra, the transpose of a matrix is an operator which flips


a matrix over its diagonal, that is, it switches the row and column
indices of the matrix by producing another matrix denoted as AT ..
11.2: Write a C Program to find the Transpose
of a given Matrix.

Input the number of rows and columns of the matrix : 2 2


Input the elements of the first matrix :
Element - [0], [0] : 1
Element - [0], [1] : 2
Element - [1], [0] : 3
Element - [1], [1] : 4

The matrix is :
1 2
3 4
The transpose of the matrix is :
1 3
2 4
#include <stdio.h>

int main(void)
{
int arr1[ 50 ][ 50 ], brr1[ 50 ][ 50 ], i, j, r, c;
printf("\nInput the number of rows and columns of the matrix : ");
scanf("%d %d", &r, &c);
printf("Input the elements of the first matrix :\n");
for( i = 0; i < r; i++ )
{
for( j = 0; j < c; j++ )
{
printf("Element - [%d], [%d] : ", i, j);
scanf("%d", &arr1[ i ][ j ] );
}
}
printf("\nThe matrix is :\n");
for( i = 0; i < r; i++ )
{
printf("\n");
for( j = 0; j < c; j++ )
printf("%d\t", arr1[ i ][ j ] );
}
for( i = 0; i < r; i++ )
{
for( j = 0; j < c; j++ )
{
brr1[ j ][ i ] = arr1[ i ][ j ];
}
}

printf("\n\nThe transpose of the matrix is : ");


for( i = 0; i < c; i++ )
{
printf("\n");
for( j = 0; j < r; j++ )
{
printf("%d\t", brr1[ i ][ j ] );
}
}
}
11.3: Write a C Program to Check whether an
array is a subset of another array ..
#include <stdio.h>
int chkSubsetArray( int *arr1, int arr1_size, int *arr2, int arr2_size ) ;
int main()
{
int arr1[] = {4, 8, 7, 11, 6, 9, 5, 0, 2}; int arr2[] = {5, 4, 2, 0, 6};
int n1 = sizeof( arr1 ) / sizeof( arr1[ 0 ] ); int n2 = sizeof( arr2 ) / sizeof( arr2[ 0 ] );
int i;
//------------- Print the First Array ------------------
printf("The given First Array is : ");
for( i = 0; i < n1; i++ ) { printf("%d ", arr1[ i ] ); }
printf("\n");
//------------- Print the Second Array ------------------
printf("The given Second Array is : ");
for( i = 0; i < n2; i++ ) { printf("%d ", arr2[ i ] ); }
printf("\n");
//------------------------------------------------------
if( chkSubsetArray( arr1, n1, arr2, n2 ) )
printf("The Second Array is a Subset of the First Array.");
else
printf("The Second Array is Not a Subset of the First Array");
return 0;
}
int chkSubsetArray( int *arr1, int arr1_size, int *arr2, int arr2_size )
{
int i, j;
for ( i = 0; i < arr2_size; i++ )
{
for ( j = 0; j < arr1_size; j++ )
{
if( arr2[i] == arr1[j] )
break;
}
if( j == arr1_size )
return 0;
}
return 1;
}
11.4: Write a C Program to sort an array of 0s,
1s and 2s ..

The Given Array is :


012210020110
After Sorting, the Elements of the Array are:
000001111222
#include <stdio.h>
void swap( int arr1[], int i, int j );
void sortElements( int arr1[], int end );

int main()
{
int arr1[] = { 0, 1, 2, 2, 1, 0, 0, 2, 0, 1, 1, 0 };
int n = sizeof( arr1 ) / sizeof( arr1[ 0 ] );
int i;
//------------- Print the Original Array ------------------
printf("The Given Array is :\n\n");
for( i = 0; i < n; i++ ) { printf("%d ", arr1[ i ] ); } printf("\n\n\n");
//-------------- Print the Sorted Array ------------------
sortElements( arr1, n - 1 );
printf("After Sorting, the Elements of the Array are: \n\n");
for( i = 0; i < n; i++ ) { printf("%d ", arr1[ i ] ); } printf("\n\n\n");
return 0;
}
void swap( int arr1[], int i, int j )
{
int tmp = arr1[ i ];
arr1[ i ] = arr1[ j ];
arr1[ j ] = tmp;
}
Tracing:
void sortElements( int arr1[], int end )
{ { 0, 1, 2, 2, 1, 0, 0, 2, 0, 1, 1, 0 } | start = 0, mid = 0, end = 11
int start = 0, mid = 0;
int pivot = 1; { 0, 1, 2, 2, 1, 0, 0, 2, 0, 1, 1, 0 } | start = 1, mid = 1, end = 11
while( mid <= end )
{ start = 1, mid = 2, end = 11
if ( arr1[ mid ] < pivot )
{ { 0, 1, 0, 2, 1, 0, 0, 2, 0, 1, 1, 2 } | start = 1, mid = 2, end = 10
swap( arr1, start, mid );
{ 0, 0, 1, 2, 1, 0, 0, 2, 0, 1, 1, 2 } | start = 2, mid = 3, end = 10
++start, ++mid;
} { 0, 0, 1, 1, 1, 0, 0, 2, 0, 1, 2, 2 } | start = 2, mid = 3, end = 9
else if ( arr1[ mid ] > pivot )
{ start = 2, mid = 4, end = 9
swap( arr1, mid, end );
--end; start = 2, mid = 5, end = 9
}
{ 0, 0, 0, 1, 1, 1, 0, 2, 0, 1, 2, 2 } | start = 3, mid = 6, end = 9
else
{ { 0, 0, 0, 0, 1, 1, 1, 2, 0, 1, 2, 2 } | start = 4, mid = 7, end = 9
++mid;
} { 0, 0, 0, 0, 1, 1, 1, 1, 0, 2, 2, 2 } | start = 4, mid = 7, end = 8
}
} { 0, 0, 0, 0, 1, 1, 1, 1, 0, 2, 2, 2 } | start = 4, mid = 8, end = 8

{ 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2 } | start = 5, mid = 9, end = 8


11.5: Write a C Program to find the Binary
Representation of an Integer using Bitwise
Operators
In this C program, we will read an integer (decimal) number, and
print its Binary Value (Binary Representation).

In this program, we are finding the Binary values of 16 bits


numbers. The logic is very simple – we have to just traverse each
bit using the Bitwise AND operator. To traverse each bit – we will
run loop from 15 to 0 (we are doing this to print the Binary
representation in a proper format).

Enter an Integer Number : 13


The Binary Value of 13 is = 0000000000001101
#include <stdio.h>
void getBinary( int );
int main()
{
int num = 0;
printf("Enter an Integer Number : ");
scanf("%d", &num );
printf("\nThe Binary Value of %d is = ", num );
getBinary( num );
return 0;
}

void getBinary( int n ) /* Function Definition : getBinary() */


{
int loop;
/* loop = 15, for representing a 16 bits value, 15th bit to 0th bit */
for( loop = 31; loop >= 0; loop-- )
{
if( ( 1 << loop ) & n )
printf("1");
else
printf("0");
}
}
11.6: Write a C Program to Compare the
Contents of Two Files (their names should be
passed as Command-Line Arguments)
#include <stdio.h>
int main( int argc, char *argv[] )
{
FILE *fp1, *fp2; int cnt1 = 0, cnt2 = 0, flg = 0;

if( argc < 3 )


{
printf("Insufficient Arguments!!!\n");
printf("Please use \"program-name file-name1 file-name2\" format.\n");
return -1;
}
fp1 = fopen( argv[ 1 ], "r" );
if( fp1 == NULL )
{ printf("\n%s could not be opened.\n", argv[ 1 ] ); return -1; }
fp2 = fopen( argv[ 2 ], "r" );
if( fp2 == NULL )
{ printf("\n%s could not be opened.\n",argv[ 2 ] ); return -1; }
// Move the file pointer to the end, and get the total number of bytes per file
fseek( fp1, 0, SEEK_END ); cnt1 = ftell( fp1 );
fseek( fp2, 0, SEEK_END ); cnt2 = ftell( fp2 );

// Check if the total number of bytes (of both files) are equal
if( cnt1 != cnt2 ) { printf("\nThe size of both files is not the same.\n"); }
else // Check if the contents of both files are the same
{
fseek( fp1, 0, SEEK_SET );
fseek( fp2, 0, SEEK_SET );
while( ! feof( fp1 ) )
{
if( fgetc( fp1 ) != fgetc( fp2 ) )
{
flg = 1;
break;
}
}
if( flg ) printf("\nThe contents of both files are NOT the same.\n");
else printf("\nThe contents of both files are the same.\n");
}
fclose( fp1 ); fclose( fp2 );
return 0;
}
11.7: Write a C Program to Read and Print a
Student’s Details using a Structure Pointer.
#include <stdio.h>
struct student{
char name[30];
int id; There are two ways of accessing members of structure using pointer:
float perc;
}; - Using arrow (->) operator or membership operator.
int main() - Using indirection (*) operator and dot (.) operator.
{
struct student std; // Structure Variable
struct student *ptr; // Pointer to a Student Structure
ptr = &std; // Assigning a value to the Pointer (the Address of a Structure Variable)
printf("Enter the Details of a Student: ");
printf("\nName? :"); gets( ptr->name );
printf("ID No.? :"); scanf("%d", &ptr->id );
printf("Percentage? :"); scanf("%f", &ptr->perc );
printf("\nThe Entered details are: \n");
printf("Name: %s\nID. No: %d \nPercentage: %.02f\n", ptr->name, ptr->id, ptr->perc );
return 0;
}
An Alternative Solution ..
#include <stdio.h>
struct student{
char name[30];
int id; There are two ways of accessing members of structure using pointer:
float perc;
}; - Using arrow (->) operator or membership operator.
int main() - Using indirection (*) operator and dot (.) operator.
{
struct student std; // Structure Variable
struct student *ptr; // Pointer to a Student Structure
ptr = &std; // Assigning a value to the Pointer (the Address of a Structure Variable)
printf("Enter the Details of a Student: ");
printf("\nName? :"); gets( (*ptr).name );
printf("ID No.? :"); scanf("%d", &(*ptr).id );
printf("Percentage? :"); scanf("%f", &(*ptr).perc );
printf("\nThe Entered details are: \n");
printf("Name: %s\nID. No: %d \nPercentage: %.02f\n", (*ptr).name,(*ptr).id,(*ptr).perc );
return 0;
}
If solved without using pointers .. ?
#include <stdio.h>
struct student{
char name[30];
int id;
float perc;
}; For accessing the members of a structure, use the dot/member (.) operator.
int main()
{
struct student std; // Structure Variable
printf("Enter the Details of a Student: ");
printf("\nName? :"); gets( std.name );
printf("ID No.? :"); scanf("%d", &std.id );
printf("Percentage? :"); scanf("%f", &std.perc );
printf("\nThe Entered details are: \n");
printf("Name: %s\nID. No: %d \nPercentage: %.02f\n", std.name, std.id, std.perc );
return 0;
}
11.8: Write a C Program to Read an Entire
String – with whitespace(s) – using scanf()
versus gets().
scanf()
- It is used to read the input (a character, a string, numeric data) from
#include <stdio.h> the standard input (keyboard).
int main() - It is used to read the input until it encounters a whitespace, a
{ newline, or End Of File (EOF).
char str[20];

printf("Enter a string: ");


scanf("%s", str);
printf("You entered: %s\n", str);

return 0;
}
11.8: Write a C Program to Read an Entire
String – with whitespace(s) – using scanf()
versus gets().
gets()
- It is used to read the input (a string) from the standard input
#include <stdio.h> (keyboard).
int main() - It is used to read the input until it encounters a newline or End Of
{ File (EOF).
char str[20];

printf("Enter a string: ");


gets(str);
printf("You entered: %s\n", str);

return 0;
}
11.8: Write a C Program to Read an Entire
String – with whitespace(s) – using scanf()
versus gets().
So, how to read a complete sentence from a user using scanf() .. ?
By using %[^\n]s inside the scanf() to read an entire string.
#include <stdio.h> The \n indicates that the input is read until a newline is encountered.
int main()
{
char str[200];
printf("Enter a string: ");
scanf("%[^\n]s", str);
printf("You entered: %s\n", str);
return 0;
}
11.9: Regarding Command-Line Arguments ..
What is the output of the following C Program
for each of the given cases:
// C program to illustrate Command-Line Arguments
#include<stdio.h>
C:\Users\Admin˃MyProgram.exe
int main( int argc, char* argv[] )
C:\Users\Admin˃MyProgram.exe First Second Third
{
C:\Users\Admin˃MyProgram.exe “First Second Third”
int counter;
printf(" Program Name Is: %s", argv[0] );
if( argc == 1 )
printf("\n No Extra Command-Line Arguments Passed Other Than the Program's Name");
if( argc >= 2 )
{
printf("\n Number Of Arguments Passed: %d", argc );
printf("\n ---- Following Are The Command-Line Arguments Passed ----");
for( counter = 0; counter < argc; counter++ )
printf("\n argv[ %d ]: %s", counter, argv[ counter ] );
}
return 0;
}
C:\Users\Admin˃MyProgram.exe
Program Name Is: MyProgram.exe
No Extra Command-Line Arguments Passed Other Than the Program's Name

C:\Users\Admin˃MyProgram First Second Third


Program Name Is: MyProgram
Number Of Arguments Passed: 4
---- Following Are The Command-Line Arguments Passed ----
argv[ 0 ]: MyProgram
argv[ 1 ]: First
argv[ 2 ]: Second
argv[ 3 ]: Third

C:\Users\Admin˃MyProgram.exe “First Second Third”


Program Name Is: MyProgram.exe
Number Of Arguments Passed: 2
---- Following Are The Command-Line Arguments Passed ----
argv[ 0 ]: MyProgram.exe
argv[ 1 ]: First Second Third
Thanks! .. Questions?

31

You might also like