Tuesday 30 December 2014

Programming Quiz-44

Q: What will be the value of expression  5/6/3 + 8/3

Options:

A: 4
B: 2
C: 2.333
D: None of above

Answer: B

Programming Quiz-43

Consider the following statement in C language:

x=(a>b)?( (a>c)?a:c):(b>c)?b:c;

What will be the value of x if a=3, b= -5, c=2

Options:

A: 2
B: 3
C: -5
D: None of above

Answer: B

Programming Quiz-42

Q: In expression X/Y, the value of y should be:

Options:

1. integer
2. non-zero
3. non-negative
4. positive

Answer: 2

Programming Quiz-41

Q: Which of following does not denote a primitive data value in C language?

Options:

1. "A"
2. 'A'
3. 45.5
4. 011

Answer: 1

Programming Quiz-40

Q: Which of the following statements are true about break statement?

Options:

1. The break statement can be used with if statement to terminate the execution of its block.
2. The break statement can only be used with loop statements and switch statement
3. The break statement terminates current iteration of the loop
4. None of above

Answer: 2

Programming Quiz-39

Q: What will be the output of following program?

#include<stdio.h>
void main( )
{
      int i=3;
      while ( i>0)
      {
             int i=3;
             printf("%d\n",i);
             i--;
       }
}

Options:
1. Program will fail to compile because variable is duplicated.
2. Program will fail to compile because variables can only be declared in the beginning of the program.
3. Program will compile and execute successfully and will print 3, 2, 1 on different lines.
4. Program will enter into infinite loop

Answer: 4

Programming Quiz-37

Q: What is the function of character hyphen '-' when used after the character % in the field specifier?

Options:

1. To print the hyphen character before the output
2. To print the output left justified
3. To print the output right justified
4. None of above

Answer: B

Programming Quiz-38

Q: What will be the output of the following program?

#include<stdio.h>
void main( )
{
     printf("%d",'B');
}

Options:

1. 66
2. B
3. b
4. Error

Answer: 1

Programming Quiz-36

Q: Every C program has access to which of the following files?

1. stdin
2. stdout
3. stderr
4. All of above

Answer: 4

Programming Quiz-35

Q: Every escape sequence begins with character:

1. %
2. /
3. \
4. -

Answer: 3

For example:  \n, \t, \r

Sunday 28 December 2014

Pointer to member of class

We can assign the address of a member of a class to a pointer by applying operator & to a "fully qualified" class member name. Pointer to class member can be declared using the operator ::*. For example:

class abc
{
      int x;
      public :
      void show( );
};

Now we can define a pointer to the member x as follows:

int abc::* p=&abc :: x;

The p pointer created thus act like a class member in that it must be invoked with a class object. In the statement above, the phrase abc::* means  "pointer-to-member of abc class". The phrase &abc::x means the "address of the x member of abc class".

abc a;
cout<<a.*p;
cout<<a.x;

Above two statements are identical

Thursday 25 December 2014

How to declare const member functions?

If a member function does not alter any data in the class, then we may declare it as a const member function as follows:

void func(int , int) const;
float sum(float , float) const;

The qualifier const is appended to the function prototypes (in both declaration and definition). The compiler will generate an error message if such functions try to alter the data values of the data members of that class.

A world of Programming- GSBPROGRAMMING



A world of programming- GSBPROGRAMMING is a blog created by:
Er Gurpreet Singh,
Junior Software Engineer,
Sopra Steria India,

Seaview Special Economic Zone, Building 4, Plot No. 20 & 21, Sector-135, Noida, Uttar Pradesh 201304

Official Facebook page:
https://www.facebook.com/gsbprogramming



For any queries, please contact: 
Email: Er.gurpreet123@gmail.com
Mobile: +91-9803723925
Facebook: https://www.facebook.com/er.gurpreet123

Some facts about static member functions in C++

Like static member variable, we can also have static member functions. A member function that is declared static has the following properties:
  1. A static function can have access to only other static members (functions or variables) declared in the same class.
  2. A static member function can be called using the class name (instead of its objects) as follows:
                   class-name  : :  function-name;

