You are on page 1of 86

School of Computing

Department of Computer Science and Engineering


ACADEMIC YEAR 2019-20(Winter Semester)

1152CS314 - PRINCIPLES OF PROGRAMMING LOGIC

NAME: MOHAMED SHAHIN BRANCH: CSE

YEAR/SEM: III / 6 VTU.NO: 8607

REG.NO: 17UECS0455 SLOT: S10


School of Computing
Department of Computer Science and Engineering
ACADEMIC YEAR 2019-20(Winter Semester)
BONAFIDE CERTIFICATE

NAME : MOHAMED SHAHIN BRANCH : CSE

VTU NO : 8607 REG.NO : 17UECS0455

YEAR/SEM : III/6

Certified that this is a bonafide record of work done by above


student in the "1152CS314 - PRINCIPLES OF PROGRAMMING
LOGIC" during the year 2019-2020.

SIGNATURE OF FACULTY INCHARGE SIGNATURE OF HOD

Submitted for the Semester Examination held on ............................ at Vel Tech


Rangarajan Dr.Sagunthala R&D Institute of Science and Technology.

INTERNAL EXAMINER EXTERNAL EXAMINER


INDEX
PAGE
S.N0 DATE TITLE MARKS SIGN
NO.

1 21.01.2020 STUDY ON WORKING AND STORING OF DATA 1

2 24.01.2020 POINT OUT THE ERRORS 10

28.01.2020 FIND THE OUTPUT OF THE GIVEN CODE 16


3
SEGMENTS

4
04.02.2020 POINTOUT THE OUTPUT OF LOOPING & 22
CONDITIONING CODE SEGMENTS

5 11.02.2020 BASIC NUMBER THEORY I 27

6 18.02.2020 BASIC NUMBER THEORY II 33

7
25.02.2020 IMPLEMENTATION OF PRIME NUMBER 38
CONCEPTS

8 03.03.2020 IMPLEMENTATION OF PRIMARILITY TEST 43

9 07.04.2020 DATASTRUCTURES ALGORITHMS 48

10
11.04.2020 CODE OPTIMIZATION AND MODULARITY 54
IMPLEMENTATION

11 12.05.2020 PARTIAL CODE COMPLETION 60

12 16.05.2020 IMPLEMENT COMMON STYLE TECHNIQUE 73

13
19.05.2020 STUDY ON BASIC CONCEPTS OF COMPILE, LINK 76
AND OS

14
19.05.2020 PRACTICE PROBLEMS FOR CODE 81
IMPLEMENTATION
TASK 1
STUDY ON WORKING AND STORING OF DATA
DATA TYPES:
Data types in c refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage and
how the bit pattern stored is interpreted.
The types in C can be classified as follows:
Basic Types
They are arithmetic types and are further classified into: (a) integer types and (b) floating-
point types.
Enumerated types
They are again arithmetic types and they are used to define variables that can only assign
certain discrete integer values throughout the program.
The type void
The type specifier void indicates that no value is available.
Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e)
Function types.

Integer Types

The following table provides the details of standard integer types with their storage sizes and
value ranges −

Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

-32,768 to 32,767 or -2,147,483,648 to


int 2 or 4 bytes
2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

1
short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 8 bytes -9223372036854775808 to


9223372036854775807

unsigned long 8 bytes 0 tOo 18446744073709551615

To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type
in bytes. Given below is an example to get the size of various type on a machine using
different constant defined in limits.h header file
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>

int main(int argc, char** argv) {

printf("CHAR_BIT : %d\n", CHAR_BIT);


printf("CHAR_MAX : %d\n", CHAR_MAX);
printf("CHAR_MIN : %d\n", CHAR_MIN);
printf("INT_MAX : %d\n", INT_MAX);
printf("INT_MIN : %d\n", INT_MIN);
printf("LONG_MAX : %ld\n", (long) LONG_MAX);
printf("LONG_MIN : %ld\n", (long) LONG_MIN);
printf("SCHAR_MAX : %d\n", SCHAR_MAX);
printf("SCHAR_MIN : %d\n", SCHAR_MIN);
printf("SHRT_MAX : %d\n", SHRT_MAX);
printf("SHRT_MIN : %d\n", SHRT_MIN);
printf("UCHAR_MAX : %d\n", UCHAR_MAX);
printf("UINT_MAX : %u\n", (unsigned int) UINT_MAX);

2
printf("ULONG_MAX : %lu\n", (unsigned long) ULONG_MAX);
printf("USHRT_MAX : %d\n", (unsigned short) USHRT_MAX);

return 0;
}
SAMPLE OUTPUT:
CHAR_BIT : 8
CHAR_MAX : 127
CHAR_MIN : -128
INT_MAX : 2147483647
INT_MIN : -2147483648
LONG_MAX : 9223372036854775807
LONG_MIN : -9223372036854775808
SCHAR_MAX : 127
SCHAR_MIN : -128
SHRT_MAX : 32767
SHRT_MIN : -32768
UCHAR_MAX : 255
UINT_MAX : 4294967295
ULONG_MAX : 18446744073709551615
USHRT_MAX : 65535

Floating-Point Types

The following table provide the details of standard floating-point types with storage sizes
and value ranges and their precision −

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal


places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal


places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal


places

The header file float.h defines macros that allow you to use these values and other details
about the binary representation of real numbers in your programs. The following example
prints the storage space taken by a float type and its range values.

3
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>

int main(int argc, char** argv) {

printf("Storage size for float : %d \n", sizeof(float));


printf("FLT_MAX : %g\n", (float) FLT_MAX);
printf("FLT_MIN : %g\n", (float) FLT_MIN);
printf("-FLT_MAX : %g\n", (float) -FLT_MAX);
printf("-FLT_MIN : %g\n", (float) -FLT_MIN);
printf("DBL_MAX : %g\n", (double) DBL_MAX);
printf("DBL_MIN : %g\n", (double) DBL_MIN);
printf("-DBL_MAX : %g\n", (double) -DBL_MAX);
printf("Precision value: %d\n", FLT_DIG );

return 0;
}
SAMPLE OUTPUT:
Storage size for float : 4
FLT_MAX : 3.40282e+38
FLT_MIN : 1.17549e-38
-FLT_MAX : -3.40282e+38
-FLT_MIN : -1.17549e-38
DBL_MAX : 1.79769e+308
DBL_MIN : 2.22507e-308
-DBL_MAX : -1.79769e+308
Precision value: 6

4
CHARACTER DATA TYPES :
Character data types are strings of characters. Upper and lower case alphabetic characters
are accepted literally. There is one fixed-length character data type: char, and two variable-
length character data types: varchar and long varchar. ... Char strings are padded with
blanks to the declared length.
CODE:

#include

void main() {

char character1, character2;

character1 = 82; // code for R

character2 = 'S';

printf("character1 and character2: \n");

printf("%c \n",character1);

printf("%c \n",character2);

}
SAMPLE OUTPUT:
Character1 & character2
R
S

Arrays:
An array is a collection of data items, all of the same type, accessed using a common name.
A one-dimensional array is like a list; A two dimensional array is like a table;
The C language places no limits on the number of dimensions in an array, though specific
implementations may.
CODE:

#include <stdio.h>

