Nothing Special   »   [go: up one dir, main page]

Copa Final Exam Paper

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 21

SAMARTH ITI , Belhe

COPA Final Exam Paper with Expert Answer

Que 1 State and explain any four bitwise operators in c Programming.

C language supports the following bitwise operators.


| – Bitwise OR
& – Bitwise AND
~ – One’s complement
^ – Bitwise XOR
<< – left shift
>> – right shift

Bitwise OR – |
Bitwise OR operator | takes 2 bit patterns, and perform OR operations on each pair of
corresponding bits. The following example will explain it.
1010
1100
--------
OR 1110
--------

Bitwise AND – &


Bitwise AND operator &, takes 2 bit patterns, and perform AND operations with it.
1010
1100
-------
AND 1000
-------

One’s Complement operator – ~


One’s complement operator (Bitwise NOT) is used to convert each “1-bit to 0-bit” and “0-bit
to 1-bit”, in the given binary pattern. It is a unary operator i.e. it takes only one operand.
1001
NOT
-------
0110
-------

Bitwise XOR – ^
Bitwise XOR ^, takes 2 bit patterns and perform XOR operation with it.
0101
0110
------
XOR 0011
------

Left shift Operator – <<


The left shift operator will shift the bits towards left for the given number of times.
int a=2<<1;
Let’s take the binary representation of 2 assuming int is 1 byte for simplicity.
Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 0 1 0

Right shift Operator – >>


The right shift operator will shift the bits towards right for the given number of times.
int a=8>>1;
Let’s take the binary representation of 8 assuming int is 1 byte for simplicity.
Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 1 0 0 0

Que 2 Explain Condition Operator With Syntax and Example

A traditional if-else construct in C,Java and JavaScript is written:


if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
A GNU extension to C allows omitting the second operand, and using implicitly the first
operand as the second also:
a = x ? : y;
The expression is equivalent to
a = x ? x : y;
except that if x is an expression, it is evaluated only once. The difference is significant if
evaluating the expression has side effects.
C# and Perl provide similar functionality with their null coalescing operator.
a = x ?? y;
(Unlike the above usage of "x ?: y", ?? will only test if x is non-null, as opposed to non-false.)

Que 3 Explain Pointer variable . What are the advantage of using pointers?

Pointer is a user defined data type which creates special types of variables which can hold the
address of primitive data type likechar, int, float, double or user defined data type like
function, pointer etc. or derived data type like array, structure, union,enum.
Examples:

int *ptr;
int (*ptr)();
int (*ptr)[2];

In c programming every variable keeps two type of value.


1. Contain of variable or value of variable.
2. Address of variable where it has stored in the memory.
(1) Meaning of following simple pointer declaration and definition:
int a=5;
int * ptr;
ptr=&a;

The basic advantages of using pointer are that, 


• It allows the use of dynamic memory allocation. 
• A pointer is a variable containing the address of a different variable of a type. 
• The concept of pointer is often scared because this is a technical programming very powerful
for defining dynamic structures that is to say that advances over time.

Que 4 What do you mean by operators Precedence & Accociativity ? Explain With
Example .
This page lists C operators in order of precedence (highest to lowest). Their associativity indicates in

what order operators of equal precedence in an expression are applied.


Operator Associativity
Description

() Parentheses (function call) (see Note 1) left-to-right


