0% found this document useful (0 votes)
65 views20 pages

20CS241 - Programming Foundations

Uploaded by

goutham.2402041
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views20 pages

20CS241 - Programming Foundations

Uploaded by

goutham.2402041
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

SRI RAMAKRISHNA ENGINEERING COLLEGE, COIMBATORE

(Autonomous Institution, Reaccredited by NAAC with 8A+9 GRADE Approved by AICTE and Permanently affiliated to Anna University, Chennai)

AUTONOMOUS EXAMINATIONS – MAY 2023


B.E / B.TECH – UG (Revised) REGULATION – 2020

20CS241 – PROGRAMMING FOUNDATIONS


(Answer Key)

PART A
1. c) 11110100
2. b) -127 and 127
3. b) Automatic and static variables
4. b) NULL
5. b) II only

PART B
6. Exchange of two variables without temporary variable:
#include<stdio.h>
int main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a+b;//a=30 (10+20)
b=a-b;//b=10 (30-20)
a=a-b;//a=20 (30-10)
printf("\nAfter swap a=%d b=%d",a,b);
return 0;
}
7. Big endian and Little Endian difference
Big-endian is an order in which the "big end" (most significant value in the sequence) is
stored first, at the lowest storage address. Little-endian is an order in which the "little end"
(least significant value in the sequence) is stored first.
8. Break and continue statements
Break statement stops the entire process of the loop. Continue statement only stops the
current iteration of the loop. Break also terminates the remaining iterations. Continue
doesn't terminate the next iterations; it resumes with the successive iterations.
9. Largest of two numbers
#include<stdio.h>
int main(void)
{
int a,b,max;
printf("Enter values for a and b : ");
scanf("%d%d", &a, &b);
max = a>b ? a : b;
printf("Larger of %d and %d is %d \n", a, b, max);
return 0;
}
10. Ans: Base address: 101Bh
Part C
Compulsory
11. i) Pseudo code to compute a factorial of a given number.
INPUT number
SET factorial := 1, i := 1
WHILE i <= number DO
COMPUTE factorial := factorial * i
INCREASE i by 1
END LOOP
PRINT factorial
ii) Flow Chart to find the largest of 3 numbers

12. Decimal number 768 to Binary and Hexadecimal representations.


In Binary:
768/2 = 384, remainder is 0
384/2 = 192, remainder is 0
192/2 = 96, remainder is 0
96/2 = 48, remainder is 0
48/2 = 24, remainder is 0
24/2 = 12, remainder is 0
12/2 = 6, remainder is 0
6/2 = 3, remainder is 0
3/2 = 1, remainder is 1
1/2 = 0, remainder is 1

Step 2: Read from the bottom (MSB) to top (LSB) as 1100000000.

So, 1100000000 is the binary equivalent of decimal number 768 (Answer).

In Hexadecimal

(768)10 = (300)16
Step by step solution
Step 1: Divide (768)10 successively by 16 until the quotient is 0:
768/16 = 48, remainder is 0
48/16 = 3, remainder is 0
3/16 = 0, remainder is 3
Step 2: Read from the bottom (MSB) to top (LSB) as 300. So, 300 is the
hexadecimal equivalent of decimal number 768 (Answer).

13. Logical Operators


Logical operators in C are used to combine multiple conditions/constraints. Logical
Operators returns either 0 or 1, it depends on the expression result true or false. In C
programming for decision-making, we use logical operators. We have 3 major logical
operators in the C language:

 Logical AND (&&)


 Logical OR (||)
 Logical NOT (!)
 Logical XOR(^)
Types of Logical Operators

1. Logical AND Operator


If both operands are non-zero then the condition becomes true. Otherwise, the result
has a value of 0. The return type of the result is int. Below is the truth table for the
logical AND operator.
2. Logical OR Operator
The condition becomes true if any one of them is non-zero. Otherwise, it returns false
i.e, 0 as the value.
3. Logical NOT Operator
If the condition is true then the logical NOT operator will make it false and vice-versa.
4. XOR (^) Logical Operator:
If both bits are the same then it will return false otherwise true.

Bitwise Operators:
The following 6 operators are bitwise operators (also known as bit operators as they work
at the bit-level). They are used to perform bitwise operations in C.

The & (bitwise AND) in C or C++ takes two numbers as operands and does AND on every
bit of two numbers. The result of AND is 1 only if both bits are 1.