int main () {

int n[ 10 ]; /* n is an array of 10 integers */

int i,j;

5
/* initialize elements of array n to 0 */

for ( i = 0; i < 10; i++ ) {

n[ i ] = i + 100; /* set element at location i to i + 100 */

/* output each array element's value */

for (j = 0; j < 10; j++ ) {

printf("Element[%d] = %d\n", j, n[j] );

return 0;

}
FUNCTIONS:
A function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional
functions.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division is such that each function performs
a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to
another location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.

PROGRAM:

#include <stdio.h>

/* function declaration */

int max(int num1, int num2);

int main () {

6
/* local variable definition */

int a = 100;

int b = 200;

int ret;

/* calling a function to get max value */

ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;

/* function returning the max between two numbers */

int max(int num1, int num2) {

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}
SAMPLE OUTPUT:
Max value is : 200

POINTERS:
Pointers in C are easy and fun to learn. Some C programming tasks are performed more
easily with pointers, and other tasks, such as dynamic memory allocation, cannot be
performed without using pointers. So it becomes necessary to learn pointers to become a
perfect C programmer. Let's start learning them in simple and easy steps.

7
As you know, every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand (&) operator, which denotes an address in
memory. Consider the following example, which prints the address of the variables defined
.
PROGRAM 1:

#include <stdio.h>

int main () {

int var1;

char var2[10];

printf("Address of var1 variable: %x\n", &var1 );

printf("Address of var2 variable: %x\n", &var2 );

return 0;

}
SAMPLE OUTPUT:
Address of var1 variable: 1df9afec
Address of var2 variable: 1df9afe2

PROGRAM 2:

#include <stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0; }
SAMPLE OUTPUT:
Address of var variable: 586b1244
Address stored in ip variable: 586b1244
Value of *ip variable: 20

8
NULL POINTER:

It is always a good practice to assign a NULL value to a pointer variable in case you do not
have an exact address to be assigned. This is done at the time of variable declaration. A
pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program −
PROGRAM:

#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
SAMPLE OUTPUT:

The value of ptr is : 0

STRING:
Strings are actually one-dimensional array of characters terminated by a null character '\0'.
Thus a null-terminated string contains the characters that comprise the string followed by
a null.
The following declaration and initialization create a string consisting of the word "Hello".
To hold the null character at the end of the array, the size of the character array containing
the string is one more than the number of characters in the word "Hello."

PROGRAM :

#include <stdio.h>

int main () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

printf("Greeting message: %s\n", greeting );

return 0;

SAMPLE OUTPUT:
Greeting message: Hello

9
TASK 2
POINT OUT THE ERRORS
1)
#include<stdio.h>
int main()
{
Int a= 35; float b = 3.24;
Printf(“%d %f %d”,a,b+1.25,235);
}
Reason: - It adds the values according to condition given 354.74 and return the value.

2)
#include<stdio.h>
int main()
{
int a,b,c;
scanf(“%d %d %d” , a,b,c);
}
Reason: -
Garbage value because of value and also address is not specified in the scanf.

3)
#include<stdio.h>
int main()
{
int m1,m2,m3;
printf(“enter values of marks in 3 subjects”);
scanf(“%d %d %d”,&m1,&m2,&m3);
printf(“you entered %d %d %d”,m1,m2,m3);
}
Reason: - Enter value of marks in 3 subjects

10
M1 = 10
M2 = 20 => 102030
M3 = 30[ combinely print the whole value]

4)
#include<stdio.h>
int main()
{
Float a = 15.5;
Char ch = ‘c’;
printf(a,ch);
Return 0 ;
}
printf(a,ch)
{
Reason: - return garbage value and value as “0”

5)
#include<stdio.h>
int main()
{
long num = 2;
printf(“%d /n”,num);
return 0;
}
Reason:- Here, the value will return as specified in the declaration

6)
#include<studio.h>
int main()
{
char ch = 200;

11
printf(“%d”,ch);
return 0 ;
}
Reason :- 56

7)
#include<stdio.h>
int main()
{
float a = 25.345;
int b = 25;
printf(“%lf %d /n”,a,b);
return 0 ;
}
Reason :- Return the int value “25”

8)
#include<stdio.h>
int main()
unsigned a = 25;
long unsigned b = 25;
printf(“%d u%u\n”,a,b);
return 0 ;
}
Reason :- 25 25
Here , the output as 25 25. Becasuse the function u is given.

9)
#include<stdio.h>
int main()
{
Int three[3][3] = { 2,4,3,6,8,2,2,3,1};

12
Printf(“%d /n”,three[1][1]); }
Reason :-
Because , we are painting the position value.given
Is [1][1]. The terminal value at position [1][1].

10)
#include <stdio.h>
int main()
{
Int ival;
Scanf(“%d /n” &ival);
Printf(“integer value = %d\n” ival);
Return 0 ;
}
Reason :
32654
123456
Integer value ; 3 2 6 5 4

11)
#include<stdio.h>
int main()
{
int dd,mm,yy;
printf(“enter data in dd/mm/yy format\n);
scanf(“%d %c %d %c %d %c” &dd,&mm,&yy);
printf(“the date is : %d %d %d \n” dd/mm/yy);
return ();
}
Reason :
The data is 18-12-2003
The given is separated by the condition (ie, dd-mm-yy.
So the year is separated by spaces.

13
12)
#include<stdio.h>
int main()

char text;

printf(text, “%u dlt %2.2f\n%s”,12,3,452,”merry go run”);

printf(“%s \n” , text);

return 0 ;

Reason :- 12 3.45
Merry go round
It satisfies the condition and return the output statement.

13)
#include<stdio.h>
void show(int,float);
int main()
{
void(*s) (int,float);
s = show ;
(*s)(10,3.14);
return 0;
}
void show(int ; float f)
{
printf(“%d %f \n”, I,f);
}

Reason :-
103.140000
The values given are combined together and returned the values by 103.140000.

14
14)
#include<stdio.h>
Void main()
{
int a,b;
scanf(“%d %d”,a,b);
If(a>b):
printf(“the game”);
else:
printf(“you play”);
return 0 ;
}
Reason : this is prime only if when there is only “&” in the scanf statement .

15)
#include<stdio.h>
int main()
{
static int count = 5;
printf(“count = %d” ,count --)
if (count != 0)
{
main();
{
Return 0;
}

Reason :
The count value starts from “5” and the value is decrement and the values are decreased to 0
and return as “54321”.

15
TASK 3
FIND THE OUTPUT OF THE GIVEN CODE SEGMENTS

1)
include<stdio.h>
int main()
{
int i = 2;
#ifdef DEF
i *= i;
#else
printf("\n%d", i);
#endif
return 0;
}
REASON :-
Directly assigning the value of “I” as the l-value to i

2)

include<stdio.h>
#define PRODUCT(x) (x*x)
int main()
{
int i = 3, j, k;
j = PRODUCT(i++);
k = PRODUCT(++i);

printf("\n%d %d", j, k);


return 0;
}

16
Reason :- 12 49
Here ,the values of I increment by I and get multiplied with previous value so the
increment value gets increment upto 7 and multiplies and gives output 49.

3)
include<stdio.h>
#define PI 3.14
#define AREA(x,y,z) PI*x*x+y*z

int main()
{
float a = AREA(1, 5, 8);
float b = AREA(AREA(1, 5, 8), 4, 5);
printf("a = %f\n", a);
printf("b = %f\n", b);
return 0;
}
Reason :-
a = 43.199
b = 195.4595
considering area value for abc we have a = 43.1399 and the resultant with (4,5) and the
output is returned.

4)
#include<stdio.h>
int main()
{
int n[3][3] = {
2, 4, 3,
6, 8, 5,
3, 5, 1
};

17
printf("\n%d %d %d", *n, n[3][3], n[2][2]);
return 0;
}
Reason :-
Returns garbage as 7826292801 because the two values of different columns and rows are
not possible to display.

5)
#include<stdio.h>
int main()
{
int n[3][3] = {
2, 4, 3,
6, 8, 5,
3, 5, 1
};
int i, *ptr;
ptr = n;
for (i = 0; i <= 8; i++)
printf("\n%d", *(ptr + i));
return 0;
}
Reason :-
23831 [ depends upon the values of the row & columns in 4655 their
index values . ]