[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
++ -- Prefix increment/decrement right-to-left
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
*  /  % Multiplication/division/modulus left-to-right
+  - Addition/subtraction left-to-right
<<  >> Bitwise shift left, Bitwise shift right left-to-right
<  <= Relational less than/less than or equal to left-to-right
>  >= Relational greater than/greater than or equal to
==  != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+=  -= Addition/subtraction assignment
*=  /= Multiplication/division assignment
%=  &= Modulus/bitwise AND assignment
^=  |= Bitwise exclusive/inclusive OR assignment
<<=  >>= Bitwise shift left/right assignment
, left-to-right
Comma (separate expressions)

Que5 How Does a Structure diffrent from a Arrey ?

Array Structure

i. Data Collection

Array is a collection of homogeneous


Stucture is a collection of heterogeneous data.
data.

ii. Element Reference

Array elements are referred by subscript. Structure elements are referred by its unique name.

iii. Access Method

Array elements are accessed by it's Stucture elements are accessed by its object as '.'
position or subscript. operator.

iv. Data type

Array is a derived data type. Structure is user defined data type.

v. Syntax

struct struct_name
{
structure element 1;
structure element 2;
<data_type> array_name[size]; ----------
----------
structure element n;
}struct_var_nm;
vi. Example

struct item_mst
{
 int rno[5]; int rno;
char nm[50];
}it;

Ques 6 Expalin Array . How Will You Declare one Dimensional and two dimensional
arrey ?
Array :
Array is a collection of homogenous data stored under unique name. The values in an array is
called as 'elements of an array.' These elements are accessed by numbers called as 'subscripts
or index numbers.' Arrays may be of any variable type.
Array is also called as 'subscripted variable.'
Types of an Array :
1.One / Single Dimensional Array
2.Two Dimensional Array
Single / One Dimensional Array :
The array which is used to represent and store data in a linear form is called as 'single or one
dimensional array.'
Syntax:
<data-type> <array_name> [size];
Example:
int a[3] = {2, 3, 5};
char ch[20] = "TechnoExam" ;
float stax[3] = {5003.23, 1940.32, 123.20} ;
Total Size (in Bytes):
total size = length of array * size of data type

In above example, a is an array of type integer which has storage size of 3 elements. The total
size would be 3 * 2 = 6 bytes.
Two Dimensional Array :
The array which is used to represent and store data in a tabular form is called as 'two
dimensional array.' Such type of array specially used to represent data in a matrix form.
The following syntax is used to represent two dimensional array.
Syntax:
<data-type> <array_nm> [row_subscript][column-subscript];
Example:
int a[3][3];
In above example, a is an array of type integer which has storage size of 3 * 3 matrix. The total
size would be 3 * 3 * 2 = 18 bytes.
It is also called as 'multidimensional array.'

Que7 What is the purpose of continue statement ?

The Continue Statement skips the current iteration of a for, while, or do-while loop. 


Unlabeled : The Unlabeled form skips to the end of the innermost loop's body and evaluates
the boolean expression that controls the loop. 
Example
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
//interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
Here is the output of this program:
Found 9 p's in the string.
- The above program, ContinueDemo , steps through a String, counting the occurences of the
letter "p". If the current character is not a p, the Continue Statement skips the rest of the loop
and proceeds to the next character. If it is a "p", the program increments the letter counts.
To see this effect more clearly, try removing the Continue Statement and recompiling. When
you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.

Que 8 State the use of % C and % S in 'C' Program. Write Print Statement in 'C' Using
Above Symbol.
printf Background
The printf function is not part of the C language, because there is no input or output defined
in C language itself. The printf function is just a useful function from the standard library of
functions that are accessible by C programs. The behavior of printf is defined in the ANSI
standard. If the compiler that you’re using conforms to this standard then all the features and
properties should be available to you.
Format Specifiers
There are many format specifiers defined in C. Take a look at the following list:
%i or %d int
%c char
%f float
%lf double
%s string

Note: %lf stands for long float.


Let’s take a look at an example of printf formatted output:

#include<stdio.h>

main()
{
int a,b;
float c,d;

a = 15;
b = a / 2;
printf("%d\n",b);
printf("%3d\n",b);
printf("%03d\n",b);

c = 15.3;
d = c / 3;
printf("%3.2f\n",d);
}

Output of the source above:

7
7
007
5.10

Ques 9 Explain “Call-By-Value” and “Call-By-Reference” in C Programming.

1) Call by Value:-when we call a Function and if a function can accept the Arguments from
the Called Function, Then we must have to Supply some Arguments to the Function. So that
the Arguments those are passed to that function just contains the values from the variables
but not an Actual Address of the variable.
 