The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit
of two numbers. The result of OR is 1 if any of the two bits is 1.

The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every
bit of two numbers. The result of XOR is 1 if the two bits are different.

The << (left shift) in C or C++ takes two numbers, the left shifts the bits of the first
operand, and the second operand decides the number of places to shift.

The >> (right shift) in C or C++ takes two numbers, right shifts the bits of the first operand,
and the second operand decides the number of places to shift.
The ~ (bitwise NOT) in C or C++ takes one number and inverts all bits of it.
ii) Difference between while loop and Do while loop

SR.NO while loop do-while loop

1. While the loop is an entry control loop The do-while loop is an exit control
because firstly, the condition is checked, loop because in this, first of all, the
then the loop's body is executed. body of the loop is executed then the
condition is checked true or false.
2. The statement of while loop may not be The statement of the do-while loop
executed at all. must be executed at least once.

3. The while loop terminates when the As long as the condition is true, the
condition becomes false. compiler keeps executing the loop in
the do-while loop.

4. In a while loop, the test condition In a do-while loop, the variable of test
variable must be initialized first to check condition Initialized in the loop also.
the test condition in the loop.

5. In a while loop, at the end of the In this, at the end of the condition, there
condition, there is no semicolon. is a semicolon.
Syntax: Syntax:
while (condition) while (condition);

6. While loop is not used for creating menu- It is mostly used for creating menu-
driven programs. driven programs because at least one
time; the loop is executed whether the
condition is true or false.

7. In a while loop, the number of executions In a do-while loop, irrespective of the


depends on the condition defined in the condition mentioned, a minimum of 1
while block. execution occurs.

8. Syntax of while loop: Syntax of do-while loop:


while (condition) do
{ {
Block of statements; statements;
} }
Statement-x; while (condition);
Statement-x;
9. Program of while loop: Program of do-while loop:
Program of while loop: #include
#include #include
#include Void main()
Void main() {
{ int i;
int i; clrscr();
clrscr(); i = 1;
i = 1; do
while(i<=10) {
{ printf("hello");
printf("hello"); i = i + 1;
i = i + 1; }
} while(i<=10);
getch(); getch();
} }
10. Flowchart of while loop: Flowchart of do-while loop:

14. i) Global layout of memory mapping


A typical memory representation of a C program consists of the following:
1. Text segment (i.e. instructions)

A text segment, also known as a code segment or simply as text, is one of the sections
of a program in an object file or in memory, which contains executable instructions.

As a memory region, a text segment may be placed below the heap or stack in order
to prevent heaps and stack overflows from overwriting it.
2. Initialized data segment

Initialized data segment, usually called simply the Data Segment. A data segment is a
portion of the virtual address space of a program, which contains the global variables
and static variables that are initialized by the programmer.

Note that, the data segment is not read-only, since the values of the variables can be
altered at run time.
3. Uninitialized data segment (bss)
Uninitialized data segment often called the <bss= segment, named after an ancient
assembler operator that stood for <block started by symbol.= Data in this segment is
initialized by the kernel to arithmetic 0 before the program starts executing
uninitialized data starts at the end of the data segment and contains all global
variables and static variables that are initialized to zero or do not have explicit
initialization in source code.
4. Heap
Heap is the segment where dynamic memory allocation usually takes place.

The heap area begins at the end of the BSS segment and grows to larger addresses
from there. The Heap area is managed by malloc, realloc, and free, which may use the
brk and sbrk system calls to adjust its size (note that the use of brk/sbrk and a single
<heap area= is not required to fulfill the contract of malloc/realloc/free; they may also
be implemented using mmap to reserve potentially non-contiguous regions of virtual
memory into the process’ virtual address space).
5. Stack

The stack area traditionally adjoined the heap area and grew in the opposite direction;
when the stack pointer met the heap pointer, free memory was exhausted. (With
modern large address spaces and virtual memory techniques they may be placed
almost anywhere, but they still typically grow in opposite directions.)

ii) Storage Classifiers


C Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility, and lifetime which help us to trace the existence of
a particular variable during the runtime of a program.
C language uses 4 storage classes, namely
1. auto
This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto
variables can be only accessed within the block/function they have been declared and not
outside them (which defines their scope). Of course, these can be accessed within nested
blocks within the parent block/function in which the auto variable was declared.
2. extern
Extern storage class simply tells us that the variable is defined elsewhere and not within
the same block where it is used. Basically, the value is assigned to it in a different block
and this can be overwritten/changed in a different block as well. So an extern variable is
nothing but a global variable initialized with a legal value where it is declared in order to
be used elsewhere. It can be accessed within any function/block.
3. static
This storage class is used to declare static variables which are popularly used while
writing programs in C language. Static variables have the property of preserving their
value even after they are out of their scope! Hence, static variables preserve the value of
their last use in their scope. So we can say that they are initialized only once and exist till
the termination of the program. Thus, no new memory is allocated because they are not
re-declared.
4. register
This storage class declares register variables that have the same functionality as that of
the auto variables. The only difference is that the compiler tries to store these variables in
the register of the microprocessor if a free register is available. This makes the use of
register variables to be much faster than that of the variables stored in the memory during
the runtime of the program.
Syntax
To specify the storage class for a variable, the following syntax is to be followed:
storage_class var_data_type var_name;
15. i) Difference between arrays and structures.

ARRAY STRUCTURE
Structure refers to a collection
Array refers to a collection consisting of
consisting of elements of
elements of homogeneous data type.
heterogeneous data type.
Array uses subscripts or <[ ]= (square Structure uses <.= (Dot operator) for
bracket) for element access element access
Array is pointer as it points to the first
Structure is not a pointer
element of the collection.
ARRAY STRUCTURE
Instantiation of Array objects is not Instantiation of Structure objects is
possible. possible.
Array size is fixed and is basically the Structure size is not fixed as each
number of elements multiplied by the element of Structure can be of
size of an element. different type and size.
Bit field is not possible in an Array. Bit field is possible in an Structure.
Array declaration is done simply using [] Structure declaration is done with the
and not any keyword. help of <struct= keyword.
Arrays is a non-primitive datatype Structure is a user-defined datatype.
Array traversal and searching is easy and Structure traversal and searching is
fast. complex and slow.
struct sruct_name{ data_type1 ele1;
data_type array_name[size];
data_type2 ele2; };
Structure elements may or may not be
Array elements are stored in contiguous
stored in a contiguous memory
memory locations.
location.
Array elements are accessed by their Structure elements are accessed by
index number using subscripts. their names using dot operator.

ii) C Code to find the smallest element in a set using pointers.


# include < stdio.h >
int main( )
{
int a[20],n,i,sml ;
int *ptr ;
printf(" How many Numner you want to enter: ") ;
scanf("%d ",& n) ;
printf("\n Enter the number : \n") ;

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


{
scanf("%d ",& a[i]) ;
ptr++ ;
}
ptr = & a[0] ;
printf(" \n Number you enter :\n ") ;
for (i = 0; i < n ; i++ )
{
printf("\t %d ",( *ptr )) ;
}
ptr = & a[0] ;
sml = a[0] ;
for (i = 0; i < n ; i++ )
{
if ( sml > ( *ptr ))
sml = *ptr ;
ptr++ ;
}
printf("\n Smallaest element is : %d",sml) ;
return ( 0 );
}
OUTPUT:
16. i) C Code to find the length of the string using pointers.

Output:

ii) Value and reference parameters in functions


Call by value in C
o In call by value method, the value of the actual parameters is copied into the formal
parameters. In other words, we can say that the value of the variable is used in the
function call in the call by value method.

o In call by value method, we can not modify the value of the actual parameter by the
formal parameter.

o In call by value, different memory is allocated for actual and formal parameters since the
value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.

#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the valu
e of a and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual pa
rameters do not change by changing the formal parameters in call by value, a = 10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters
, a = 20, b = 10
}

Call by reference in C
In call by reference, the address of the variable is passed into the function call as the actual
parameter.

The value of the actual parameters can be modified by changing the formal parameters since the
address of the actual parameters is passed.

In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the address of
the actual parameters, and the modified value gets stored at the same address.

Example:
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the valu
e of a and b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual p
arameters do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
// Formal parameters, a = 20, b = 10
}
17. i) Array and Pointers

Relationship Between Arrays and Pointers


An array is a block of sequential data. Let's write a program to print addresses of array
elements.
#include <stdio.h>
int main() {
int x[4];
int i;

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


printf("&x[%d] = %p\n", i, &x[i]);
}