6)
#include<stdio.h>
int main()
{
int n[3][3] = {
2, 4, 3,
6, 8, 5,

18
3, 5, 1
};
int i, j;
for (i = 0; i <= 2; i++)
for (j = 0; j <= 2; j++)
printf("\n%d %d", n[i][j], *(*(n + i) + j));
return 0;
}
Reason :-
23831 [ depends upon the values of the row & columns in 4655 their
index values . ]

7)
#include<stdio.h>
int main()
{
char c[2] = "A";
printf("\n%c", c[0]);
printf("\n%s", c);
return 0;
}
Reason :-
A
A
Because the condition is given for printing the double character in both lower & upper
cases.

8)
#include<stdio.h>
int main()
{
char s[] = "Get organised! learn C!!";
printf("\n%s", &s[2]);

19
printf("\n%s", s);
printf("\n%s", &s);
printf("\n%c", s[2]);
return 0;
}
Reason :-
Get organised ! learn c !!
Get organised ! learn c !!
Because the repletion is given as 2 times for the problem in the condion as s[2]

9)
#include<stdio.h>
int main()
{
char s[] = "No two viruses work similarly";
int i = 0;
while (s[i] != 0)
{
printf("\n%c %c", s[i], *(s + i));
printf("\n%c %c", i[s], *(i + s));
i++;
}
return 0;
}
Reason :-
The condition is given as specifying the string as printing them two times even with the
spaces].

10)
#include<stdio.h>
int main()
{

20
printf(5 + "Good Morning ");
return 0;
}

Reason :-
Morning
It will start printing from 5th position by considering its index value.

Result:

Thus, the implementing of program is successfully executed and O/P is verified.

21
TASK 4
POINTOUT THE OUTPUT OF LOOPING & CONDITIONING CODE SEGMENTS

1)
#include<stdio.h>
int main()
{
int a=300,b,c;
if(a>=400)
b=300;
c=200;
printf(“%d%d\n”,b,c);
return 0;
}
REASON :
It generate the garbage values and with no error in the code . To generate the output ,
the “&” symbols in printf statement should be removed and then ruined to get the output as
300,200

2)
#include<stdio.h>
int main()
{
int a=500,b,c;
if(a>=400)
b=300;
c=200;
printf(“%d %d\n”,b,c);
return 0;}
Reason : it generate the output as “300,200” with no errors in the code.

22
3) #include<stdio.h>
int main()
{
int x=10,y=20;
if(x==y);
printf(“%d%d\n”,x,y);
return 0;
}
Reason : it generate the as “1020” with no error in the code.
4) #include<stdio.h>
int main()
{
int x=3;
float y=3.0;
if(x==y)
printf(“x and y are equal\n”);
else
printf(“x and y are not equal”);
return 0;
}
Reason :- It returns the output as x and y are equal. Because “x” value is equal to y
value. It compares and satisfies the condition. Then it returns the first printf statement.

5) #include<stdio.h>
int main()
{
int x=3,y,z;
y=x=10;

23
z=x<10;
printf(“x=%dy=%dz=%d\n”,x,y,z);
return 0;
}
Reason :-
X = 10 , y = 10,z=0
6) #include<stdio.h>
int main()
{
int i=65;
char j=’A’;
if(i==j)
printf(“C is wow\n”);
else
printf(“ C is headache\n”);
return 0; }
Reason :-
It will return the output as “c is wow” . because here I,j value is taken ascii value of
a . hence I = 65 ,j = 65. Then satisfies the condition and print the statement “ c is
wow”.

7)
#include<stdio.h>

int main()
{
float a=12.25, b=12.52;
if(a=b)
printf(“a and b are equal\n”);
return 0;
}

24
Reason :-

A and b are equal. In float , it will consider the element before the decimal part.

8)
# include<stdio.h>
int main()
{
int j=10,k=12;
if(k>=j)
{
{
k=j;
j=k;
}
}
return 0;
}
Reason :-
No return value. Because , at initial given condition k>=j it satisfices the condition
and went fro swapping which will return the same value as output.

9)
#include<stdio.h>
int main()
{
if(‘X’<’x’)
printf(“ascii value of X is smaller than that of x\n”);
}
Reason :- ascii values of x is smaller than that of x. because by comparing the ascii
values of the two character.

25
10)
#include<stdio.h>
int main()
{
int x=10;
if(x>=2) then
printf(“%d\n”,x)
return 0;
}
Output :- 10

Result:

Thus, the implementing of program is successfully executed and O/P is verified.

26
TASK 5
BASIC NUMBER THEORY - 1

Instructions:

Write code for the given scenario

1)Two boys, Venky and Sagar, are at war over a girl, Riu. Driven by their feelings, they
decided to confess to Riu. Since both of them were equally dumb, Riu decided that she
would go out with that boy who would successfully find the pattern and thus prove that he is
less dumb.

Read input until end of file.

Given : 0<=N<=10^18

Sample input

1
2
3
10
100

Sample Output

1
2
3
11
121

PROGRAM :
#include <stdio.h>
long int dec2bas(long int n);
int main()
{
long int a;
do{
if(scanf("%ld",&a)!=EOF)
printf("%ld\n",dec2bas(a));
else

27
break;
}
while(1);
return 0;
}
long int dec2bas(long int n)
{
if(n<9)
return n;
return n%9 + 10*dec2bas(n/9);
}

1. 2) Little Panda has a thing for powers and modulus and he likes challenges. His friend Lucy,
however, is impractical and challenges Panda to find both positive and negative powers of a
number modulo a particular number. We all know that A-1mod X refers to the modular inverse
of A modulo X. Since Lucy is impractical, she says that
A-nmodX=(A-1modX)n for n>0. Now she wants Panda to compute ABmodX. She also thinks
that this problem can be very difficult if the constraints aren't given properly. Little Panda is
very confused and leaves the problem to the worthy programmers of the world. Help him in
finding the solution.
Input Format
The first line contains T, the number of test cases.
Then T lines follow, each line containing A,B and X .
Output Format
Output the value of ABmodX .
Constraints
1≤T≤1000
1≤A≤106
-106≤B≤106
1≤X≤106
A and X are coprime to each other.

28
Sample Input
3
123
342
4 -1 5
Sample Output
1
1
4

PROGRAM :

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

long long int gcd(long long int a,long long int bp);
long long int powr(long long int a,long long int b,long long int p);
long long int mul_inv(long long int a,long long int b);

int main() {
long long int k,a,b,x,i,j,ans=0;
scanf("%lld",&k);
while(k>0)
{
scanf("%lld %lld %lld",&a,&b,&x);
if(b>=0)
{
i=a;
}
else
{

29
i=mul_inv(a,x);
b=-b;
}
printf("%lld\n",powr(i,b,x)%x);
k--;
}
return 0;
}

long long int powr(long long int a,long long int b,long long int p)
{
a=a%p;
long long int ans=1;
long long int k=(a*a)%p;
if(b==0)
{
return 1;
}
if(a==0)
{
return 0;
}
if(b%2==0)
ans=powr(k,(b/2),p);
else
ans=(a*powr(k,((b-1)/2),p))%p;
return ans;
}

long long int mul_inv(long long int a,long long int b)


{
long long int b0 = b, t, q;
long long int x0 = 0, x1 = 1;

30
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}