So that generally when we call a Function then we will just pass the variables or the
Arguments and we doesn’t Pass the Address of Variables , So that the function will never
effects on the Values or on the variables. So Call by value is just the Concept in which you
must have to Remember that the values those are Passed to the Functions will never effect the
Actual Values those are Stored into the variables.
 
2) Call By Reference :-When a function is called by the reference then the values those are
passed in the calling functions are affected when they are passed by Reference Means they
change their value when they passed by the References. In the Call by Reference we pass the
Address of the variables whose Arguments are also Send. So that when we use the Reference
then, we pass the Address the Variables.
 
When we pass the Address of variables to the Arguments then a Function may effect on the
Variables. Means When a Function will Change the Values then the values of Variables gets
Automatically Changed. And When a Function performs Some Operation on the Passed
values, then this will also effect on the Actual Values.

Que 10 Write a “C” Program to Accept 10 integer numbers and Display them using
Arrey.

#include<iostream>

1.#include<conio>

2.int main()

3.{

4.int arr[10];

5.int i,j,sum=0,flag;

6.cout<<"Enter the Integers : ";

7.for(i=0;i<10;i++)

8.cin>>arr[i]; //Loop Takes ten integer

9.for(i=0;i<10;i++)

10.{

11.flag=0; // Flag is assigned 0 intially

12.for(j=i+1;j<10;j++)

13.if(arr[i]==arr[j]) // Any integer repeat then flag becomes 1

14.flag=1;

15.if(flag==0) //If any integer is repeated then it is not counted

16.sum=sum+arr[i];

17.}

18.cout<<" Sum is :"<<sum; //Sum is displayed


19.return 0;

20.}

Que 11 Explain Meaning of increment & Decrement Operator.

Increment and Decrement Operators


There are some operations that occur so frequently in writing assignment statements that C+
+ has shorthand methods for writing them.
One common situation is that of incrementing or decrementing an integer variable. For
example:
n = n + 1;
n = n - 1;
C++ has an increment operator ++ and a decrement operator --. Thus
n++; can be used instead of n = n + 1; 
n--; can be used instead of n = n - 1;
The ++ and -- operators here have been written after the variable they apply to, in which case
they are called the postincrement and postdecrement operators. There are also
identical preincrement and predecrement operators which are written before the variable to
which they apply. Thus
++n; can be used instead of n = n + 1; 
--n; can be used instead of n = n - 1;
Both the pre- and post- versions of these operators appear to be the same from the above, and
in fact it does not matter whether n++ or ++n is used if all that is required is to increment the
variable n. However both versions of the increment and decrement operators have a side
effect which means that they are not equivalent in all cases. These operators as well as
incrementing or decrementing the variable also return a value. Thus it is possible to write
i = n++;
What value does i take? Should it take the old value of n before it is incremented or the new
value after it is incremented? The rule is that a postincrement or postdecrement operator
delivers the old value of the variable before incrementing or decrementing the variable. A
preincrement or predecrement operator carries out the incrementation first and then delivers
the new value. For example if n has the value 5 then
i = n++;
would set i to the original value of n i.e. 5 and would then increment n to 6. Whereas
i = ++n;
would increment n to 6 and then set i to 6.
For the moment this notation will only be used as a shorthand method of incrementing or
decrementing a variable.

Que 12 Explain Declaration and Initialization of string variables.