printf("Address of array x: %p", x);


return 0;
}
Output
&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448

There is a difference of 4 bytes between two consecutive elements of array x. It is


because the size of int is 4 bytes (on our compiler).

Notice that, the address of &x[0] and x is the same. It's because the variable
name x points to the first element of the array.

Relation between Arrays and Pointers


From the above example, it is clear that &x[0] is equivalent to x. And, x[0] is equivalent
to *x.
Similarly,
 &x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).
 &x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
 ...
 Basically, &x[i] is equivalent to x+i and x[i] is equivalent to *(x+i).

Example 1: Pointers and Arrays


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

int i, x[6], sum = 0;

printf("Enter 6 numbers: ");

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


// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);

// Equivalent to sum += x[i]


sum += *(x+i);
}

printf("Sum = %d", sum);

return 0;
}
When you run the program, the output will be:
Enter 6 numbers: 2
3
4
4
12
4
Sum = 29

ii) Command Line arguments


The most important function of C is the main() function. It is mostly defined with a return
type of int and without parameters as shown below:

int main() {
...
}
It can also given command-line arguments in C. Command-line arguments are the values given
after the name of the program in the command-line shell of Operating Systems. Command-line
arguments are handled by the main() function of a C program.

To pass command-line arguments, we typically define main() with two arguments: the first
argument is the number of command-line arguments and the second is a list of command-line
arguments.
Syntax:
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }

Here,
 argc (ARGument Count) is an integer variable that stores the number of command-line
arguments passed by the user including the name of the program. So if we pass a value to
a program, the value of argc would be 2 (one for argument and one for program name)
 The value of argc should be non-negative.
 argv (ARGument Vector) is an array of character pointers listing all the arguments.

 If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.

 argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.
For better understanding run this code on your Linux machine.

Example:
 In C

// program named mainreturn.c


#include <stdio.h>
// defining main with arguments
int main(int argc, char* argv[])
{
printf("You have entered %d arguments:\n", argc);
for (int i = 0; i < argc; i++) {
printf("%s\n", argv[i]);
}
return 0;
}

Terminal Input:
$ g++ mainreturn.cpp -o main
$ ./main geeks for geeks

Output:
You have entered 4 arguments:
./main
geeks
for
geeks

Note : Other platform-dependent formats are also allowed by the C and C++ standards; for
example, Unix (though not POSIX.1) and Microsoft Visual C++ have a third argument giving
the program’s environment, otherwise accessible through getenv in stdlib.h. Refer C program to
print environment variables for details.

Properties of Command Line Arguments:


1. They are passed to the main() function.
2. They are parameters/arguments supplied to the program when it is invoked.

3. They are used to control programs from outside instead of hard coding those values
inside the code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.

6. argv[1] points to the first command line argument and argv[argc-1] points to the last
argument.

Note: You pass all the command line arguments separated by a space, but if the argument itself
has a space, then you can pass such arguments by putting them inside double quotes <= or single
quotes =.

Example:
In C program:

// C program to illustrate
// command line arguments
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("Program name is: %s", argv[0]);
if (argc == 1)
printf("\nNo Extra Command Line Argument Passed "
"Other Than Program Name");
if (argc >= 2) {
printf("\nNumber Of Arguments Passed: %d", argc);
printf("\n----Following Are The Command Line "
"Arguments Passed----");
for (int i = 0; i < argc; i++)
printf("\nargv[%d]: %s", i, argv[i]);
}
return 0;
}

Output in different scenarios:


1. Without argument: When the above code is compiled and executed without passing any
argument, it produces the following output.

Terminal Input:
$ ./a.out

Output:
Program Name Is: ./a.out
No Extra Command Line Argument Passed Other Than Program Name

2. Three arguments: When the above code is compiled and executed with three arguments, it
produces the following output.

Terminal Input:
$ ./a.out First Second Third

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

3. Single Argument: When the above code is compiled and executed with a single argument
separated by space but inside double quotes, it produces the following output.

Terminal Input:
$ ./a.out "First Second Third"

Output:
Program Name Is: ./a.out
Number Of Arguments Passed: 2
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: First Second Third

4. A single argument in quotes separated by space: When the above code is compiled and
executed with a single argument separated by space but inside single quotes, it produces the
following output.

Terminal Input:
$ ./a.out 'First Second Third'

You might also like