Situations where inline expansion may not work

The inline keyword merely sends a request, not a command, to the compiler. The compiler may ignore this request if the function definition is too large or too complicated and compile the function as a normal function.

Some of the situation where inline expansion may not work are:

1. For functions returning value, if a loop, a switch, or a goto exists.
2. For functions not returning values, if a return statement exist.
3. If functions contain static variables.
4. If inline functions are recursive.

Sunday 21 December 2014

Method Overloading in C#

The process of creating more than one method in a class with same name or creating a method in derived class with same name as a method in base class is called as method overloading.


In VB.net when you are overloading a method of the base class in derived class, then you must use the keyword “Overloads”.


But in C# no need to use any keyword while overloading a method either in same class or in derived class.


While overloading methods, a rule to follow is the overloaded methods must differ either in number of arguments they take or the data type of at least one argument.


Example for Method Overloading


using System;

namespace ProgramCall
{

    class Class1
    {

        public int Sum(int A, int B)
        {
            return A + B;
        }

        public float Sum(int A, float B)
        {
            return A + B;
        }
    }

    class Class2 : Class1
    {
        public int Sum(int A, int B, int C)
        {
            return A + B + C;

        }
    }

    class MainClass
    {
        static void Main()
        {

            Class2 obj = new Class2();

            Console.WriteLine(obj.Sum(10, 20));

            Console.WriteLine(obj.Sum(10, 15.70f));

            Console.WriteLine(obj.Sum(10, 20, 30));

            Console.Read();
        }

    }
}

Output

30
25.7
60


Note

Method overloading provides more than one form for a method. Hence it is an example for polymorphism.


In case of method overloading, compiler identifies which overloaded method to execute based on number of arguments and their data types during compilation it self. Hence method overloading is an example for compile time polymorphism.

Method Overriding in C#

Creating a method in derived class with same signature as a method in base class is called as method overriding.
Same signature means methods must have same name, same number of arguments and same type of arguments.

Method overriding is possible only in derived classes, but not within the same class.


When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used.


To allow the derived class to override a method of the base class, C# provides two options, virtual methods and abstract methods.

Abstract Classes and Abstract Methods in C#

The purpose of abstract class is to provide default functionality to its sub classes.

When a method is declared as abstract in the base class then every derived class of that class must provide its own definition for that method.

 An abstract class can also contain methods with complete implementation, besides abstract methods.

When a class contains at least one abstract method, then the class must be declared as abstract class.

It is mandatory to override abstract method in the derived class.

When a class is declared as abstract class, then it is not possible to create an instance for that class. But it can be used as a parameter in a method.


Abstract class in c# example



The following example creates three classes shape, circle and rectangle where circle and rectangle are inherited from the class shape and overrides the methods Area() and Circumference() that are declared as abstract in Shape class and as Shape class contains abstract methods it is declared as abstract class.


using System;

namespace ProgramCall
{

    //Abstract class
    abstract class Shape1
    {

        protected float R, L, B;

        //Abstract methods can have only declarations
        public abstract float Area();
        public abstract float Circumference();

    }


    class Rectangle1 : Shape1
    {
        public void GetLB()
        {
            Console.Write("Enter  Length  :  ");

            L = float.Parse(Console.ReadLine());

            Console.Write("Enter Breadth : ");

            B = float.Parse(Console.ReadLine());
        }

      
        public override float Area()
        {
            return L * B;
        }

        public override float Circumference()
        {
            return 2 * (L + B);
        }

    }


    class Circle1 : Shape1
    {

        public void GetRadius()
        {

            Console.Write("Enter  Radius  :  ");
            R = float.Parse(Console.ReadLine());
        }

        public override float Area()
        {
            return 3.14F * R * R;
        }
        public override float Circumference()
        {
            return 2 * 3.14F * R;

        }
    }
    class MainClass
    {
        public static void Calculate(Shape1 S)
        {

            Console.WriteLine("Area : {0}", S.Area());
            Console.WriteLine("Circumference : {0}", S.Circumference());

        }
        static void Main()
        {

            Rectangle1 R = new Rectangle1();
            R.GetLB();
            Calculate(R);

            Console.WriteLine();

            Circle1 C = new Circle1();
            C.GetRadius();
            Calculate(C);

            Console.Read();

        }
    }
}