long long int gcd(long long int a,long long int bp)
{
long long int temp,p1=1,p2=0,p0=0,q[3],b=bp,bt=bp,cn=0;
q[2]=q[1]=q[0]=0;
if(a<b)
{
temp=b;
b=a;
a=temp;
}
temp=a%b;
q[2]=(a/b);
a=b;
b=temp;
temp=a%b;
q[1]=(a/b);
a=b;
b=temp;
while(b!=0)
{
temp=a%b;
q[0]=(a/b);
a=b;

31
b=temp;
p0=(p2-(p1*q[2]))%bt;
p0=(p0+bt)%bt;
p2=p1;
p1=p0;
q[2]=q[1];
q[1]=q[0];
cn++;
}
p0=(p2-(p1*q[2]))%bt;
p0=(p0+bt)%bt;
return p0;
}

Result:

Thus, the implementing of program is successfully executed and O/P is verified.

32
TASK 6
BASIC NUMBER THEORY – 2

Instructions:

Write code for the given scenario

1) The Monk wants to teach all its disciples a lesson about patience, since they are
always in a hurry to do something crazy. To teach them this, he gives them a list
of N numbers, which may or may not be distinct. The students are supposed to solve a
simple Mathematical equation based on the array of these N numbers.

• g(x) - GCD (a[ 0 ], a[ 1 ], a[ 2 ]... a[n-1] )

• f(x) - (a[ 0 ] * a[ 1 ] * a[ 2 ]... * a[n-1] )

The value of the MonkQuotient is: 109 + 7.

The equation to be solved is: ( f(x)g(x) ) % MonkQuotient

Input constraints:
The first line of input will contain an integer — N. The next line will contain N integers
denoting the elements of the list.

Output constraints:
Print the required answer of the equation.

Constraints:
1 ≤ N ≤ 50
1 ≤ Ai ≤ 103

Sample input

2
26

33
Sample O/P

144

PROGRAM :

#include <stdio.h>
#include <stdlib.h>
main()
{
int input,gcd,i,*arr;
unsigned long long mul=1,ans=1;
scanf("%d",&input);
arr=(int *)malloc(sizeof(int)*input);
for(i=0;i<input;i++)
scanf("%d",&arr[i]);
gcd=arr[0];
for(i=0;i<input-1;i++)
{
gcd=cal_gcd(gcd,arr[i+1]);
if(gcd==1)
break;
}
for(i=0;i<input;i++)
{
mul=mul*arr[i];
mul%=1000000007;
}
for(i=0;i<gcd;i++)
{
ans=ans*mul;
ans%=1000000007;
}

34
printf("%llu",ans);

}
cal_gcd(int A,int B)
{
int tmp;
tmp=A;
A=B;
B=tmp%B;
if(B==0)
return A;
else
cal_gcd(A,B);
}

2) There are N ants staying at the vertices of the N-regular polygon (one ant at one
vertex). At some moment of time all the ants choose one of the edges their vertex is adjacent
to and start walking along this edge. If two ants meet at some point of the edge they die.
Please find the probability that all the ants will survive.

Input
The first line contains one integer T - number of test cases. The following T lines contain
one integer each - N.

Output
We can consider answer as a fraction P / Q. For each test case output P * Q-1 modulo 109 +
7.

Constraints

• T <= 1000

• 3 <= N <= 1011

35
SAMPLE INPUT

SAMPLE OUTPUT

250000002

PROGRAM

#include<stdio.h>
int main()
{
long long unsigned n;
int t,i,j;
scanf("%d",&t);
for(i=0;i<=t-1;i++)
{long long int result=1,x;
int mod=1000000007;
scanf("%llu",&n);
n=n-1;
x=2;
while(n>0)
{
if(n & 1)
{
result=(result*x)%mod;
}
n=n>>1;
x=(x*x)%mod;
}
int m0=mod;
int y=0,z=1;
while(result>1)
{

36
int q=result/mod;
int t=mod;

mod=result%mod;
result=t;
t=y;
y=z-q*y;
z=t;
}
if(z<0)
{
z+=1000000007;
}
printf("%d\n",z);
}
return 0;
}

Result:

Thus, the implementing of program is successfully executed and O/P is verified.

37
TASK 7

IMPLEMENTATION OF PRIME NUMBER CONCEPTS

Instructions:

Write code for the given scenario

1) Ashu is very fond of Prime numbers and he like challenging his friends by giving
them various problems based on Mathematics and Prime number. One of his friend Harshit
is jealous and challenges him to solve a task. Task is :
Given a prime number X, you need to give the count of all numbers in range 1 to
106 inclusive which have minimum prime factor X.
Help Ashu in solving this task.

Input:
First line consist of numer of test cases T.
Each test case contains a single number X.

Output:
Output for each test case count of all numbers in range 1 to 106 inclusive which have
minimum prime factor X.

Constraints:
1 ≤ T ≤ 105
Prime number X where 2 ≤ X ≤ 106

SAMPLE INPUT

11

38
SAMPLE OUTPUT

500000

20779

PROGRAM :

#include <stdio.h>
int p[1000100]={0};
int a[1000100]={0};
int main()
{
int i,j,x,mc,n;

p[0]=1;
p[1]=1;
for(i=2;i*i<=1000000;i++)
{
mc=0;
if(p[i]!=0)
continue;
p[i]=1;
mc++;
for(j=2;j*i<=1000000;j++)
{
if(!p[i*j])
{
p[j*i]=1;
mc++;
}

39
a[i]=mc;
}
for(i=0;i<=1000000;i++)
{
if(p[i]==0 && a[i]==0)
a[i]=1;
}
scanf("%d",&n);
while(n--)
{
scanf("%d",&x);
printf("%d",a[x]);
printf("\n");
}
return 0;
}

2) Joy is a hacker at hackerclub and he got a new problem on prime numbers.The


problem states that given an integer N find the nearest prime number to N.If multiple answer
is possible then output the smallest one of them.There are T number of test cases.
1<=N<10^6
1<=T<=2*10^6
INPUT:First line of input contains an Integer T denoting the number of test cases.
Next each of the T lines contain one integer N.
OUTPUT:output the nearest prime number possible to N in a new line

SAMPLE INPUT
3
51
12
65

SAMPLE OUTPUT
53

40
11
67

PROGRAM :
#include<stdio.h>
#include<math.h>
void solution();
void sieve();
char isPrime[1000000];
int main(){
sieve();
unsigned long long t;
scanf("%llu",&t);
while(t--){
unsigned long long n;
scanf("%llu",&n);
solution(n);
}
}
void solution(unsigned long long n){
for(unsigned long long i=1;;i++){
if(isPrime[n]==1){
printf("%llu\n",n);
break;
}
else if(isPrime[n-i]==1){
printf("%llu\n",n-i);
break;
}
else if(isPrime[n+i]==1){
printf("%llu\n",n+i);
break;
}

41
}}
void sieve(){
for(unsigned long long i=0;i<sizeof(isPrime);i++)
isPrime[i]=1;
isPrime[0]=0;
isPrime[1]=0;
for(unsigned long long i=2;i<=(unsigned long
long)(lround(sqrt(1000000)));i++){
if(isPrime[i]==1){
unsigned long long mul=2;
for(unsigned long long j=i;j*i<sizeof(isPrime);j++)
isPrime[i*j]=0;
}
}
}

Result:

Thus, the implementing of program is successfully executed and O/P is verified.

42
TASK 8
IMPLEMENTATION OF PRIMALITY TEST

Instructions:

Write code for the given scenario

1) You are required to distribute N bananas among some people according to the
following conditions:

• You can select the number of people that receive bananas.

• Each person should get more than one banana.

• One person cannot receive all the bananas.

• All the N bananas must be distributed.


• Each person can only receive an integral number of bananas.

Write a program to determine whether the bananas can be distributed among the people.

Input format

• First line: T denoting the number of test cases


• Next T lines: N

Output format

For each test case, print Yes or No depending upon the result.

