25
// C program to print range of basic data types #include <stdio.h> // Prints min and max value for a signed type void printUnsignedRange(size_t bytes) { int bits = 8*bytes; // Note that the value of ‘to’ is "(1 << bits) – 1" // Writing it in following way doesn’t cause overflow unsigned int to = ((1 << (bits-1)) – 1) + (1 << (bits-1)) ; printf(" range is from %u to %u \n", 0, to); } // Prints min and max value for an unsigned type void printSignedRange(size_t bytes) { int bits = 8*bytes; int from = -(1 << (bits-1)); int to = (1 << (bits-1)) – 1; printf(" range is from %d to %d\n", from, to); } int main() { printf("signed char: "); printSignedRange(sizeof(char)); printf("unsigned char: "); printUnsignedRange(sizeof(unsigned char)); printf("signed int: "); printSignedRange(sizeof(int)); printf("unsigned int: "); printUnsignedRange(sizeof(unsigned int)); printf("signed short int: "); printSignedRange(sizeof(short int)); printf("unsigned short int: "); printUnsignedRange(sizeof(unsigned short int)); return 0;

Bug Bounty

Embed Size (px)

DESCRIPTION

yes bug bounty

Citation preview

// C program to print range of basic data types#include <stdio.h>

// Prints min and max value for a signed typevoid printUnsignedRange(size_t bytes){    int bits = 8*bytes;

    // Note that the value of ‘to’ is "(1 << bits) – 1"    // Writing it in following way doesn’t cause overflow    unsigned int to = ((1 << (bits-1)) – 1) + (1 << (bits-1)) ;

    printf(" range is from %u to %u \n", 0, to);}

// Prints min and max value for an unsigned typevoid printSignedRange(size_t bytes){   int bits = 8*bytes;   int from = -(1 << (bits-1));   int to =  (1 << (bits-1)) – 1;   printf(" range is from %d to %d\n", from, to);}

int main(){    printf("signed char: ");    printSignedRange(sizeof(char));

    printf("unsigned char: ");    printUnsignedRange(sizeof(unsigned char));

    printf("signed int: ");    printSignedRange(sizeof(int));

    printf("unsigned int: ");    printUnsignedRange(sizeof(unsigned int));

    printf("signed short int: ");    printSignedRange(sizeof(short int));

    printf("unsigned short int: ");    printUnsignedRange(sizeof(unsigned short int));

    return 0;}

//Output:

signed char: range is from -128 to 127

unsigned char: range is from 0 to 255

signed int: range is from -2147483648 to 2147483647

unsigned int: range is from 0 to 4294967295

signed short int: range is from -32768 to 32767

unsigned short int: range is from 0 to 65535

question2:

#include<iostream>#include<stdio.h>

using namespace std;