Output

Enter  Length  :  10
Enter Breadth : 12
Area : 120
Circumference : 44
Enter  Radius  :  5
Area : 78.5
Circumference : 31.4

Note

In the above example method calculate takes a parameter of type Shape1 from which rectangle1 and circle1 classes are inherited.

A base class type parameter can take derived class object as an argument. Hence the calculate method can take either rectangle1 or circle1 object as argument and the actual argument in the parameter S will be determined only at runtime and hence this example is an example for runtime polymorphism.

Virtual Methods in C#

When you want to allow a derived class to override a method of the base class, within the base class method must be created as virtual method and within the derived class method must be created using the keyword override.

When a method declared as virtual in base class, then that method can be defined in base class and it is optional for the derived class to override that method.

When it needs same definition as base class, then no need to override the method and if it needs different definition than provided by base class then it must override the method.

Method overriding also provides more than one form for a method. Hence it is also an example for polymorphism.


The following example creates three classes shape, circle and rectangle where circle and rectangle are inherited from the class shape and overrides the methods Area() and Circumference() that are declared as virtual in Shape class.



using System;

namespace demo
{
    class Shape
    {

        protected float R, L, B;
        public virtual float Area()
        {

            return 3.14F * R * R;
        }

        public virtual float Circumference()
        {
            return 2 * 3.14F * R;
        }

    }

    class Rectangle : Shape
    {
        public void GetLB()
        {
            Console.Write("Enter  Length  :  ");

            L = float.Parse(Console.ReadLine());

            Console.Write("Enter Breadth : ");
            B = float.Parse(Console.ReadLine());
        }
        public override float Area()
        {

            return L * B;
        }

        public override float Circumference()
        {
            return 2 * (L + B);
        }
    }

    class Circle : Shape
    {
        public void GetRadius()
        {
            Console.Write("Enter  Radius  :  ");

            R = float.Parse(Console.ReadLine());
        }
    }

    class entryClass
    {
        static void Main()
        {

            Rectangle R = new Rectangle();
            R.GetLB();

            Console.WriteLine("Area : {0}", R.Area());

            Console.WriteLine("Circumference : {0}", R.Circumference());

            Console.WriteLine();

            Circle C = new Circle();
            C.GetRadius();

            Console.WriteLine("Area : {0}", C.Area());
            Console.WriteLine("Circumference : {0}", C.Circumference());

            Console.Read();
        }
    }
}

Output

Enter  Length  :  10
Enter Breadth : 20
Area : 200
Circumference : 60
Enter  Radius  :  25
Area : 1962.5
Circumference : 157

Wednesday 17 December 2014

Programming Quiz-34

Q1) global variable conflicts due to multiple file occurrence is resolved during

a. compile-time
b. run-time
c. link-time
d. load-time

Answer: C


Q2) What will be the value of a & b after the execution of below program?
int a=5,b=6
swap(&a,b);
This function is written to swap a and b
find value of a and b.
a. 5,6
b. 6,5
c. 5,5
d. 6,6

Answer: D


Q3) What will be the output of the program below
#include
main(){
    int num[] = {1,4,8,12,16};
    int *p,*q;
    int i;
    p =  num;
    q = num+2;
    i = *p++;
    printf("%d, %d, %d\n",i, *p, *q);
}

a) 4, 4, 8
b) 1, 4, 8  
c) 2, 1, 8  
d) 2, 4, 8

Answer: B


Q4) What will be the output of the program below
#include

main(){
char *a[4]={"jaya","mahesh","chandra","swapant"};
int i = sizeof(a)/sizeof(char *);
printf("i = %d\n", i);
}
 
a)
b) 7  
c) 8  
d) 1
 
Answer: A
 
 
Q5)
#include
 #define scanf "%s is a string"