Constraints

2≤T≤105
1≤N≤106

SAMPLE INPUT
2
2
4

43
SAMPLE OUTPUT
No
Yes

PROGRAM :

#include<stdio.h>
#include<stdbool.h>
#include<malloc.h>
#include <math.h>

char* solve (int N ) {


// Your code goes here
for(int i=2;i<=sqrt(N);i++){
if(N%i==0)
return "Yes";
}
return "No";
}

int main() {
int T;
scanf("%d", &T);
for(int t_i=0; t_i<T; t_i++)
{
int N;
scanf("%d", &N);

char* out_ = solve(N);


printf("%s", out_);
printf("\n");
}
}

44
2) Alfi asked Roy to go for shopping with her. Witty Roy came up with a condition. He
said, for each product of MRP (Maximum Retail Price) R, she'll have to pay minimum of all
the prime factors of R and he himself will pay rest of the amount. Without giving it a second
thought Alfi agreed.

Now they bought N number of products. You're to find how much money did Roy had to
pay for each product.

Input:

First line will contain integer N, number of products they bought.

Next N lines each will contain R, MRP of each product.

Output:

Print single integer in a new line, the amount of money Roy had to pay for each product.

Constraints:

2<=N,R<=1000000

Warning: Large I/O. Be careful with certain languages.

SAMPLE INPUT

2
5
10
SAMPLE OUTPUT

0
8

45
PROGRAM :
#include <stdio.h>
#include <stdlib.h>
#define pcx putchar_unlocked
#define gcx getchar_unlocked
typedef long int lint;

inline lint getli () {


lint n =0;
int c = gcx();
while(c<'0' || c>'9') c = gcx();
while(c>='0' && c<='9') {
n = n * 10 + c-'0';
c = gcx();
} return n;
}
inline void putli (lint n, char lc) {
if (0 == n) {
pcx('0'); if(lc) pcx(lc); return;
}
char s[24]; lint rdi =-1;
while (n) {
s[++rdi] = '0' + n % 10;
n /= 10;
}
while (rdi>=0) pcx(s[rdi--]);
if(lc) pcx(lc);
}
#define PLTsz 1000001
lint spFact [PLTsz]; // smallest-prime factor of X

int main () {
for (lint ni=0; ni<PLTsz; ++ni) spFact[ni] =ni;

46
for (lint ni=4; ni<PLTsz; ni+=2) spFact[ni] =2;
for (lint pn=3; pn<PLTsz; pn+=2) {
if (pn == spFact[pn]) {
for (lint ni=pn; ni<=PLTsz; ni+=pn)
if (ni==spFact[ni]) spFact[ni] = pn;
}
}
lint T = getli() +1;
while(--T) {
lint MRP = getli();
if (MRP==spFact[MRP]) putli(0, '\n');
else putli(MRP-spFact[MRP], '\n');
}
return 0;
}

Result:

Thus, the implementing of program is successfully executed and O/P is verified.

47
TASK 9
DATA STRUCTURE ALGORITHMS

Write the procedure, program and output and also mention the time complexity.

1. Linked List

After getting her PhD, Christie has become a celebrity at her university, and her facebook
profile is full of friend requests. Being the nice girl she is, Christie has accepted all the
requests.

Now Kuldeep is jealous of all the attention she is getting from other guys, so he asks her to
delete some of the guys from her friend list.

To avoid a 'scene', Christie decides to remove some friends from her friend list, since she
knows the popularity of each of the friend she has, she uses the following algorithm to
delete a friend.

Algorithm
Delete(Friend):
DeleteFriend=false
for i = 1 to
Friend.length-1
if (Friend[i].popularity <
Friend[i+1].popularity) delete i th friend
DeleteFriend=true break
if(DeleteFriend == false)
delete the last friend

Input:
First line contains T number of test cases. First line of each test case contains N, the number
of friends Christie currently has and K ,the number of friends Christie decides to delete.
Next lines contains popularity of her friends separated by space.

Output:

48
For each test case print N-K numbers which represent popularity of Christie friend's after
deleting K friends.

Constraints
1<=T<=1000
1<=N<=100000
0<=K< N
0<=popularity_of_friend<=100

NOTE:
Order of friends after deleting exactly K friends should be maintained as given in input.

SAMPLE INPUT

3
31
3 100 1
52
19 12 3 4 17
53
23 45 11 77 18

SAMPLE OUTPUT

100 1
19 12 17
77 18

2. Stacks

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ].

Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {)
occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three
types of matched pairs of brackets: [], {},and ().

49
A matching pair of brackets is not balanced if the set of brackets it encloses are not matched.
For example, {[(])} is not balanced because the contents in between { and } are not
balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and
the pair of parentheses encloses a single, unbalanced closing square bracket, ].

By this logic, we say a sequence of brackets is balanced if the following conditions are met:

It contains no unmatched brackets.


The subset of brackets enclosed within the confines of a matched pair of brackets is also a
matched pair of brackets.
Given n strings of brackets, determine whether each sequence of brackets
is balanced. If a string is balanced, return YES. Otherwise, return NO.

INPUT:

The first line contains a single integer n, the number of strings.

Each of the next n lines contains a single string s, a sequence of brackets.

CONSTRAINTS:
1<=n<=10^3
1<=|s|<=10^3, where is the length of the
sequence. All chracters in the sequences ? { {, },
(, ), [, ] }.

OUTPUT:

For each string, return YES or NO.

SAMPLE INPUT

3
{[()]}
{[(])}
{{[[(())]]}}

50
SAMPLE OUTPUT

YES
NO
YES

Explanation

1.The string {[()]} meets both criteria for being a balanced string, so we print YES on a new
line.

2.The string {[(])} is not balanced because the brackets enclosed by the matched pair { and
} are not balanced: [(]).

3.The string {{[[(())]]}} meets both criteria for being a balanced string, so we print YES on
a new line.

3. QUEUE

Your task is to construct a tower in N days by following these conditions:

• Every day you are provided with one disk of distinct size.

• The disk with larger sizes should be placed at the bottom of the tower.

• The disk with smaller sizes should be placed at the top of the tower.

The order in which tower must be constructed is as follows:

• You cannot put a new disk on the top of the tower until all the larger disks that are
given to you get placed.

Print N lines denoting the disk sizes that can be put on the tower on the ith day.

Input format
• First line: N denoting the total number of disks that are given to you in the N
subsequent days
• Second line: N integers in which the ith integers denote the size of the disks that are
given to you on the ith day

Note: All the disk sizes are distinct integers in the range of 1 to N.

51
Output format
Print N lines. In the ith line, print the size of disks that can be placed on the top of the
tower in descending order of the disk sizes.

If on the ith day no disks can be placed, then leave that line empty.

Constraints
1≤N≤106

1≤size of a disk≤N

SAMPLE INPUT

5
45123

SAMPLE OUTPUT
4
321

Explanation
On the first day, the disk of size 4 is given. But you cannot put the disk on the bottom of the
tower as a disk of size 5 is still remaining.

On the second day, the disk of size 5 will be given so now disk of sizes 5 and 4 can be
placed on the tower.

On the third and fourth day, disks cannot be placed on the tower as the disk of 3 needs to be
given yet. Therefore, these lines are empty.

On the fifth day, all the disks of sizes 3, 2, and 1 can be placed on the top of the tower.

4. Binary Search Tree

Given an array A of N integers, classify it as being Good Bad or Average. It is called Good,
if it contains exactly X distinct integers, Bad if it contains less than X distinct integers and
Average if it contains more than X distinct integers.

52
Input format:
First line consists of a single integer T denoting the number of test cases.
First line of each test case consists of two space separated integers denoting N and X.
Second line of each test case consists of N space separated integers denoting the array
elements.