class Base{public:  Base()  {    fun(); //note: fun() is virtual  }  virtual void fun()  {    cout<<"\nBase Function";  }};

class Derived: public Base{public:  Derived(){}  virtual void fun()  {    cout<<"\nDerived Function";  }};

int main(){  Base* pBase = new Derived();  delete pBase;  return 0;}

//Output:Base FunctionSee following excerpt from C++ standard for explanation.When a virtual function is called directly or indirectly from a constructor (including from the mem-initializer for a data member) or from a destructor, and the object to which the call applies is the object under

construction or destruction, the function called is the one defined in the constructor or destructor’s own class or in one of its bases, but not a function overriding it in a class derived from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived object.Because of this difference in behavior, it is recommended that object’s virtual function is not invoked while it is being constructed or destroyed. See this for more details.

Question:

#include<iostream>

using namespace std;

class Test

{

private:

int x;

static int count;

public:

Test(int i = 0) : x(i) {}

Test(const Test& rhs) : x(rhs.x) { ++count; }

static int getCount() { return count; }

};

int Test::count = 0;

Test fun()

{

return Test();

}

int main()

{

Test a = fun();

cout<< Test::getCount();

return 0;

}

Output: Compiler DependentThe line “Test a = fun()” may or may not call copy constructor. So output may be 0 or 1. If copy elision happens in your compiler, the copy constructor will not be called. If copy elision doesn’t happen, copy constructor will be called. The gcc compiler produced the output as 0.

#include <iostream>using namespace std;

class A{public:    void print() { cout << "A::print()"; }};

class B : private A{public:    void print() { cout << "B::print()"; }};

class C : public B{public:    void print() { A::print(); }};

int main(){    C b;    b.print();}

//Output: Compiler Error: ‘A’ is not an accessible base of ‘C’There is multilevel inheritance in the above code. Note the access specifier in “class B : private A”. Since private access specifier is used, all members of ‘A’ become private in ‘B’. Class ‘C’ is a inherited class of ‘B’. An inherited class can not access private data members of the parent class, but print() of ‘C’ tries to access private member, that is why we get the error.

Question 2#include<iostream>using namespace std;

class base

{public:    virtual void show()  { cout<<" In Base \n"; }};

class derived: public base{    int x;public:    void show() { cout<<"In derived \n"; }    derived()   { x = 10; }    int getX() const { return x;}};

int main(){    derived d;    base *bp = &d;    bp->show();    cout << bp->getX();    return 0;}

//Output: Compiler Error: ‘class base’ has no member named ‘getX’In the above program, there is pointer ‘bp’ of type ‘base’ which points to an object of type derived. The call of show() through ‘bp’ is fine because ‘show()’ is present in base class. In fact, it calls the derived class ‘show()’ because ‘show()’ is virtual in base class. But the call to ‘getX()’ is invalid, because getX() is not present in base class. When a base class pointer points to a derived class object, it can access only those methods of derived class which are present in base class and are virtual.

Question 3#include<iostream>using namespace std;

class Test{    int value;public:    Test(int v = 0) { value = v; }    int getValue()  { return value; }};

int main(){    const Test t;    cout << t.getValue();    return 0;}

//Output: Compiler ErrorIn the above program, object ‘t’ is declared as a const object. A const object can only call const functions. To fix the error, we must make getValue() a const function.

// PROGRAM 1#include <stdio.h>int main(void){    int arr[] = {10, 20};    int *p = arr;    ++*p;    printf("arr[0] = %d, arr[1] = %d, *p = %d", arr[0], arr[1], *p);    return 0;}

//// PROGRAM 2#include <stdio.h>int main(void){    int arr[] = {10, 20};    int *p = arr;    *p++;    printf("arr[0] = %d, arr[1] = %d, *p = %d", arr[0], arr[1], *p);    return 0;}

//// PROGRAM 3#include <stdio.h>int main(void){    int arr[] = {10, 20};    int *p = arr;    *++p;    printf("arr[0] = %d, arr[1] = %d, *p = %d", arr[0], arr[1], *p);    return 0;}

The output of above programs and all such programs can be easily guessed by remembering following simple rules about postfix ++, prefix ++ and * (dereference) operators1) Precedence of prefix ++ and * is same. Associativity of both is right to left.2) Precedence of postfix ++ is higher than both * and prefix ++. Associativity of postfix ++ is left to right.(Refer: Precedence Table)The expression ++*p has two operators of same precedence, so compiler looks for assoiativity. Associativity of operators is right to left. Therefore the expression is treated as ++(*p). Therefore the output of first program is “arr[0] = 11, arr[1] = 20, *p = 11“.The expression *p++ is treated as *(p++) as the precedence of postfix ++ is higher than *. Therefore the output of second program is “arr[0] = 10, arr[1] = 20, *p = 20“.The expression *++p has two operators of same precedence, so compiler looks for assoiativity. Associativity of operators is right to left. Therefore the expression is treated as *(++p). Therefore the output of second program is “arr[0] = 10, arr[1] = 20, *p = 20“.

Q: Does overloading work with Inheritance?If we have a function in base class and a function with same name in derived class, can the base class function be called from derived class object? This is an interesting question and as an experiment predict the output of the following C++ program.

#include <iostream>using namespace std;class Base{public:    int f(int i)    {        cout << "f(int): ";        return i+3;    }};class Derived : public Base{public:    double f(double d)    {        cout << "f(double): ";        return d+3.3;    }};int main(){    Derived* dp = new Derived;    cout << dp->f(3) << '\n';    cout << dp->f(3.3) << '\n';    delete dp;    return 0;}