main()
{
 printf(scanf,scanf);
 

a) compilation error
b) runtime error  
c) %s is a string %s is a string  
d) %s is a string is a string  
e) None of the above

Answer: D
 


Programming Quiz-33

Q1) Max value of SIGNED int?

a. 2^31
b. 2^31 -1
c. 2^32
d. 2^32 -1


Answer: B






Q2) What does extern means in a function declaration?


a. the funct has global scope
b. the funct need not be defined
c. nothing really
d. the funct has local scope only to the file it is defined in
e. none of the above

Answer: C


Q3) When does a stack member will be initialized?

a. when object is created
b. when object is initialised.
c. does not depend on object.
d. none.

Answer: C


Q4) Which operator cannot be overloaded in C++ ?

a. +
b. ++
c. *
d. .

Answer: D



Q5) What is the size of the stack ?
fact(int x)
 {
  int n;
  n=x;
  return fact(x-1);
 }
 
a. infinity
b. n
c. n*(n-1)
d. depends on compiler and processor used.

Answer: B


Some facts on C/C++

  1. Functions defined in a class are by default inline.
  2. Memory space for the members of a class is allocated when an object of that class is created, not before that(at declaration of the class).
  3. Compiler provides a zero argument constructor only when there is no other constructor defined in the class.
  4. Realloc can be used to reallocate the memory allocated using new operator.
  5. Size of the pointer does not depend on where it is pointing to, it is always the same.
  6. Copy constructor and assignment operators are provided by default by the compiler.
  7. When an object is passed or returned to/from a function by value the copy constructor gets called automatically.
  8. For a template function to work it is mandatory that its definition should always be present in the same file from where it is called.
  9. All static data members are initialized to zero.
  10. For every static data member of a class it should also be defined outside the class to allocate the storage location.

Saturday 13 December 2014

Dangling Pointer

Dangling pointer:

If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.
 
for example:
 
#include<stdio.h>
int main()
{
int *p;
{
   int a=10;
   p=&a;
   delete &a;
}
printf("%d",*p);
return 0;
}
 
output:
garbage value

Wild Pointer

Wild pointer:

A pointer in c which has not been initialized is known as wild pointer.

Example:

What will be output of following c program?


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

int *ptr;

printf("%u\n",ptr);
printf("%d",*ptr);


return 0;
}


Output: 


Any address
Garbage value

 
Here ptr is wild pointer because it has not been initialized.

There is difference between the NULL pointer and wild pointer. Null pointer points the base address of segment while wild pointer doesn’t point any specific memory location.

Null Pointer

NULL pointer:

NULL pointer is a pointer which is pointing to nothing. NULL pointer points the base address of segment.

Examples of NULL pointer:

1. int *ptr=(char *)0;
2. float *ptr=(float *)0;
3. char *ptr=(char *)0;
4. double *ptr=(double *)0;
5. char *ptr=’\0’;
6. int *ptr=NULL;

We cannot copy any thing in the NULL pointer.

Example:

What will be output of following c program?

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

int main(){

char *str=NULL;

strcpy(str,"c-pointer.blogspot.com");
printf("%s",str);


return 0;
}

Output: (null)

Generic Pointer

Generic pointer:

void pointer in c is known as generic pointer. Literal meaning of generic pointer is a pointer which can point to any type of data.

Example:

void *ptr;
Here ptr is generic pointer.

Important points about generic pointer in c?

1. We cannot dereference generic pointer.


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

void *ptr;
printf("%d",*ptr);


return 0;
}

Output: Compiler error

2. We can find the size of generic pointer using sizeof operator.

#include <string.h>
#include<stdio.h>
int main(){
void *ptr;
printf("%d",sizeof(ptr));


return 0;
}

Output: 2
Explanation: Size of any type of near pointer in c is two byte.

3. Generic pointer can hold any type of pointers like char pointer, struct pointer, array of pointer etc without any typecasting.

Example:


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

char c='A';
int i=4;
void *p;
char *q=&c;
int *r=&i;

p=q;
printf("%c",*(char *)p);

p=r;
printf("%d",*(int *)p);