Output format:
Print the required answer for each test case on a new line.

Constraints:
1≤T≤50
1≤X,N≤13000
1≤A[i]≤109

SAMPLE INPUT

4
41
1425
42
42
15
43
5241
44
1245

SAMPLE OUTPUT

Average
Average
Average
Good
Result:
Thus, the implementing of program is successfully executed and O/P is verified.

53
TASK 10
CODE OPTIMIZATION AND MODULARITY IMPLEMENTATION

In 2018, Shourya learned about a serious Android bug: in the burger emoji, the cheese was
directly on top of the lower bun, rather than on the patty itself. Really, who makes a burger
that way? Shourya, vowed to drop everything and address this issue immediately.

To prevent this sort of situation in the future, the ANC (Algorithms and Coding ) Core
team has constructed a mathematical model for understanding burgers. A burger consists of
a stack of K ingredients between two buns, with each ingredient appearing exactly once.
We are interested in the distance-to-bun value of each ingredient. The distance-to-bun
value of an ingredient is the minimum number of other ingredients between the that
ingredient and a bun:

• If K is even, then the distance-to-bun values for the ingredients (starting with the
ingredient at the top of the stack) are: 0,1,...,K/2−1,K/2−1,...,1,0.
• If K is odd, then they are: 0,1,...,((K−1)/2)−1,(K−1)/2,((K−1)/2)−1,...,1,0.

After carrying out a lot of focus group testing (and eating a lot of burgers), we have
determined that the i-th of each of our K ingredients has an optimal distance-to-bun value of
Di. We think our burger emoji users will be happiest if we choose an ordering for our
ingredients that minimizes the error value, which we define as the sum of the squared
differences between each ingredient's optimal and actual distance-to-bun values.

For example, if we have five ingredients A, B, C, D, and E with optimal distance-to-bun


values of 0,2,1,1, and 2, and we place them between the buns in that order, then the error is
(0−0)2+(2−1)2+(1−2)2+(1−1)2+(2−0)2=6. If we instead place them in the order C, E, B, D,
A, then the error is(1−0)2+(2−1)2+(2−2)2+(1−1)2+(0−0)2=2, which turns out to be the
minimum possible error for these ingredients.

Given the list of optimal distance-to-bun values for our ingredients, can you help us
determine the smallest possible error?

Input
The first line of the input gives the number of test cases, T; T test cases follow. Each begins
with one line containing an integer K: the number of ingredients in our burger. Then, there

54
is one more line containing K integers Di, the optimal distance-to-bun values of our
ingredients.

Output

For each test case, output one line containing the smallest possible error, as described above.

Constraints
1 ≤ T≤ 100.
0 ≤ Di≤ floor((K-1)/2), for all i (Each optimal distance-to-bun value is within the range of
attainable distance-to-bun values.)

1≤K≤1000

Problem Setter: Shivam Jadhav

SAMPLE INPUT
3
5
02112
1
0
6
222222

SAMPLE OUTPUT
2
0
10

Explanation
Sample Case 1 is the one illustrated in the problem statement.

In Sample Case 2, there is only one ingredient in the burger; that is not much of a burger,
but our model has to be able to handle this base case! There is no confusion over how to
place the one ingredient, and the error is 0.

55
In Sample Case 3, there are six ingredients, but all of them have an optimal distance-to-bun
of 2.
Any way of placing them is equivalent, and the error is 22 + 12 + 02 + 02 + 12 + 22 = 10.

PROGRAM :
#include<stdio.h>
void merge(int arr[], int l, int m, int r);
void mergeSort(int arr[], int l, int r);
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int k;
scanf("%d",&k);
int a[k],b[k];
if (k%2==1)
{b[(k-1)]=(k-1)/2;
for (int i=0;i<(k-1)/2;i++)
{b[2*i]=i;
b[2*i+1]=i;}}
else
for (int i=0;i<k/2;i++)
{
b[2*i]=i;
b[2*i+1]=i;
}
for (int i=0;i<k;i++)
{scanf("%d",&a[i]);}

mergeSort(a,0,k-1);
int sqsum=0;

56
for (int i=0;i<k;i++)
{
sqsum=sqsum+(a[i]-b[i])*(a[i]-b[i]);
}
printf("%d\n",sqsum);
}
}
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}

57
else
{
arr[k] = R[j];
j++;
}
k++;
}