Declare a Variable
Java is a strongly typed programming language. This means that every variable must have a
data type associated with it. For example, a variable could be declared to use one of the eight
primitive data types: byte, short, int, long, float, double, char or boolean.
A good analogy for a variable is to think of a bucket. We can fill it to a certain level, we can
replace what's inside it, and sometimes we can add or take something away from it. When we
declare a variable to use a data type it's like putting a label on the bucket that says what it can
be filled with. Let's say the label for the bucket is "Sand". Once the label is attached, we can
only ever add or remove sand from the bucket. Anytime we try and put anything else into it,
we will get stopped by the bucket police. In Java, you can think of the compiler as the bucket
police. It ensures that programmers declare and use variables properly.
To declare a variable in Java, all that is needed is the data type followed by the variable name:
int numberOfDays;
In the above example, a variable called "numberOfDays" has been declared with a data type of
int. Notice how the line ends with a semi-colon. The semi-colon tells the Java compiler that
the declaration is complete.
Now that it has been declared, numberOfDays can only ever hold values that match the
definition of the data type (i.e., for an int data type the value can only be a whole number
between -2,147,483,648 to 2,147,483,647).
Declaring variables for other data types is exactly the same:
byte nextInStream;
short hour;
long totalNumberOfStars;
float reactionTime;
double itemPrice;

Initializing Variables
Before a variable can be used it must be given an initial value. This is called initializing the
variable. If we try to use a variable without first giving it a value:
int numberOfDays;
//try and add 10 to the value of numberOfDays
numberOfDays = numberOfDays + 10;
the compiler will throw an error:
variable numberOfDays might not have been initialized
To initialize a variable we use an assignment statement. An assignment statement follows the
same pattern as an equation in mathematics (e.g., 2 + 2 = 4). There is a left side of the
equation, a right side and an equals sign (i.e., "=") in the middle. To give a variable a value, the
left side is the name of the variable and the right side is the value:
int numberOfDays;
numberOfDays = 7;
In the above example, numberOfDays has been declared with a data type of int and has been
giving an initial value of 7. We can now add ten to the value of numberOfDays because it has
been initialized:
int numberOfDays;
numberOfDays = 7;
numberOfDays = numberOfDays + 10;
System.out.println(numberOfDays);
Typically, the initializing of a variable is done at the same time as its declaration:
//declare the variable and give it a value all in one statement
int numberOfDays = 7;

Que 13 Explain Global and local varible..Write “C” Program to explain global and local
varible.

Local and Global Variables


Local Variables
All the variables we have used thus far have been local variables.  A local variable is a variable
which is either a variable declared within the function or is an argument passed to a function. 
As you may have encountered in your programming, if we declare variables in a function then
we can only use them within that function.  This is a direct result of placing our declaration
statements inside functions.
Consider a program that calls a swap() function.
#include <iostream.h>
void swap(int x, int y) { 
  int temp = x; 
  x = y; 
  y = temp; 
}
int main() 

  int A, B;
  cin >> A >> B;
  cout << "A: " << A << "." << endl; 
  cout << "B: " << B << "." << endl; 
  swap(A, B); 
  cout << "A: " << A << "." << endl; 
  cout << "B: " << B << "." << endl;
  return 0; 
}
Consider variables which are in scope (DEF: portion of a program in which a 
variable is legally accessible) in the main() and swap() functions: 
 