return 0;
}

Output: A4

4. Any type of pointer can hold generic pointer without any typecasting.

5. Generic pointers are used when we want to return such pointer which is applicable to all types of pointers. For example return type of malloc function is generic pointer because it can dynamically allocate the memory space to stores integer, float, structure etc. hence we type cast its return type to appropriate pointer type.

Examples:
1.

char *c;
c=(char *)malloc(sizeof(char));

2.
double *d;
d=(double *)malloc(sizeof(double));

3.
Struct student{
char *name;
int roll;
};
Struct student *stu;
Stu=(struct student *)malloc(sizeof(struct student));

Programming Quiz-32

Q: What will happen in this code?
    int a = 100, b = 200;
    int *p = &a, *q = &b;
    p = q;

Options:

a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a

Answer: b

Programming Quiz-31

Q: Which of the following is illegal?


Options:
a) int *ip;
b) string s, *sp = 0;
c) int i; double* dp = &i;
d) int *pi = 0;

Answer: c

Explanation: dp is initialized int value of i. 

Programming Quiz-30

Q: Choose the right option
    string* x, y;

Options:

a) x is a pointer to a string, y is a string
b) y is a pointer to a string, x is a string
c) both x and y are pointer to string types
d) none of the mentioned

Answer: a

Programming Quiz-29

Q: The operator used for dereferencing or indirection is ____



Options:

a) *
b) &
c) ->
d) –>>

Answer: a

Programming Quiz-28

Declare the following statement:

"A pointer to a function which receives nothing and returns nothing"

Options:

A: void *(ptr)*int;
B: void *(*ptr)( )
C: void *(*ptr)(*)
D: void (*ptr)( )

Answer: D

Programming Quiz-27

What do following declaration signify?

void *cmp();

Options:

A: cmp is a pointer to a void type
B: cmp is a void type pointer variable
C: cmp is a function that return a void pointer
D: cmp function returns nothing

Answer: C

Programming Quiz-26

Declare the following statement
"A pointer to a function which receives an int pointer and returns float pointer"

Options:

A: float *(ptr)*int;
B: float *(*ptr)(int)
C: float * (*ptr)(int *)
D: float (*ptr)(int)

Answer: C

Programming Quiz-25

Q: What do the following declaration signify?

int *ptr[30];

Options:

A: ptr is a pointer to an array of 30 integer pointers.
B: ptr is a array of 30 pointers to integers
C: ptr is a array of 30 integer pointers
D: ptr is a array of 30 pointers

Answer: B

Programming Quiz-24

Declare the following statement.

"An array of three pointers to chars"

Options:
A: char *ptr[3]( );
B: char *ptr[3];
C: char(*ptr[3])( );
char **ptr[3];

Answer: B

Programming Quiz-23

Q: What does the following declaration mean?

int (*ptr)[10];

Options:

A: ptr is array of pointers to 10 integers
B: ptr is a pointer to an array of 10 integers
C: ptr is an array of 10 integers
D: ptr is an pointer to array

Answer: B

Programming Quiz-22

Q: What does the following statement mean?
    int (*fp)(char*)

Options:

a) pointer to a pointer
b) pointer to an array of chars
c) pointer to function taking a char* argument and returns an int
d) function taking a char* argument and returning a pointer to int

Answer: C

Programming Quiz-21

Q: Pick the odd one out



Options:

a) array type
b) character type
c) boolean type
d) integer type

Answer: A

Explanation: Array is not a fundamental data type.

Programming Quiz-20

Q: What will be the output of following program?
#include<stdio.h>
int main( )
{
        float a=5,b=2;
        int c,d;
        c=a%b;
        d=a/2;
        printf("%d",d);
        return 0;
}

Options:

A: 3
B: 2.5
C: 2
D: Error

Answer: D

Thursday 11 December 2014

Some facts about comma operator