/* Copy the remaining elements of L[], if there


are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

/* Copy the remaining elements of R[], if there


are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

/* l is for left index and r is right index of the


sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{

58
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}

Result:

Thus, the implementing of program is successfully executed and O/P is verified.

59
TASK 11
PARTIAL CODE COMPLETION
1) Cut the sticks:

You are given N sticks, where each stick has the length of a positive integer. A cut operation
is performed on the sticks such that all of them are reduced by the length of the smallest
stick. Suppose we have six sticks of the following lengths:

544228
Then, in one cut operation we make a cut of length 2 from each of the six sticks. For the
next cut operation four sticks are left (of non-zero length), whose lengths are the following:
3226
The above step is repeated until no sticks are left.

Given the length of N sticks, print the number of sticks that are cut in subsequent cut
operations.

Input Format
The first line contains a single integer NN.
The next line contains NN integers: a0,a1,…,aN−1a0,a1,…,aN−1separated by
space, where airepresents the length of ithstick.

Output Format
For each operation, print the number of sticks that are cut in separate line.

Constraints: 1≤N≤10001≤N≤1000 and 1≤ai≤10001≤ai≤1000


Sample Input
6
544228
Sample Output
6
4
2
1

60
PROGRAM:

#include <stdio.h>
#include <string.h>
#include
<math.h>
#include
<stdlib.h> int
main ( )

{
int n;
scanf("%d",
&n); int a[n-
1];
for(inti=0;i<n
;++i)
{
int stick;
scanf("%d",&stick);
a[i]=stick;
}
int
f=0;
do
{
int count=0,small=99;
f=0;
for(inti=0;i<n;++i)
{
if(a[i]>0&&a[i]<small)
small=a[i];
}
for(inti=0;i<n;++i)

61
{
if(a[i]!=0)
{
a[i]=a[i]-small;

++count;
f=1;
}
}
if(count)
printf("%d\n",count);
}while(f==1);

return 0;
}

2) One Egg

“One Egg” is an egg supply company which supplies eggs to retailers. They have M classes
of eggs. Each class can have N number of eggs (N can be the same or can vary class to class).
They accept order via mail for X eggs. In response, they confirm if they can supply the eggs
with a “Thank you” note and the number of eggs or with a “Sorry” note and the numbers of
eggs they can supply. They also mention the breakdown of eggs by the class they will supply.
The ordered eggs are adjusted against the different classes with the most number of eggs
adjusted first then the balance is adjusted against the second-highest and so on. The
company is a bit superstitious as well. If the number of eggs ordered is greater than or equal
to the total number of eggs in stock then they retain one egg and responds back with the
“Sorry” note with total number of eggs in stock minus one and breakdown of eggs by class.
Note: If the classes have the same number of eggs then class entered first should be selected
to adjust.

62
Input Format:
First line contains two space-separated integers denoting the respective values of M (the
number of classes of eggs) and X, the number of eggs ordered The following M lines contain
an integer each indicating the number of eggs available in each class Output Format:

First line should be, if X is less than total number of Eggs then Print ” Thank you, your
order for X eggs is accepted” Else if X is greater than or equal to total number of Eggs then
print ” ” Sorry, we can only supply (total number of Eggs in stock -1) eggs” T hen M lines
with 3 columns: First column – Number of eggs available in each class Second column –
Eggs allocated against each class for that order Third column – Balance Eggs against each
class

Constraints:

1 ≤ M ≤ 20 N ≥ 1 X ≥ 1

Sample Input 1:
5 150

50

15

80

10 5

Sample Output 1:

Thank you, your order for 150 eggs are accepted

50 50 0

15 15 0

80 80 0

10 5 5

5 0 5

63
Explanation:

Total order of 150 eggs is less than the total number of Eggs 50+15+80+10+5 = 160. Hence
the Thank you message. 150 was first adjusted against Class with the first highest number
of eggs
80. Balance of 150-80 = 70 was adjusted against the second highest class of 50. Balance of
70-50 = 20 then adjusted against 15. Balance of 20-15 = 5 then adjusted against 10 leaving
behind 5

eggs in that class.

Sample Input 2:

4 250

80

50

70

20

Sample Output 2:

Sorry, we can only supply 219 eggs

80 80 0

50 50 0

70 70
0 20 19
1
Explanation:

The total order of 250 eggs was greater than the total number of eggs 80+50+70+20 = 220.
Hence the sorry message. 250 was first adjusted against Class with the first highest number

64
of eggs 80. Balance of 250-80 = 170 was adjusted against the second highest class of 70.
Balance of 170-70 = 100 was then adjusted against 50. Balance of 100-50 = 50 then adjusted
against 20.
Since Balance is greater than the last class of egg all but one egg is left in that last class.

Solution:

#include
<stdio.h> int
main() {
int m,x,i,a[1000],sum=0,s;
scanf("%d %d",&m,&x);
for(i=0;i<m;i++)

{
scanf("%d",&a[i]);
sum=sum+a[i];
}
if(su
m>x)
printf("Thank you, your order for %d eggs are
accepted\n",x); else {
printf("Sorry, we can only supply %d eggs\n",sum-1);
x=sum-1;
}
for(i=0;i<m;i++)
{
if(x>=a[i])
{
printf("%d\t%d\t%d\n",a[i],a[i],0);
x=x-a[i];
}
else if(x<a[i])

65
{
s=a[i]-
x;

printf("%d\t%d\t%d\n",a[i],x,s);
x=0;
}

else if(x==0)
printf("%d\t%d\t%d\n",a[i],0,a[i]);

}
ret
ur
n
0;
}

3) Bride Hunting
Sam is an eligible bachelor. He decides to settle down in life and start a family. He goes
bride hunting. He wants to marry a girl who has at least one of the 8 qualities mentioned
below:- 1) The girl should be rich.

2) The girl should be an Engineer/Doctor.

3) The girl should be beautiful.


4) The girl should be of height 5.3″.

5) The girl should be working in an MNC.

6) The girl should be an extrovert.

7) The girl should not have spectacles.

8) The girl should be kind and honest.

He is in search of a bride who has some or all of the 8 qualities mentioned above. On bride
hunting, he may find more than one contenders to be his wife.

66
In that case, he wants to choose a girl whose house is closest to his house. Find a bride for
Sam who has maximum qualities. If in case, there are more than one contenders who are at
equal distance from Sam’’s house; then print ““Polygamy not allowed””.
In case there is no suitable girl who fits the criteria then print “”No suitable girl found””

Given a Matrix N*M, Sam’s house is at (1, 1). It is denoted by 1. In the same matrix, the
location of a marriageable Girl is also denoted by 1. Hence 1 at location (1, 1) should not be
considered as the location of a marriageable Girl’s location.
The qualities of that girl, as per Sam’’s criteria, have to be decoded from the number of non-
zero neighbors (max 8-way) she has. Similar to the condition above, 1 at location (1, 1)
should not be considered as the quality of a Girl. See Example section to get a better
understanding.
Find Sam, a suitable Bride and print the row and column of the bride, and find out the
number of qualities that the Bride possesses.

NOTE: Distance is calculated in number of hops in any direction i.e. (Left, Right, Up, Down
and Diagonal)

Constraints: 2 <= N,M <= 10^2

Input Format:

• First Line contains the row (N) and column (M) of the houses.
• Next N lines contain the data about girls and their qualities.
Output Format:

It will contain the row and column of the bride, and the number of qualities that Bride
possess separated by a colon (i.e. :).

Sample Input 1:
29
101101111
000101001
Sample Output
1: 1:7:3

67
Explanation:
The girl and qualities are present at (1,3),(1,4),(1,6),(1,7),(1,8),(1,9),(2,4),(2,6),(2,9).
The girl present at (1,3) has 2 qualities (i.e. (1,4)and (2,4)).
The girl present at (1,4) has 2 qualities.
The Bride present at (1,6) has 2 qualities.
The Bride present at (1,7) has 3 qualities.
The Bride present at (1,8) has 3 qualities.
The Bride present at (1,9) has 2 qualities.
The Bride present at (2,4) has 2 qualities.
The Bride present at (2,6) has 2 qualities.
The Bride present at (2,9) has 2 qualities.
As we see, there are two contenders who have maximum qualities, one is at (1,7) and
another at (1,8).
The girl who is closest to Sam’s house is at (1,7). Hence, she is the bride.
Hence, the output will be 1:7:3.
Sample Input 2:
66
100000
000000
001110
001110
001110
000000
Sample Output
2: 4:4:8
Explanation:
The bride and qualities are present at
(3,3),(3,4),(3,5),(4,3),(4,4),(4,5),(5,3),(5,4),(5,5) The Bride present at (3,3) has 3
qualities (i.e. (3,4),(4,3) and (4,4)).
The Bride present at (3,4) has 5 qualities.
The Bride present at (3,5) has 3 qualities.
The Bride present at (4,3) has 5 qualities.
The Bride present at (4,4) has 8 qualities.

68
The Bride present at (4,5) has 5 qualities.
The Bride present at (5,3) has 3 qualities.
The Bride present at (5,4) has 5 qualities.
The Bride present at (5,5) has 3 qualities.
As we see, the girl present in (4,4) has the maximum number of Qualities. Hence, she is the
bride.
Hence, the output will be 4:4:8.

PROGRAM :

#include<st
dio.h> int
main() {
int
n,m,i,g[50][50],j,p,q,max=0,cnt=0,k=1,c=0,u=1,x[30],y[30],t1,min=0
, sc[50],e,f,ct=0,a[50],count=0,t2=0,t=0; scanf(“%d
%d”,&n,&m);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
scanf(“%d”,&g[i][j]);
}
}
g[1][1]=
0;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
cnt=0;

69
if(g[i][j]==1
)
{
t++;
for(p=i-1;p<=i+1;p++)
{
for(q=j-1;q<=j+1;q++)
{

if(g[p][q]==1)
{
cnt++;
}
}

}cnt=cnt-1;
a[k]=cnt;
k++;
}
}
}
for(k=1;k<=t;k++)
{
if(a[k]>max)
max=a[k];
}
if(max==0)
{
printf(“No suitable girl found”);
return 0;
}
for(k=1;k<=t;k++)

70
{
if(a[k]==max)
c++;
}
for(k=1;k<=t;k++)
{
t2=0;
if(a[k]==max)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(g[i][j]==1)
t2++;
if(t2==k)
{
x[u]=i;
y[u]=j;
u++;
}
}
}

}
}
t1=u-1;
if(c==1)

printf(“%d:%d:%d”,x[1],y[1],max);
else
{
for(u=1;u<=t1;u++)

71
{
sc[u]=sqrt(((x[u]-1) * (x[u]-1)) + ((y[u]-1)*(y[u]-1)));;
}
min=sc[1];
for(u=1;u<=t1;u++)
{
if(sc[u]<min)
min=sc[u];
}
for(u=1;u<=t1;u++)
{
if(sc[u]==min)
count++;
}
if(count>1)
printf(“Polygamy not allowed”);
if(count==1)
{
for(u=1;u<=t1;u++)
{
if(sc[u]==min)
printf(“%d:%d:%d”,x[u],y[u],max);
}
}
}
return
0; }

Result:

Thus, the implementing of program is successfully executed and O/P is verified.

72
TASK 12
IMPLEMENT COMMON STYLE TECHNIQUE

1. Ramesh Salary:

2. The Distance :

73
3. Marks:

4. Leap Year:

5. Two numbers are input through the keyboard into two locations C and D.
Write a program to interchange the contents of C and D.

#include<stdio.h>
#include<conio.h>
main()

74
{
int c,d,e;
clrscr();
printf(“\n Enter the number at location C:”);
scanf(“%d”, &c);
printf(“\n Enter the number at location D:”);
scanf(“%d”, &d);
e=c; c=d; d=e;
printf(“\n New Number at location C=%d”,c);
printf(“\n New Number at location D=%d”,d);
printf(“\n\n\n\n\n Press any key to exit….”);
getch();
}

6. Write a recursive function to obtain the sum of first 25 natural numbers.

#include <stdio.h>
int addNumbers(int n);
int main() {
int num=20;
printf(“Sum = %d”, addNumbers(num));
return 0; }
int addNumbers(int n) {
if (n != 0)
return n + addNumbers(n – 1);
else
return n;
}

Result:

Thus, the implementing of basic concepts of tools successfully executed.

75
TASK 13
STUDY ON BASIC CONCEPTS OF COMPILE, LINK AND OS

Aim:

To understand and to implement basic concepts behind compiling linking hardware tools
compilation and execution.

Software tools: (All programming tools)

Programming tool 1

Turbo C ++

Steps to install

Step 1: First of all download Turbo C++ from the internet

Step 2: If any previous Turbo C++version already installed in your computer then first
uninstall that

Step 3: Extract downloader Turbo C++ file

Step 4: Run setup.exe file

Step 5: Double click on Turbo shortcut link on desktop

Step 6: If you want to run Turbo on full screen simply click on button Run Turbo

Step 7: If you want full screen mode unclick the full screen mode checkbox and click
on button start Turbo

Steps to Compile and execute

Step 1: Start Turbo C plus plus from start all programs or from desktop

Step 2: Select file new from Menu

Step 3: Type the program

Step 4: Save the program

Step 5: Compile and execute the program

Step 6: Use Alt + f5 to view the output


Programming tool 2

76
NetBeans

Steps to install

Step 1: To use NetBeans for Java programming you need to first install Java
development kit

Step 2: Download from netbeans.org

Step 3: Run the downloaded installer

Steps to compile and execute

Step 1: Start NetBeans from start all programs NetBeans

Step 2: Select file new project from the file menu select project category as C++ and
project type as C++ application from the dialogue that pop up click next button

Step 3: Type a suitable project name in project name textbox click finish

Step 4: Type the program and save it using Control + S

Programming tools 3

Visual Studio Express

Steps to install

Step 1: Visual Studio can be downloaded from the following link

Step 2: You can select Visual Studio 2019 Community Edition

Step 3: Visual Studio 2019 professional edition

Step 4: Click on the downloaded exe file

Step 5: In the next screen click continue

Step 6: Visual Studio will start download in the initial files download speed will vary as
per your internet connection

Step 7: In the next screen click install

77
Step 8: In the next screen select .net desktop development

Step 9: Click install

Step 10: Download the relevant files based on the selection in step 6

Step 11: Once download is done you will be asked to reboot PC

Step 12: Post reboot open Visual Studio IDE

Step 13: Select a team of your choice

Step 14: Click start Visual Studio

Step 15: In Visual Studio ID you can navigate to file menu to create new C# applications

Steps to compile and execute

Step 1: Start Visual Studio Express from start all programs

Step 2: Select file new project from file menu select project type a visual C++ when is
console application from the dialogue that pops up . Type a suitable project name

Step 3: Type the program and save it using Cntrl+S

Programming tools 4

Eclipse

Steps to install

Step 1: Download eclipse installer from

Step 2: Start the eclipse installer executable

Step 3: Select the package to install

Step 4: Select your installation folder

Step 5: Select the install button to begin the installation

Step 6: Launch eclipse

78
Steps to compile and execute

Step 1: Launch eclipse

Step 2: Start eclipse by clicking on shortcut on desktop

Step 3: Choose an appropriate directory for your workspace

Step 4: If the welcome screen pops up close it by button

Step 5: Create a new C++ project

Step 6: Write a program and save it using control+s

Step 7: Compile and execute using the button in the options

Programming tools 5

Android studio

Steps to install

Step 1: Download and .exe file from official website

Step 2: If you download a Zip file unpack the zip copy Android studio folder into your
program files folder

Step 3: Follow the setup Wizard in the Android studio and install any SDK packages
that recommends

Step 4: Launch Android studio

Steps to compile and execute

Step 1: Creating a new project with support for native code is to creating and other
Studio but there is an additional step

Step 2: In the choose your project section of the wizard select the native C++ project
type

Step 3: Click next

79
Step 4: Complete all other fields in the next section of the wizard.

Step 5: Click next in the customise C++ support section of the wizard you can
customise your project.

Step 6: Click finish after Android studio finish Creating your new project open the
project pad from left side of the IDE and select the Android view.

Result:

Thus, the implementing of basic concepts of tools successfully executed.

80
TASK 14
PRACTICE PROBLEMS FOR CODE IMPLEMENTATION

Aim: To Practice problems for coding preparation

PRACTICE PROBLEMS

Pseudocode 1:

Declare an integer variable called n // n is the numberlimit


Declare an integer variable sum // f is the sum
Declare an integer variable f1 // f1 is temporary storage
Declare an integer variable f2 // f2 is temporary storage
set loopcounter to 2 // assigning the variables declared above to values
set sum to 0
set f1 and f2 to 1 set n to 50

Code :

int main( )
{ int n, k, f1, f2, f;
if ( n < 2 ) return n;
else { f1 = f2 = 1;
for(k=2;k<n;k++)
{ f = f1 + f2; f2 = f1; f1 = f; }
return f;
}

Pseudocode 2:

Declare an integer variable arr


Declare an integer variable loopcounter
Set arr to size 10
for loopcounter = 0 to (size of arr)-1
arr[loopcounter] = random()
loopcounter = loopcounter + 1
print arr[loopcounter] endfor

Code :

int arr; // Declaring a variable called arr


// which will be later used to create an array
arr = new int[10]; // Initialising the array
for(int i = 0; i < arr.size(); i++) // Loop
{ arr[i] = random (); // insert random numbers into the array
print arr[i]; }

81
Pseudocode 3:

If student's grade is greater than or equal to 60

Print "passed"
else
Print "failed"

Pseudocode 4:

Set total to zero

Set grade counter to one

While grade counter is less than or equal to ten

Input the next grade


Add the grade into the total

Set the class average to the total divided by ten

Print the class average.

Pseudocode 5:

Initialize total to zero

Initialize counter to zero

Input the first grade

while the user has not as yet entered the sentinel

add this grade into the running total


add one to the grade counter
input the next grade (possibly the sentinel)

if the counter is not equal to zero

set the average to the total divided by the counter


print the average

else

print 'no grades were entered'

82
Pseudocode 6:

initialize passes to zero

initialize failures to zero

initialize student to one

while student counter is less than or equal to ten

input the next exam result


if the student passed
add one to passes

else

add one to failures

add one to student counter

print the number of passes

print the number of failures

if eight or more students passed

print "raise tuition"

Result:

Thus, the practice problem for coding preparation for coding preparation is
successfully practiced.

83

You might also like