Function Accessible variables
main A, B
swap temp, x, y
If you attempted to use A was in swap(), a compilation error would result ("undeclared
identifier") since it is a local variable in only main(). 
Global Variables
A global variable (DEF) is a variable which is accessible in multiple scopes.  It is important to
note that global variables are only accessible after they have been declared.  That is, you can
use a variable is is declared below its usage in the text.  For instance, if we consider this simple
program, we have one global variable, w.
#include <iostream.h>
double w;
void Z() { 
  w = 0; 
  return; 
}
void Q() { 
  int index;
  w = 2; 
  return; 
}
int main() { 
  int i;
  w = 4;
  return 0; 
}
w is a global variable which is in scope in all three functions in this program: Z(), Q(), and
main().  This program also has local variables: index is local to Q(), and i is local to main().
Scoping can viewed easily in the following table. 
Function Accessible Variables
main w, i
Z w
Q w, index
Another example.
#include <iostream.h>
int sum;
void Z(int alpha) { 
  sum += 1; 
  alpha *= 3;
  return; 
}
double total;
void Q() { 
  int index;
  total = index;
  return; 
}
int main() { 
  int i; 
  int w = 10;
  sum = 0; 
  total = 0;
  return 0; 
}
We construct the scoping table. 
Function Accessible Variables
main sum total, i, w
Q sum, total, index
Z sum, alpha
Note that since the variable total is declared below Z() in the text, total is not in scope in Z().

Que 14 write a program in “C” to declare the structure employee having member
varible emp-id , name and phone no . Accept to data for 5 employees and display it.

1. #include
2. using namespace std;
3. struct persontag {
4. char name[ 20 ];
5. int age;
6. float salary;
7. }employee;
8. main( ){
9. cout << " ENTER EMPLOYEE NAME: ";
10. cin >> employee.name;
11. cout << " ENTER EMPLOYEE AGE: ";
12. cin >> employee.age;
13. cout << " ENTER EMPLOYEE SALARY:";
14. cin >> employee.salary;
15. cout << " NAME IS " << employee.name s<< endl;
16. cout << "AGE IS " << employee.age << endl;
17. cout << " SALARY IS " << employee.salary << endl;
18. return 0;
19. }//MAIN
Que 15 write a “C” Program to display menu. Addition, Subtraction , multiplication,
Division and Execute it using switch case (Accept two nos. From User)
{
//input declarations as doubles for total and counter
double total = 0, counter =0;
//input declarations sign and Q as character
char sign, Q = 0;
//input declaration value as double
double value;

//A do..while will loop forever (or until we hit the break statement)
do
{
//The current value is 0.
cout << "Result :"<<" "<< total << '\n';

//Please enter an operation


cout << "Please enter an operation and number : ";
cin >> sign;

//If the operation is Q, the program will end.


if (sign != 'Q')

cin >> value;


cin.ignore();

// If the value input is <=0, you can't divide anything by zero.


if (value <= 0)
{
cout << "Unknown Operator " << sign <<'\n' ;
}

//Otherwise procede with the calulator program


else
{
//If the operation is equal to '+', then the total is added.
if (sign == '+')
{
total += value;
}

// If the operation is equal to '-', then the value is subtracted


from the previous number input.
else
{
if (sign == '-')
{
total -= value;
}
// If the operation is equal to '*', then the value is
multiplied to the previous number input.
else
{
if (sign == '*')
{
total *= value;
}

// If the operation is equal to '/', then the value is


divided by the previous number input.
else
{
if ((sign == '/')&&(value != 0))
{
total /= value;
}
}
}
}
}
}

//While the operation is not equal to 'Q', the program will run.
while (sign != 'Q');

return 0;
}

Que 16 Explain the Concept of Pointer Arithmetic Operation with example.

s explained in main chapter, C pointer is an address which is a numeric value.


Therefore, you can perform arithmetic operations on a pointer just as you can a
numeric value. There are four arithmetic operators that can be used on pointers: +
+, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer
which points to the address 1000. Assuming 32-bit integers, let us perform the
following arithmetic operation on the pointer:

Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable
pointer can be incremented, unlike the array name which cannot be incremented
because it is a constant pointer. The following program increments the variable
pointer to access each succeeding element of the array:
#include <stdio.h>

const int MAX = 3;


int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;

/* let us have array address in pointer */


ptr = var;
for ( i = 0; i < MAX; i++)
{

printf("Address of var[%d] = %x\n", i, ptr );


printf("Value of var[%d] = %d\n", i, *ptr );

/* move to the next location */


ptr++;
}
return 0;
}
When the above code is compiled and executed, it produces result something as
follows:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value
by the number of bytes of its data type as shown below:
#include <stdio.h>

const int MAX = 3;