Consider the following C programs.
// PROGRAM 1
#include<stdio.h>
int main(void)
{
    int a = 1, 2, 3;
    printf("%d", a);
    return 0;
}
The above program fails in compilation, but the following program compiles fine and prints 1.
// PROGRAM 2
#include<stdio.h>
int main(void)
{
    int a;
    a = 1, 2, 3;
    printf("%d", a);
    return 0;
}
And the following program prints 3
// PROGRAM 3
#include<stdio.h>
int main(void)
{
    int a;
    a = (1, 2, 3);
    printf("%d", a);
    return 0;
}

In a C/C++ program, comma is used in two contexts: (1) A separator (2) An Operator.
Comma works just as a separator in PROGRAM 1 and we get compilation error in this program.
Comma works as an operator in PROGRAM 2. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3″ becomes equivalent to “(a = 1), 2, 3″. That is why we get output as 1 in the second program.

Programming Quiz-19

Q: A Program to add to two numbers without using Arithmetic operators.
A: Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result.

 #include<stdio.h>
  int Add(int x, int y)
 {
    // Iterate till there is no carry
    while (y != 0)
    {
        // carry now contains common set bits of x and y
        int carry = x & y;
        // Sum of bits of x and y where at least one of the bits is not set
        x = x ^ y;
        // Carry is shifted by one so that adding it to x gives the required sum
        y = carry << 1;
    }
    return x;
}
int main()
{
    printf("%d", Add(15, 32));
    return 0;
}

Some facts about static variable

IN C STATIC VARIABLE CAN BE INITIALIZED USING ONLY CONSTANT LITERALS.........

FOR EXAMPLE :  


static int i=20;
 

 IF WE DO NOT INITIALIZE ANY VALUE THEN......



 FOR EXAMPLE : 

static int i;

then by default value of i will be ZERO.......
MEANS i will be 0  ......



Note: All objects with static storage duration must be initialized   before execution of main() starts......

 FOR EXAMPLE : 

BELLOW PROGRAM WILL GIVE COMPILE TIME ERROR...


#include<stdio.h>
int a( )
{
return 6;
}
main( )
{
static int i=a( );       /* Compile Time Error*/
printf("%d",i);
return 0;
}




Explanation: All objects with static storage duration must be initialized   before execution of main() starts......

Programming Quiz-18




Answers:

Q1: Output will be:


2      657


Here 657 is address of func1 in integral format.

Q2: Output will be:


10
20
30
               30


Here we have given values as:
10
20
30

after that due to encounter of printf statement 30 will be printed. Now to understand this we must need to understand what does '*' in scanf and printf means

In scanf:
When we write scanf("%*d    %d",&a);
This means that the field '%*d'  is to be read but ignored...
for example: If we write 12   32 ,then 12 will be ignored and 32 will be stored in a

Now in above program scanf("%d %*d %d",&a,&b);
means that 2nd field (or second value) is ignored. So values stored in a and b are 10 and 30 respectively.

In printf:
When we write printf("%nd",a);
where n is any integer like 1,2,3.....   it means that the we are defining the field width.
for example: printf("%5d",1); will print 1 with 4 spaces preceding it. i.e.:
_ _ _ _ 1

Also when we write printf("%*d",a,b); it means that the field width will be a and the value printed will be b

for example: printf("%*d",5,1); will again print the above output i.e.:
_ _ _ _ 1


Q3: Output will be:


1


Explanation: In enum the values are assigned as: 0,1,2,3....
So value of second element will ofcourse be 1


Q4: Size of array must be a constant expresion, i.e. the size of array cannot be a variable whose value can be changed. To solve this we must define variable size as constant


Q5: The lines which will give errors are:

*str1='M';

*str2='K';

str3="Goodbye";

Explanation:

const char* str1
and
char const* str1   are identical expression.

now *str1 will points to first character and str1 will point to whole string.
Also, above expressions means that we cannot modify the string to which str1 points but we can modify the str1 to point to new string. So that's why *str1='M' and *str2='K' are error statements as they are modifying the string which is pointed by str1 and str2.

Also,
char * const str3 
statement means that str3 will only point to one string with which it is initialized i.e. it cannot point to other string but we can modify the string to which it points. So the statement str3="Goodbye" is error statement as it trying to modify the pointer