Run on IDEThe output of this program is:

f(double): 6.3

f(double): 6.6

Instead of the supposed output:

f(int): 6

f(double): 6.6

Overloading doesn’t work for derived class in C++ programming language. There is no overload resolution between Base and Derived. The compiler looks into the scope of Derived, finds the single function “double f(double)” and calls it. It never disturbs with the (enclosing) scope of Base. In C++, there is no overloading across scopes – derived class scopes are not an exception to this general rule. (See this for more examples)Reference: technical FAQs on www.stroustrup.comNow consider Java version of this program:

class Base{    public int f(int i)    {        System.out.print("f (int): ");        return i+3;    }}class Derived extends Base{    public double f(double i)    {        System.out.print("f (double) : ");        return i + 3.3;    }}class myprogram3{    public static void main(String args[])    {        Derived obj = new Derived();        System.out.println(obj.f(3));        System.out.println(obj.f(3.3));    }}

Run on IDEThe output of the above program is:

f (int): 6

f (double): 6.6

So in Java overloading works across scopes contrary to C++. Java compiler determines correct version of the overloaded method to be executed at compile time based upon the type of argument used to call the method and parameters of the overloaded methods of both these classes receive the values of arguments used in call and executes the overloaded method.

Finally, let us try the output of following C# program:using System;class Base{    public int f(int i)    {        Console.Write("f (int): ");        return i + 3;    }}class Derived : Base{    public double f(double i)    {        Console.Write("f (double) : ");        return i+3.3;    }}class MyProgram