int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;

/* let us have array address in pointer */


ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--)
{

printf("Address of var[%d] = %x\n", i, ptr );


printf("Value of var[%d] = %d\n", i, *ptr );

/* move to the previous location */


ptr--;
}
return 0;
}
When the above code is compiled and executed, it produces result something as
follows:
Address of var[3] = bfedbcd8
Value of var[3] = 200
Address of var[2] = bfedbcd4
Value of var[2] = 100
Address of var[1] = bfedbcd0
Value of var[1] = 10
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1
and p2 point to variables that are related to each other, such as elements of the
same array, then p1 and p2 can be meaningfully compared.
The following program modifies the previous example one by incrementing the
variable pointer so long as the address to which it points is either less than or
equal to the address of the last element of the array, which is &var[MAX - 1]:
#include <stdio.h>

const int MAX = 3;

int main ()
{
int var[] = {10, 100, 200};
int i, *ptr;

/* let us have address of the first element in pointer */


ptr = var;
i = 0;
while ( ptr <= &var[MAX - 1] )
{

printf("Address of var[%d] = %x\n", i, ptr );


printf("Value of var[%d] = %d\n", i, *ptr );

/* point to the previous location */


ptr++;
i++;
}
return 0;
}
When the above code is compiled and executed, it produces result something as
follows:
Address of var[0] = bfdbcb20
Value of var[0] = 10
Address of var[1] = bfdbcb24
Value of var[1] = 100
Address of var[2] = bfdbcb28
Value of var[2] = 200

Que 17 Explain following string handling function in “C” Program


Strcat(), Strcmp(), strcpy(),strlen().

Program to find length of the string.


#include <stdio.h>
#include <conio.h>
#include <string.h>
void main ()
{
char s[20];
int l;
clrscr ();
puts(“Enter String”);
gets(s);
l = strlen (s);
printf (“Length=%d”, l);
getch ();
}

Output

Enter String
WELCOME
Length=7
Program to copy one string into another string.
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main ()
{
char s1[20],s2[20];
clrscr ();
puts(“Enter String”);
gets(s1);
strcpy(s2, s1);
printf (“S1=%s\n”, s1);
printf (“S2=%s\n”, s2);
getch ();
}

Output

Enter String
Hello
S1=Hello
S2=Hello
Program to concate two strings.
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main ()
{
    char s1[40],s2[20];
    clrscr ();
    puts(“Enter String1”);
    gets(s1);
    puts(“Enter String2”);
    gets(s2);
    strcat(s1, s2);
    printf (“S1=%s\n”, s1);
    getch ();
}

Output

Enter String1
Hello
Enter String2
Welcome
S1=HelloWelcome
Program to compare two strings.
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main ()
{
    char s1[20],s2[20];
    int ans;
    clrscr ();
    puts(“Enter String1”);
    gets(s1);
    puts(“Enter String2”);
    gets(s2);
    ans=strcmp(s1, s2);
    if (ans == 0)
    printf (“String are equal);
    else
    printf("String are Not equal");
    getch ();
}

Output
Enter String1
MAX
Enter String2
MIN
String are not equal
Program to reverse given string.
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main ()
{
    char s1[20];
    clrscr ();
    puts(“Enter String”);
    gets(s1);
    printf (“Original String is %s\n”, s1);
    strrev(s1);
    printf (“Reverse is %s\n”, s1);
    getch ();
}

Output

Enter String
NODE
Original String Is NODE
Reverse is EDON
Program to find one string into another string.
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main ()
{
    char s1[20],s2[20];
    clrscr ();
    puts(“Enter Original String”);
    gets(s1);
    puts(“Enter Search String”);
    gets(s2);
    if ( strstr(s1, s2)==NULL)
    printf (“String Not Found");
    else
    printf (“String Found”);
    getch ();
}
Output
Enter Original String
Hello How Are U
Enter Search String
How
String Found

You might also like