{    static void Main(string[] args)    {        Derived obj = new Derived();        Console.WriteLine(obj.f(3));        Console.WriteLine(obj.f(3.3));        Console.ReadKey(); // write this line if you use visual studio    }}

Run on IDENote: Console.ReadKey() is used to halt the console. It is similar to getch as in C/C++.The output of the above program is:

f(double) : 6.3

f(double): 6.6

instead of the assumed output

f(int) : 6

f(double) : 6.6

The reason is same as explained in C++ program. Like C++, there is no overload resolution between class Base and class Derived. In C#, there is no overloading across scopes derived class scopes are not an exception to this general rule. This is same as C++ because C# is designed to be much closer to C++, according to the Anders hejlsberg the creator of C# language.

Programs of larger lengths::

#include <cassert>#include <cstdlib>#include <iostream>

class Cpu { public: virtual int dummy( int, int ) {} private: virtual int add_( int a, int b ) { return a + b; } /* A */ virtual int sub_( int a, int b ) { return a - b; } /* B */ virtual int mul_( int a, int b ) { return a * b; } /* C */ virtual int div_( int a, int b ) { return a / b; } /* D */ virtual int mod_( int a, int b ) { return a % b; } /* E */ virtual int and_( int a, int b ) { return a & b; } /* F */ virtual int or_( int a, int b ) { return a | b; } /* G */ virtual int xor_( int a, int b ) { return a ^ b; } /* H */};

int main( int argc, char* argv[] ) { typedef int (Cpu::*Memfun)( int, int );

union { Memfun fn; unsigned char ptr[6]; } u;

Cpu cpu;

u.fn = &Cpu::dummy;

assert( argc == 4 );

int p1 = atoi( argv[ 1 ] ); int p2 = atoi( argv[ 3 ] ); char op = argv[2][0];

assert( op >= 'A' && op <= 'H' );

u.ptr[0] = 1 + 4 * ( op - 'A' + 1 ); // Don't look here!

std::cout << "The answer is " << ( (cpu.*(u.fn))( p1, p2 ) ) << std::endl;}

/************************************************************ Function of an integer raised in a power* and the calculation of the sum of a series of integers (1^e+2^e....+n^e) raised in a power.** Author: Spyridon Arvanitis* Date  : Jan, 2014***********************************************************/ #include <stdio.h> int power(int b, int e); int main()

 { /* n= positive integer e= power, S=  sum of integers raised in e power*/ int e,n,i,S=0; /*Input e and n. Control that the   inputs are positive numbers*/ printf (\\"Enter the last number (n)  of  the series\n\\"); scanf (\\"%d\\", &n);    if (n<=0) /* if n is a negative  number*/    {    printf (\\"Error. You gave a  negative number. Program ends.\n\\");    return 0;    } printf (\\"Input the number to be the  power\n\\"); scanf (\\"%d\\", &e);    if (e<=0) /* if n is a negative  number*/    {     printf (\\"Error. You gave a  negative number. Program ends.\n\\");     return 0;    } /* Calling function power n times*/    for (i=1; i<=n; i++)    {    S += power (i,e);   } printf (\\"The sum of the 1-%d series  of integers raised in %d is %d\\", n,e,  S); return 0; } /*Fuction to calculate a number raised  in power*/ int power(int b, int e) { 

int power=1; int i; if (b<=0)    {       return -1;   } if (e<=0)    {       return -1;   } for (i=1; i<=e;i++)    {    power*=b;    } return (power); }

//Procedural Programming technique shows creation of Pascal's Triangl#include <iostream>#include <iomanip>using namespace std;int** comb(int** a , int row , int col){   int mid = col/2;        //clear matrix         for( int i = 0 ; i < row ; i++)         for( int j = 0 ; j < col ; j++)                a[i][j] = 0;                a[0][mid] = 1; //put 1 in the middle of first row    //build up Pascal's Triangle matrix     for( int i = 1 ; i < row ; i++)        {          for( int j = 1 ; j < col - 1 ; j++)               a[i][j] = a[i-1][j-1] + a[i-1][j+1];        }   return a;}void disp(int** ptr, int row, int col){  cout << endl << endl;    for ( int i = 0 ; i < row ; i++)

        {        for ( int j = 0 ; j < col ; j++)            {                if( ptr[i][j] == 0)                cout << "   ";                else                cout << setw(4) << right << ptr[i][j];            }            cout << endl;        }    cout << endl << endl;}int main(){    int **ptr, m, n;    cout << "\nEnter number of rows to draw Pascal's Triangle: ";    cin >> m;    n = 2 * m + 1; //column = 2 * row + 1     ptr = new int*[m];    for( int i = 0 ; i < m ; i++)        ptr[i] = new int[n];         ptr = comb(ptr, m, n);//calling function for array creation         disp(ptr, m, n);//calling function for array displaying.     return 0;}/*Programs output******************Enter number of rows to draw Pascal's Triangle: 9                                1                           1      1                        1      2      1                     1      3      3      1                  1      4      6      4      1               1      5     10     10      5      1            1      6     15     20     15      6      1         1      7     21     35     35     21      7      1      1      8     28     56     70     56     28      8      1   Process returned 0 (0x0)   execution time : 2.996 sPress any key to continue.*/

1 // Program shows copying one text file from source location// to any other location (destination), plus possibility of changing its name,

234567891011121314151617181920212223242526272829303132333435363738394041424344454647

// and also shows many language features in exception handling.// This program should be run from the command prompt

#include<iostream>#include<stdio.h>#include<stdexcept>

using namespace std;

class PathError : public runtime_error{    public:        PathError(const char *x) : runtime_error(x)    {}};

// function to open source file for read

FILE* source (char* argvs[]){    FILE *in;    //open source file for read    if((in = fopen(argvs[1],"r"))==NULL)    {        throw PathError("attempted to open wrong input file path");//terminate function    }    return in;}

//function to create destination file for writtingFILE* destination (char* argvs[]){    FILE *out;    //open destination file for write    if((out = fopen(argvs[2],"w")) == NULL)    {        throw PathError("attempted to open wrong output file path");//terminate function    }    return out;}

int main(int argc, char *argv[]){    FILE *in, *out;    bool flag = 1;    int temp;    while(argc == 3)    {        try        {            in = source( argv );            out = destination( argv );            argc = 0;        }        catch(PathError& PathError)

4849505152535455565758596061626364656667686970717273747576777879808182

        {            cerr <<"\nException occured: " << PathError.what() << endl;            return -1;        }

        while(!feof(in))//test for it is not end of input file        {            temp = fgetc(in);//get char from (in)file            if( temp != EOF)            {                fputc(temp,out);//put char to (out) file            }        }        fclose(in);        fclose(out);        cout<<"\n\t 1 file copied.\n";        flag = 0;    }    if( flag != 0 )    {        cerr<<"\nWrong argument list!!!\n\n";        return -1;    }    return 0;}

12345678910111213141516171819202122232425262728293031323334353637383940414243

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

int main(){    int x,div=2;

    int i=0,j=0;    printf("Enter Number X : ");    scanf("%d",&x);    int num=x;    int *prime=(int *) malloc(x*sizeof(int));    printf("\n Allocated \n");    getch();    if (x==1 || x==0)    { printf(" Number %d have no prime Factors",x);    *prime=0;    }    else    { while(x>1)    {  if ((x%div)==0)        { *(prime+i)=div;x=x/div;i++;printf("\n Prime Factor\n");

        }        else        { div++; }

    }

    }

    printf("\n The Prime Factors for Number %d are  :\n",num);

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

    { printf (" %d ",*(prime+j));   }

    return(0);}

Fibonacci Series in C without recursion

Let's see the fibonacci series program in c without recursion.

1. #include<stdio.h>  2. #include<conio.h>  3. void main()  4. {  5.  int n1=0,n2=1,n3,i,number;  6.  clrscr();  7.  printf("Enter the number of elements:");  8.  scanf("%d",&number);  9.  printf("\n%d %d",n1,n2);//printing 0 and 1  10.   11.  for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed  12.  {  13.   n3=n1+n2;  14.   printf(" %d",n3);  15.   n1=n2;  16.   n2=n3;  17.  }  18. getch();  19. }  

Output:

Enter the number of elements:15

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Fibonacci Series using recursion in C

Let's see the fibonacci series program in c using recursion.

1. #include<stdio.h>  2. #include<conio.h>  3. void printFibonacci(int n){  4.     static int n1=0,n2=1,n3;  5.     if(n>0){  6.          n3 = n1 + n2;  7.          n1 = n2;  8.          n2 = n3;  9.          printf("%d ",n3);  10.          printFibonacci(n-1);  11.     }  12. }  13. void main(){  14.     int n;  15.     clrscr();  16.     printf("Enter the number of elements: ");  

17.     scanf("%d",&n);  18.   19.     printf("Fibonacci Series: ");  20.     printf("%d %d ",0,1);  21.     printFibonacci(n-2);//n-2 because 2 numbers are already printed  22.   23.     getch();  24. }  

Output:

Enter the number of elements:15

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

1. #include<stdio.h>  2. #include<conio.h>  3. main()  4. {  5. int n,r,sum=0,temp;  6. clrscr();  7. printf("enter the number=");  8. scanf("%d",&n);  9. temp=n;  10.while(n>0)  11. {  12. r=n%10;  13. sum=(sum*10)+r;  14. n=n/10;  15. }  16. if(temp==sum)  17. printf("palindrome number ");  18. else  19. printf("not palindrome");  20. getch();  21. }  

Output:

enter the number=151

palindrome number

enter the number=5621

not palindrome number

1. #include<stdio.h>  2. #include<conio.h>  3. void main()  

4. {  5. int n,i,m=0,flag=0;  6. clrscr();  7. printf("Enter the number to check prime:");  8. scanf("%d",&n);  9. m=n/2;  10. for(i=2;i<=m;i++)  11. {  12. if(n%i==0)  13. {  14. printf("Number is not prime");  15. flag=1;  16.break;  17. }  18. }  19. if(flag==0)  20. printf("Number is prime");  21. getch();  22. }   

#include<iostream>using namespace std;

class Test {    int value;public:    Test(int v);};

Test::Test(int v) {    value = v;}

int main() {    Test t[100];    return 0;}

Run on IDE

Output: Compiler error

The class Test has one user defined constructor “Test(int v)” that expects one argument. It doesn’t have a constructor without any argument as the compiler doesn’t create the default constructor if user defines a constructor (See this). Following modified program works without any error.#include<iostream>using namespace std;

class Test {    int value;public:    Test(int v = 0);};

Test::Test(int v) {    value = v;}

int main() {    Test t[100];    return 0;}