The CE Coding Challange

Yeah, it's time to code, here give your tricky questions on Programming, and we will all try to do that.

This would improve your thinking ability and refine your logic.

First we would have some simple questions and then move to more tricky ones.

I would like to roll the dice first.

Q1. Write a Program in C/C++ to print a statement ( say "Hello World") without using a semicolon (in the entire program).

Q2. Write a Program to add two numbers without using "+" .

Q3. Write a Program to multiply two numbers without using "*" .


Now that was a bit kiddish, don't worry, now let's face some questions which are more tricky

-> Write a Program that print it's own source code ie it would then recompile and run itself !

PS :- Though you may find solutions to the above questions googling them, but it would ruin the craziness .

This thread is created so that everyone can learn and improve their programming.


And keep adding more questions to this thread..!!

_______________________________________________________________________
Edit : While answering the questions, please explain the logic also, it would help others in understanding what you have done and others can also learn more stuff.

Replies

  • avii
    avii
    Please explain me how does printing Hello World without semi colon improves my logic ?
  • Sanyam Khurana
    Sanyam Khurana
    avii
    Please explain me how does printing Hello World without semi colon improves my logic ?
    Is not just about printing hello world but its more than that

    of course for printing something without semi colon you have to think differently which would improve your logic

    try all the questions and choose them

    lets see who does that and if these questions seems kiddish to you don't worry we will move to more complex questions soon.......
  • Vishal Sharma
    Vishal Sharma
    -> Write a Program that print it's own source code ie it would then recompile and run itself !
    I think the program will run unconditionally and infinitely if it recompiles itself and runs the exe generated.
    Here's my code there is some problem with process leaving the control of Untitled1.exe and go to recompiled.exe but it works fine.
    (Assuming that the gcc compiler already has a path in variables)


    #include
    #include
    #include
    int main() {
        printf("source code, recompile, display output\n\n");
        system("type Untitled1.cpp");
       
        Sleep(500);
       
        system("g++ -o recompiled Untitled1.cpp");
           
        Sleep(1000);              // stabilizing time
        system("recompiled.exe");
        return 0;
    }
  • Vishal Sharma
    Vishal Sharma
    Q1. Write a Program in C/C++ to print a statement ( say "Hello World") without using a semicolon.
    #include
    int main()
    {
        if(printf("I don't have semi colon"))
        {
              fflush(stdin);
              getchar();
        }   
    }
  • Vishal Sharma
    Vishal Sharma
    Q3. Write a Program to multiply two numbers without using "*" .
    #include
    void multi(int,int);
    int main()
    {
        int a = 40,b = 30;
        if(a>b)
            multi(a,b);
        else
            multi(b,a);
    }
    
    void multi(int greater, int smaller) {
        int ans = 0;
        while(smaller != 0) {
            ans += greater;
            smaller--;
        }
        printf("%d",ans);
    }
  • Vishal Sharma
    Vishal Sharma
    Q2. Write a Program to add two numbers without using "+" .

    #include
    void multi(int,int);
    int main()
    {
        int a = 32,b = 15;
        while( b != 0) {
            int c = a & b;
            a = a ^ b;
            b = c << 1;
        }
        printf("%d",a);
    }
    
  • Vishal Sharma
    Vishal Sharma
    Adding another question here!!


    write a program to swap all the occurrences of 0 to the end of the array!
    ex:
    input -> 1,0,2,0,3,0,4
    output -> 1,2,3,4,0,0,0
  • Sanyam Khurana
    Sanyam Khurana
    Vishal0203
    #include
    int main()
    {
        if(printf("I don't have semi colon"))
        {
              fflush(stdin);
              getchar();
        }  
    }

    Actually your code shouldn't use any semi colon.
    So, it would be something like this..

    #include
    int main()
    {
        if(printf("I don't have semi colon"))
        {
        }  
    }


    Your logic is right, just there wouldn't be any code in between the if statement.

    I would also like to request you to edit your above posts and explain the logic you used too, it would help many newbies, and other people.
  • Vishal Sharma
    Vishal Sharma
    Sanyam Khurana
    Actually your code shouldn't use any semi colon.
    So, it would be something like this..

    #include
    int main()
    {
        if(printf("I don't have semi colon"))
        {
        }
    }


    Your logic is right, just there wouldn't be any code in between the if statement.

    I would also like to request you to edit your above posts and explain the logic you used too, it would help many newbies, and other people.

    I printed the statement without using semi colon. I don't think it needs to be pointed out
    the code i've written inside if block is just to make it stay
    anyway,
    another way to do that (it satisfies your rules)


    #include
    int main()
    {
        switch(printf(" hello mere doston :P "))
        {
        }
    }
  • Sanyam Khurana
    Sanyam Khurana
    Vishal0203
    Adding another question here!!


    write a program to swap all the occurrences of 0 to the end of the array!
    ex:
    input -> 1,0,2,0,3,0,4
    output -> 1,2,3,4,0,0,0
    I have designed this code for 10 elements and would work as given.

    #include
    #include
    void main()
    {
    int a[10],i,j,b[10],count;
    clrscr();
    for(i=0;i<10;i++)
    {
    cin>>a[i];
    }
    for(i=0,j=0;i<10;i++)
    {
    
        if(a[i]!=0)
        {
          b[j]=a[i];
          j++;
        }
        else
        count++;
    }
    for(i=j;i<10;i++)
    b[i]=0;
    for(i=0;i<10;i++)
    {
    cout<
                                        
  • Vishal Sharma
    Vishal Sharma
    Sanyam Khurana
    I have designed this code for 10 elements and would work as given.

    #include
    #include
    void main()
    {
    int a[10],i,j,b[10],count;
    clrscr();
    for(i=0;i<10;i++)
    {
    cin>>a[i];
    }
    for(i=0,j=0;i<10;i++)
    {
    
        if(a[i]!=0)
        {
          b[j]=a[i];
          j++;
        }
        else
        count++;
    }
    for(i=j;i<10;i++)
    b[i]=0;
    for(i=0;i<10;i++)
    {
    cout<
    You need to swap the values instead of taking a separate array!
    I mean the changes are to be made within the array which is used to take input from user
  • Sanyam Khurana
    Sanyam Khurana
    Vishal0203
    I printed the statement without using semi colon. I don't think it needs to be pointed out
    Sorry, the question was actually that you don't have to use semi colon anywhere in the entire program. 😀

    PS:- I know I forgot to mention it clearly that you can't use the semicolon in the entire program , no problem, I'm going to edit that ...!!!

    Sorry for that, but please explain all your programs too...

    Vishal0203
    You need to swap the values instead of taking a separate array!
    I mean the changes are to be made within the array which is used to take input from user
    Ok, will work on it..
  • Vishal Sharma
    Vishal Sharma
    Sorry for that, but please explain all your programs too...
    2 of my programs are self explanatory, i'll add tags to my addition program
  • Sanyam Khurana
    Sanyam Khurana
    Vishal0203
    You need to swap the values instead of taking a separate array!
    I mean the changes are to be made within the array which is used to take input from user
    Ok, will work on it...

    Vishal0203
    #include
    void multi(int,int);
    int main()
    {
        int a = 32,b = 15;
        while( b != 0) {
            int c = a & b;
            a = a ^ b;
            b = c << 1;
        }
        printf("%d",a);
    }
    

    Can you explain this program, I'm not getting what you have done here....


    basically these three lines of code is what I need to understand..

    I have never seen this before 😔

     int c = a & b;
            a = a ^ b;
            b = c << 1;
    Thanks in advance..!!
  • Vishal Sharma
    Vishal Sharma
    Sanyam Khurana
    Ok, will work on it...




    Can you explain this program, I'm not getting what you have done here....


    basically these three lines of code is what I need to understand..

    I have never seen this before 😔

     int c = a & b;
            a = a ^ b;
            b = c << 1;
    Thanks in advance..!!
    I am just operating on the bits... I'll explain this in detail!

    I'll take a few small numbers to give an explanation..
    Say, a = 9 (1001 in binary) and b = 3 (0011 in binary)
    the variable c here indicates the carry. if I perform AND operation on a & b
    i.e. c = a & b;
    it executes like this,
    1 0 0 1
    0 0 1 1
    """"""""""
    0 0 0 1 (performing AND operation according to truth table)
    hence the carry i.e. c = 1 (0001 in binary)

    the next step is a = a ^ b where we are performing XOR operation on bits to calculating sum without adding the carry
    i.e.
    1 0 0 1
    0 0 1 1
    """"""""""
    1 0 1 0 (performing XOR operation according to #-Link-Snipped-#)
    hence value of a = 10 (1010 in binary)

    the next step is b = c << 1 (left shift of c)
    as we saw above c = 1 (0001) after left shift it becomes (0010) viz stored in b

    so at 1st iteration a = 10 , b = 2 , c = 1

    since it is in loop, we perform the 1st operation again i.e. c = a & b
    at this step, the value of a = 1 0 1 0 and b = 0 0 1 0
    so c becomes
    1 0 1 0
    0 0 1 0
    """"""""""
    0 0 1 0
    hence c = 2 (0010 in binary)
    the next step is a = a ^ b
    i.e.
    1 0 1 0
    0 0 1 0
    """"""""""
    1 0 0 0
    therefore, a = 8 (1000 in binary)
    next step b = c << 1 i.e. b = 0 1 0 0

    so at 2nd iteration a = 8 , b = 4 , c = 2
    again in next iteration, c = a & b
    1 0 0 0
    0 1 0 0
    """"""""""
    0 0 0 0
    i.e. c = 0

    next step, a = a ^ b
    1 0 0 0
    0 1 0 0
    """"""""""
    1 1 0 0
    i.e a = 12

    next step, b = c << 1;
    i.e. b = 0;
    since b = 0, loop breaks and value of a i.e. 12 is printed and that's the answer 😀
  • Vishal Sharma
    Vishal Sharma
    @#-Link-Snipped-# take time to read it and keep a paper and pen with you 😉
  • simplycoder
    simplycoder
    Sanyam Khurana
    Ok, will work on it...

    Can you explain this program, I'm not getting what you have done here....


    basically these three lines of code is what I need to understand..

    I have never seen this before 😔

     int c = a & b;
            a = a ^ b;
            b = c << 1;
    Thanks in advance..!!

    Basically this is the same as full adder. where c is the carry.



    Vishal0203
    Adding another question here!!


    write a program to swap all the occurrences of 0 to the end of the array!
    ex:
    input -> 1,0,2,0,3,0,4
    output -> 1,2,3,4,0,0,0
    I didn't find time to write a code, but here is an algorithm which I would use.
    Keep an counter of non-zero numbers(n), this would either be less or equal to numbers entered(m).
    print all the numbers the way they are and then print (m-n) zeroes.
  • Vishal Sharma
    Vishal Sharma
    I didn't find time to write a code, but here is an algorithm which I would use.
    treat 0 as highest number(replace 0 with infinity.. (if its an int array, treat 0 as 4294967295 and so).

    Sort in descending order and once we know the correct place, replace infinity by 0
    I think we can sort it normally!?
  • simplycoder
    simplycoder
    Vishal0203
    I think we can sort it normally!?
    My bad, I have edited my previous post, your problem never said sorting, it was my wrong assumption, refer to above edited post.
  • Vishal Sharma
    Vishal Sharma
    simplycoder
    My bad, I have edited my previous post, your problem never said sorting, it was my wrong assumption, refer to above edited post.
    hehe but i gave an example 😛 anyway lets see if anyone tries your algorithm!
  • Sanyam Khurana
    Sanyam Khurana
    Ok, it's done..!

    😛

    Here it is, just removed the second array and used first array itself..

    #include
    #include
    void main()
    {
    int a[10],i,j,count;
    clrscr();
    for(i=0;i<10;i++)
    {
    cin>>a[i];
    }
    for(i=0,j=0;i<10;i++)
    {
    
        if(a[i]!=0)
        {
          a[j]=a[i];
          j++;
        }
        else
        count++;
    }
    for(i=j;i<10;i++)
    a[i]=0;
    for(i=0;i<10;i++)
    {
    cout<
                                        
  • Sanyam Khurana
    Sanyam Khurana
    I think, count isn't required in this case, so it can be ignored and the else part too..

    The code would work fine without these also...
  • Sanyam Khurana
    Sanyam Khurana
    Ok, tell the output of this code

    and reason too for your answer

    #include
    #include
    void main()
    {
    int a=-29, b=-3;
    printf('%d",a%b);
    getch();
    }
    I know, vishal and crazycoder would immediately answer this.. 😛
  • Vishal Sharma
    Vishal Sharma
    Sanyam Khurana
    Ok, it's done..!

    😛

    Here it is, just removed the second array and used first array itself..

    #include
    #include
    void main()
    {
    int a[10],i,j,count;
    clrscr();
    for(i=0;i<10;i++)
    {
    cin>>a[i];
    }
    for(i=0,j=0;i<10;i++)
    {
    
        if(a[i]!=0)
        {
          a[j]=a[i];
          j++;
        }
        else
        count++;
    }
    for(i=j;i<10;i++)
    a[i]=0;
    for(i=0;i<10;i++)
    {
    cout<
    I'm sorry but you need to swap...
  • simplycoder
    simplycoder
    @#-Link-Snipped-#
    #include
    
    using namespace std;
    #define total_count 10
    int arr_numbers[total_count];
    
    int main(int argc,char**argv)
    {
        int non_zero_count=0; // Count non-zero numbers.
        int index;
       
        // Take the input.
        for(index=0; index>arr_numbers[index];
           
        }
       
        // Print only the nonzero number.
        for(index=0; index
  • Vishal Sharma
    Vishal Sharma
    Sanyam Khurana
    Ok, tell the output of this code

    and reason too for your answer

    #include
    #include
    void main()
    {
    int a=-29, b=-3;
    printf('%d",a%b);
    getch();
    }
    I know, vishal and crazycoder would immediately answer this.. 😛
    So lets wait for others to answer this! 😉
  • Vishal Sharma
    Vishal Sharma
    simplycoder
    @#-Link-Snipped-#
    #include
    
    using namespace std;
    #define total_count 10
    int arr_numbers[total_count];
    
    int main(int argc,char**argv)
    {
        int non_zero_count=0; // Count non-zero numbers.
        int index;
      
        // Take the input.
        for(index=0; index>arr_numbers[index];
          
        }
      
        // Print only the nonzero number.
        for(index=0; index
    umm... It gives the output but doesn't change the array... The question says "swap" , means the entire array will be modified
    ex:
    if array is
    1 0 2 0 3 0 4 0 5 0
    then after performing the sort
    the array will become
    1 2 3 4 5 0 0 0 0 0
  • Sanyam Khurana
    Sanyam Khurana
    Vishal0203
    I'm sorry but you need to swap...
    oops..

    Sorry, my bad..

    just forgot that it says swap..

    but what's the use of sort here..?

    Why do we have to sort..?


    Can't we just swap the element which is equal to zero?😐
  • Vishal Sharma
    Vishal Sharma
    Sanyam Khurana
    oops..

    Sorry, my bad..

    just forgot that it says swap..

    but what's the use of sort here..?

    Why do we have to sort..?


    Can't we just swap the element which is equal to zero?😐
    means the same!
    actually changes need to be made in array itself and the final result of array will be the array itself after the sort

    if array is
    1 0 2 0 3 0 4 0 5 0
    then after performing the sort
    the array will become
    1 2 3 4 5 0 0 0 0 0
  • simplycoder
    simplycoder
    Sanyam Khurana
    Ok, tell the output of this code

    and reason too for your answer

    #include
    #include
    void main()
    {
    int a=-29, b=-3;
    printf('%d",a%b);
    getch();
    }
    I know, vishal and crazycoder would immediately answer this.. 😛
    Its pretty simple if we think this as math question.

    1) '/' operator would give quotient.
    2) '%' operator would give remainder.
    3) Dividend=Divisor*Quotient+remainder
    4) a=b*(a/b)+(a%b)
    Don't discard b's in b*(a/b)!!
    => a/b gives -29/-3 = 9
    b*(a/b) gives -3*9=-27
    hence a%b=-2.
  • avii
    avii
    Sanyam Khurana
    Is not just about printing hello world but its more than that

    of course for printing something without semi colon you have to think differently which would improve your logic

    try all the questions and choose them

    lets see who does that and if these questions seems kiddish to you don't worry we will move to more complex questions soon.......
    Did I say these are kiddish ?

    Printing hello world in C without semi colons just shows how good your knowledge in C. It does not improve your logic. If you are targeting to end up working in companies like Infosys, Wipro, continue doing these. These will help you clear the placements.

    But if you think beyond them, for companies like Microsoft, Google etc, then start solving actual problem which will just f*ck your brains out. Something like this :

    The prime 41, can be written as the sum of six consecutive primes:

    41 = 2 + 3 + 5 + 7 + 11 + 13
    This is the longest sum of consecutive primes that adds to a prime below one-hundred.

    The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

    Which prime, below one-million, can be written as the sum of the most consecutive primes?
    This is 50th problem from project euler.

    Just today I finished interviewing bunch of people who probably were same like you guys. I am like, man, I don't give two f*cks about whether you do it in C or Java, I just want to know how you do it. They happily answer how to swap two numbers without using temp variable and all that stuff. Fact is, I don't care. And good companies or start ups don't care.

    Don't worry about languages. Think in terms of algorithms. Stop solving 'Tricky C questions' etc. Start doing, 'tricky questions'. Which are agonistic to any language. Your solution shouldn't be dependent on language.

    Anyways, these are my two cents. You may absolutely ignore my advice. Best of luck.
  • Abhishek Rawal
    Abhishek Rawal
    See, Knowledge of language is equally important as logic. Many people in world are good at logic, but they can't program.
    How would be the situation if a man can solve most trickiest query on paper, but couldn't program the shit ?
    All I mean is, both are equally important.

    And BTW, no need to flame on eachother, guys. Calm down.
    Don't like the thread ? Ignore it & move further. There is no need to give free suggestions to anyone until it's asked.
    Peace!
  • Vishal Sharma
    Vishal Sharma
    The prime 41, can be written as the sum of six consecutive primes:

    41 = 2 + 3 + 5 + 7 + 11 + 13
    This is the longest sum of consecutive primes that adds to a prime below one-hundred.

    The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

    Which prime, below one-million, can be written as the sum of the most consecutive primes?
    the prime number is 9384209 ?????

    can anyone confirm this answer??
  • Abhishek Rawal
    Abhishek Rawal
    Nope. Because 9,384,209 > 1,000,000.
  • Vishal Sharma
    Vishal Sharma
    Abhishek Rawal
    Nope. Because 9,384,209 > 1,000,000.
    oh shit i took it for 10,000,000 😛 my bad

    then is it 958577 ???
  • Sanyam Khurana
    Sanyam Khurana
    avii
    Did I say these are kiddish ?

    Printing hello world in C without semi colons just shows how good your knowledge in C. It does not improve your logic. If you are targeting to end up working in companies like Infosys, Wipro, continue doing these. These will help you clear the placements.

    But if you think beyond them, for companies like Microsoft, Google etc, then start solving actual problem which will just f*ck your brains out. Something like this :



    This is 50th problem from project euler.

    Just today I finished interviewing bunch of people who probably were same like you guys. I am like, man, I don't give two f*cks about whether you do it in C or Java, I just want to know how you do it. They happily answer how to swap two numbers without using temp variable and all that stuff. Fact is, I don't care. And good companies or start ups don't care.

    Don't worry about languages. Think in terms of algorithms. Stop solving 'Tricky C questions' etc. Start doing, 'tricky questions'. Which are agonistic to any language. Your solution shouldn't be dependent on language.

    Anyways, these are my two cents. You may absolutely ignore my advice. Best of luck.
    What I wanted to say is, I'm not a good programmer, not I'm a pro at forming algorithms, but we all have to start somewhere. So, I started this thread (as a learning opportunity), so that people like me, could grab the basic things first. I can't really code a bigger thing in one shot, if I'm even not clear with my basics.

    Sorry, if you got offended.
  • Vishal Sharma
    Vishal Sharma
    Sanyam Khurana
    What I wanted to say is, I'm not a good programmer, not I'm a pro at forming algorithms, but we all have to start somewhere. So, I started this thread (as a learning opportunity), so that people like me, could grab the basic things first. I can't really code a bigger thing in one shot, if I'm even not clear with my basics.

    Sorry, if you got offended.
    it's okay guys forget about it!
    and please confirm the answer i got? 😲
  • Vishal Sharma
    Vishal Sharma
    Vishal0203
    Adding another question here!!


    write a program to swap all the occurrences of 0 to the end of the array!
    ex:
    input -> 1,0,2,0,3,0,4
    output -> 1,2,3,4,0,0,0
    Answer to the above question!!


    #include
    int n,a[15];
    void sorter();
    int main()
    {
        printf("Enter the no. : ");
        scanf("%d",&n);
        printf("Enter the numbers : ");
        for(int i = 0 ; i < n ; i++) {
          scanf("%d",&a[i]);
        }
        sorter();
        printf("sorted! \n");
        for(int i = 0 ; i < n ; i++) {
            printf("%d",a[i]);
        }
        fflush(stdin);
        getchar();
        return 0;
    }
    
    void sorter() {
        for(int i = 0 ; i < n ; i++) {
        //swapping only when 2 adjacent elements are not zero
            if(a[i] == 0 && a[i+1] != 0) {    
                  int temp = a[i];
                  a[i] = a[i+1];
                  a[i+1] = temp;
                  if(i == 0)
                      i -= 1;
                  else
                      i -= 2;     // a proper decrement of index to reduce the no of comp
            }
        //if 2 adjacent elements are zero, toggle through array until two adj elements 
        // are non-zero
            if(a[i] == 0 && a[i+1] == 0) {
                continue;
            }
      }
    }
  • Sanyam Khurana
    Sanyam Khurana
    Here's one more..

    Write a Program to print all Pythagorean Triplets that occur between 100 and 900.

    PS: Pythagorean Triplets are the numbers which satisfy Pythagoras Theorem, Example is 3,4,5.
  • Vishal Sharma
    Vishal Sharma
    Sanyam Khurana
    Here's one more..

    Write a Program to print all Pythagorean Triplets that occur between 100 and 900.

    PS: Pythagorean Triplets are the numbers which satisfy Pythagoras Theorem, Example is 3,4,5.
    Do you mean all a,b,c values above 100 and below 900 ?
  • Sanyam Khurana
    Sanyam Khurana
    Vishal0203
    Do you mean all a,b,c values above 100 and below 900 ?
    Yes, we want Pythagorean Triplets..

    Which means you have to print all the three values between 100 to 900 ...
  • Vishal Sharma
    Vishal Sharma
    Sanyam Khurana
    Yes, we want Pythagorean Triplets..

    Which means you have to print all the three values between 100 to 900 ...
    I dont think we have any triplet with all 3 numbers between 100 to 900
    any way here's my code that gives you triplets up to 900


    #include
    #include
    int main() {
        int a,b,c;
        for(int i = 1 ; i <= 200 ; i++) {
            int m = i;
            int n = i+1;
            a= n*n - m*m;
            b = 2*m*n;
            c = m*m + n*n;
            if(c > 900)
                break;
            printf("%d, %d, %d\n",a,b,c);
        }
        return 0;
    }
  • Sanyam Khurana
    Sanyam Khurana
    Find the product of Pythagorean Triplet whose sum is 1000.
    It's just unique.

    PS: I just finished doing this one..!
  • Sanyam Khurana
    Sanyam Khurana
    Sanyam Khurana
    Q3. Write a Program to multiply two numbers without using "*" .
    What I did for this one is

    #include
    #include
    void main()
    {
    int a,b,c;
    clrscr();
    cout<<"Enter two numbers";
    cin>>a>>b;
    for(i=0;i
                                        
  • Jeffrey Arulraj
    Jeffrey Arulraj
    @#-Link-Snipped-#


    #include
    #include
    void main()
    {
    int a,b,c;
    clrscr();
    cout<<"Enter two numbers";
    cin>>a>>b;
    for(i=0;iAm I not right

    Cos it has to be added from 0 to N-1 or from 1 to N
  • Sanyam Khurana
    Sanyam Khurana
    Jeffrey Samuel
    @#-Link-Snipped-#


    #include
    #include
    void main()
    {
    int a,b,c;
    clrscr();
    cout<<"Enter two numbers";
    cin>>a>>b;
    for(i=0;iAm I not right

    Cos it has to be added from 0 to N-1 or from 1 to N
    Yup you are right ...

    This time didn't copied code, but just wrote it, and by mistake I wrote that equality sign.

    If we do add equality sign, then the loop will run one more time, so if we are multiplying 5*3, it would give 5*4.
  • Sanyam Khurana
    Sanyam Khurana
    Adding one more...

    Although I have done this, but my code was inefficient if the value is large, I Want to know a better way of doing this..(can't find a way to have a loop)

    Ok, question is..

    Find the smallest positive number which is divisible by numbers from 1 to 20.
  • Sanyam Khurana
    Sanyam Khurana
    Vishal0203
    I dont think we have any triplet with all 3 numbers between 100 to 900
    any way here's my code that gives you triplets up to 900


    #include
    #include
    int main() {
        int a,b,c;
        for(int i = 1 ; i <= 200 ; i++) {
            int m = i;
            int n = i+1;
            a= n*n - m*m;
            b = 2*m*n;
            c = m*m + n*n;
            if(c > 900)
                break;
            printf("%d, %d, %d\n",a,b,c);
        }
        return 0;
    }
    It is printing triplets even like 3,4,5 and 5,12,13...

    We wanted from 100 to 900...
  • rahul69
    rahul69
    Sanyam Khurana
    Here's one more..

    Write a Program to print all Pythagorean Triplets that occur between 100 and 900.

    PS: Pythagorean Triplets are the numbers which satisfy Pythagoras Theorem, Example is 3,4,5.
    int checkint(int f)
    {
    for(int i=100;i<900;i++)
    if((i*i)==f)
    return i;
    return 0;
    }
    main()
    {
      int a,b,c;
      int f,sq;  
    for(int i=100;i<700;i++)
    {
      a=i;
              for(int j=i+1;j<700;j++)
              {
                    b=j;
                    f= ((a*a)+(b*b));
                      sq=checkint(f);
                      if(sq)
                        c=sq;
                      else
                        c=999;
                      if(c<900)
                        cout<<"\n"<
                                        
  • rahul69
    rahul69
    Sanyam Khurana
    Find the product of Pythagorean Triplet whose sum is 1000.
    It's just unique.

    PS: I just finished doing this one..!
    31875000?
  • Sanyam Khurana
    Sanyam Khurana
    rahul69
    31875000?
    Yes, that's correct..👍

    and the triplets are

    200, 375 and 425...
  • Sanyam Khurana
    Sanyam Khurana
    Adding one more...

    Write a Program to first search the value of 2^1000 and then print the sum of it's digits.

    Eg. if we have to find value of 2^5= 32 then sum of it's digit is 3+2 = 5 , so 5 is the answer.

    PS: I was designing the algorithm for this, but just got stuck on how to save the large value of 2^1000 as there's no data type which can store that much large number.

    If you can help me, please head to the thread to discuss more about this problem..

    #-Link-Snipped-#
  • Sanyam Khurana
    Sanyam Khurana
    One more question..

    Write a Program to find the largest palindrome is a string.

    PS:- We need active participation, we are here to learn. Let's have an awesome discussion, learn and improve ourselves. 👍
  • Jeffrey Arulraj
    Jeffrey Arulraj
    Sanyam Khurana
    Write a Program to find the largest palindrome is a string.
    Explain this mate

    Largest palindrome is a string or in a string

    A little confused here
  • Sanyam Khurana
    Sanyam Khurana
    Jeffrey Samuel
    Explain this mate

    Largest palindrome is a string or in a string

    A little confused here
    If you are given a string, which would contain a palindrome inside it ..you need to spot the biggest palindrome..

    Eg. Let's say we have a string "ABCDEDCFGTU"
    here "DED" is a sub string which is a palindrome, but "CDEDC" is the biggest palindrome in the entire string, so we need to spot this and display it.

    Hope you got it..
  • Sanyam Khurana
    Sanyam Khurana
    or consider this...

    A string like
    "ABCDEDCGFATTAFGLU"
    Here, "CDEDC" is there and "GFATTAFG" is also there, so the second one would be the right answer.

    If it happens that two strings are of same length then you have to display both of the palindromes.
  • Sanyam Khurana
    Sanyam Khurana
    Here's another one to go...

    Write a Program to find largest and smallest from five numbers without using any array and loop, or conditional statements.


    PS: Keep adding more questions, and let's solve them..!! 👍
  • Shailaja Tiwari
    Shailaja Tiwari
    What value should be printed for x?
    #include

    int main()
    {
    int x = int() = 3;

    std::cout << x << std::endl;

    return 0;
    }

    options:
    a)0
    b)3
    c)undefined
    d)won't compile

    P.S. Do mention the logic for your answer.
    This question was asked to us in viva today.
  • simplycoder
    simplycoder
    Shailaja Tiwari
    What value should be printed for x?
    #include

    int main()
    {
    int x = int() = 3;

    std::cout << x << std::endl;

    return 0;
    }

    options:
    a)0
    b)3
    c)undefined
    d)won't compile

    P.S. Do mention the logic for your answer.
    This question was asked to us in viva today.
    d) Won't compile,
    code would expect an object int x = int() = 3;
    since this is not done, it would fail to compile throwing lvalue required error.
  • Shailaja Tiwari
    Shailaja Tiwari
    Right answer .
    Any way when this question was being asked to us by external most of my classmates ended up either by being mum or by suggesting the question as wrong.
  • rahul69
    rahul69
    Sanyam Khurana
    Here's another one to go...
    Write a Program to find largest and smallest from five numbers without using any array and loop, or conditional statements.

    PS: Keep adding more questions, and let's solve them..!! 👍
    Can we, however use conditional operators??
  • Sanyam Khurana
    Sanyam Khurana
    simplycoder
    d) Won't compile,
    code would expect an object int x = int() = 3;
    since this is not done, it would fail to compile throwing lvalue required error.
    Can you please tell me, how this would expect an object, and what's the meaning of this

    rahul69
    Can we, however use conditional operators??
    Conditional Operators as in " ? : " ?
  • simplycoder
    simplycoder
    Sanyam Khurana
    Can you please tell me, how this would expect an object, and what's the meaning of this


    Conditional Operators as in " ? : " ?
    #include
    int main(){
      
    int num1,num2,num3,num4,num5,largest,smallest;
      
    printf("\n\n
            Enter 5 numbers:\n\n"
    );
      
    scanf("%d %d %d %d %d",&num1,&num2,&num3,&num4,&num5);

      
    largest=(num1>num2?num1:num2);
      
    largest=(largest>num3?largest:num3);
      
    largest=(largest>num4?largest:num4);
      
    largest=(largest>num5?largest:num5);

      
    smallest=(num1<num2?num1:num2);
      
    smallest=(smallest<num3?smallest:num3);
      
    smallest=(smallest<num4?smallest:num4);
      
    smallest=(smallest<num5?smallest:num5);


      
    printf("\n\nThe largest number is: %d\n smallest is :%d\n",largest,smallest);

      return 
    0;
    }
  • Sanyam Khurana
    Sanyam Khurana
    simplycoder
    #include
    int main(){
      
    int num1,num2,num3,num4,num5,largest,smallest;
      
    printf("\n\n
            Enter 5 numbers:\n\n"
    );
      
    scanf("%d %d %d %d %d",&num1,&num2,&num3,&num4,&num5);

      
    largest=(num1>num2?num1:num2);
      
    largest=(largest>num3?largest:num3);
      
    largest=(largest>num4?largest:num4);
      
    largest=(largest>num5?largest:num5);

      
    smallest=(num1<num2?num1:num2);
      
    smallest=(smallest<num3?smallest:num3);
      
    smallest=(smallest<num4?smallest:num4);
      
    smallest=(smallest<num5?smallest:num5);


      
    printf("\n\nThe largest number is: %d\n smallest is :%d\n",largest,smallest);

      return 
    0;
    }
    Oh, I was just asking him about if he meant " ? : " as conditional operators ...

    No, you can't do with conditional operators too...

    Remember, you have to do this using no loop, no array, no conditional statements and no conditional operator too...

    BDW, could you please explain me what does it mean by int() ?

    And also the meaning of this statement int x = int() = 3;
  • Nikumbh
    Nikumbh
    Solution for the problem
    a[]={1,0,2,0,3,0}
    then, it should print
    1,2,3,0,0,0


    solution :
    #include
    using namespace std;
    int main()
    {
        int a[15],i,j,k,n;
        cout<<"Enter the array size\n";
        cin>>n;
        cout<<"Enter the nos\n";
        for(i=0;i>a[i];
        for (i = 0 ; i < (n-1); i++)
          {
                for (j = 0 ; j < (n-i-1); j++)
                {
            //if zero is followed by a non-zero, swap the zero and non-zero numbers
             
                      if ((a[j]==0) && ( a[j+1]!=0))
                      {
                    k      = a[j];
                        a[j]  = a[j+1];
                        a[j+1] = k;
                      }
                }
        }
     
        for(i=0;i

    It's just a bubble sort........
  • Nikumbh
    Nikumbh
    Vishal0203
    Adding another question here!!


    write a program to swap all the occurrences of 0 to the end of the array!
    ex:
    input -> 1,0,2,0,3,0,4
    output -> 1,2,3,4,0,0,0

    #include
    using namespace std;
    int main()
    {
        int a[15],i,j,k,n;
        cout<<"Enter the array size\n";
        cin>>n;
        cout<<"Enter the nos\n";
        for(i=0;i>a[i];
        for (i = 0 ; i < (n-1); i++)
          {
                for (j = 0 ; j < (n-i-1); j++)
                {
            //if zero is followed by a non-zero, swap the zero and non-zero numbers
               
                      if ((a[j]==0) && ( a[j+1]!=0))
                      {
                    k      = a[j];
                        a[j]  = a[j+1];
                        a[j+1] = k;
                      }
                }
        }
       
        for(i=0;i
    It's a kinda bubble sort technique........
  • Nikumbh
    Nikumbh
    Write a program to reverse the words in the string ie., if "you are a boy" is a string then should be changed like, "uoy era a yob"
  • Nikumbh
    Nikumbh
    Another question : Write a program to sort the elements of an array, the first half of the array should be sorted ascending, the second half of the array should be sorted descending..

    ie., a[]={9,2,3,7,4,5,6,3,8,2}

    the resultant a[]={2,3,4,7,9,8,6,5,3,2}
  • rahul69
    rahul69
    Sanyam Khurana
    Can you please tell me, how this would expect an object, and what's the meaning of this


    Conditional Operators as in " ? : " ?
    Yes I meant that (?😀 only.. so I guess we can't use those. I tried to write a program, but sadly it works only for natural numbers 😔
    Still sharing it, as I think it is an awesome Logic that I built.
    Do check it out: 😛😏😁
    #include
    #include
    using namespace std;
    
    void check()
    {
      int n1,n2,n3,n4,n5,a1,a2,a3,a4,a5;
    cout<<"\nEnter the 5 numbers:";
    cin>>n1>>n2>>n3>>n4>>n5;
    a1=(((n1/n2)*(n1/n3)*(n1/n4)*(n1/n5))&&1)*n1;
    a2=(((n2/n1)*(n2/n3)*(n2/n4)*(n2/n5))&&1)*n2;
    a3=(((n3/n2)*(n3/n1)*(n3/n4)*(n3/n5))&&1)*n3;
    a4=(((n4/n2)*(n4/n3)*(n4/n1)*(n4/n5))&&1)*n4;
    a5=(((n5/n2)*(n5/n3)*(n5/n4)*(n5/n1))&&1)*n5;
    cout<<"\nThe highest number is:"<<(a1+a2+a3+a4+a5);
    a1=(((n1/n2)+(n1/n3)+(n1/n4)+(n1/n5))&&1);
    a2=(((n2/n1)+(n2/n3)+(n2/n4)+(n2/n5))&&1);
    a3=(((n3/n2)+(n3/n1)+(n3/n4)+(n3/n5))&&1);
    a4=(((n4/n2)+(n4/n3)+(n4/n1)+(n4/n5))&&1);
    a5=(((n5/n2)+(n5/n3)+(n5/n4)+(n5/n1))&&1);
    n1=(a2*a3*a4*a5)*n1;
    n2=(a1*a3*a4*a5)*n2;
    n3=(a1*a2*a4*a5)*n3;
    n4=(a1*a2*a3*a5)*n4;
    n5=(a1*a2*a3*a4)*n5;
    cout<<"\nThe lowest number is:"<<(n1+n2+n3+n4+n5)<<"\n"; 
    }
    
    main()
    {
    check();
    system("Pause");
    return 0;   
    }
    
    😁
  • Vishal Sharma
    Vishal Sharma
    Nikumbh
    Write a program to reverse the words in the string ie., if "you are a boy" is a string then should be changed like, "uoy era a yob"
    I did this program using data structures long back! Here it is!


    #include
    #include
    using namespace std;
    
    struct list
    {
        char c;
        struct list *next;
    };
    
    list *reverse(list *);
    
    int main()
    {
        string input = "you are a boy";
        list *curr = new list;
        list *head = NULL;
    
        for(int i = 0 ; i < input.size() ; i++)
        {
            if(i == 0)
            {
                curr -> c = input[i];
                curr -> next = NULL;
                head = curr;
            }
            else
            {
                list *temp = new list;
                temp -> c = input[i];
                temp -> next = NULL;
                curr -> next = temp;
                curr = temp;
            }
        }
    
        list *temp;
        temp = head;
        while(temp != NULL)
        {
            cout<c;
            temp = temp->next;
        }
    
        temp = reverse(head);
    
        cout<c;
            temp = temp->next;
        }
    }
    
    
    list * reverse(list *head)
    {
        list *curr = head;
        list *prev = NULL;
        list *last = head;
    
        while(curr!= NULL && curr->c != ' ')
        {
            list *nextnode = curr->next;
            curr->next = prev;
            prev = curr;
            curr = nextnode;
        }
    
        last->next = curr;
    
        if(curr != NULL && curr->next != NULL)
        {
            curr -> next = reverse(curr -> next);
        }
    
        return prev;
    }
  • Vishal Sharma
    Vishal Sharma
    Nikumbh
    Another question : Write a program to sort the elements of an array, the first half of the array should be sorted ascending, the second half of the array should be sorted descending..

    ie., a[]={9,2,3,7,4,5,6,3,8,2}

    the resultant a[]={2,3,4,7,9,8,6,5,3,2}
    #include
    int main() {
        int a[10];
        int n,mid;
        printf("Enter num : ");
        scanf("%d",&n);
        mid = n/2;
        for(int i = 0 ; i < n ; i++) {
            scanf("%d",&a[i]);
        }
        for(int i = 0 ; i < mid ; i++) {
            for(int j = 0 ; j < mid ; j++) {
                if(a[i] < a[j]) {
                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
       
       
        for(int i = mid ; i < n ; i++) {
            for(int j = mid ; j < n ; j++) {
                if(a[i] > a[j]) {
                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
       
        for(int i = 0 ; i < n ; i++) {
            printf("%d ",a[i]);
        }
    }
  • Nikumbh
    Nikumbh
    Vishal0203
    I did this program using data structures long back! Here it is!


    #include
    #include
    using namespace std;
    
    struct list
    {
        char c;
        struct list *next;
    };
    
    list *reverse(list *);
    
    int main()
    {
        string input = "you are a boy";
        list *curr = new list;
        list *head = NULL;
    
        for(int i = 0 ; i < input.size() ; i++)
        {
            if(i == 0)
            {
                curr -> c = input[i];
                curr -> next = NULL;
                head = curr;
            }
            else
            {
                list *temp = new list;
                temp -> c = input[i];
                temp -> next = NULL;
                curr -> next = temp;
                curr = temp;
            }
        }
    
        list *temp;
        temp = head;
        while(temp != NULL)
        {
            cout<c;
            temp = temp->next;
        }
    
        temp = reverse(head);
    
        cout<c;
            temp = temp->next;
        }
    }
    
    
    list * reverse(list *head)
    {
        list *curr = head;
        list *prev = NULL;
        list *last = head;
    
        while(curr!= NULL && curr->c != ' ')
        {
            list *nextnode = curr->next;
            curr->next = prev;
            prev = curr;
            curr = nextnode;
        }
    
        last->next = curr;
    
        if(curr != NULL && curr->next != NULL)
        {
            curr -> next = reverse(curr -> next);
        }
    
        return prev;
    }

    @#-Link-Snipped-# Great work buddy !
  • Vishal Sharma
    Vishal Sharma
    Nikumbh
    @#-Link-Snipped-# Great work buddy !
    thanks! 😛😁
  • Sanyam Khurana
    Sanyam Khurana
    Ok, answer what will be the output of the below mentioned code

    //assume all necessary header files added..
    void main()
    {
    char i=0;
    for(;i>=0;i++);
    printf("i=%d",i);
    getch();
    }
    
  • Jeffrey Arulraj
    Jeffrey Arulraj
    I think we will have output in the form of
    i=0
    i=1
    till
    i=255
    Sanyam Khurana
    Ok, answer what will be the output of the below mentioned code

    //assume all necessary header files added..
    void main()
    {
    char i=0;
    for(;i>=0;i++);
    printf("i=%d",i);
    getch();
    }
    
  • Sanyam Khurana
    Sanyam Khurana
    Jeffrey Samuel
    I think we will have output in the form of
    i=0
    i=1
    till
    i=255

    You're wrong...

    Look at the question carefully, and if I say carefully, I mean it..

    In programming even a little thing have tremendous powers.. 😛
  • simplycoder
    simplycoder
    According to me, the output for this is specific to compiler.

    Case 1:
    When char is treated as signed char.
    It will print i=-128.
    For loop there has a semi-colon (😉
    loop would terminate after i=127
    thus when it would try to increment, cyclic property would then make it -128
    [Signed chars range from -128 to 127 ].

    Case 2:
    When char is treated as unsigned char,
    the for loop would never terminate causing an infinite loop.
    In this case, I would increment from 0 to 255 and then get reset to 0.
    thus the i>=0 condition would never fail.
    [Unsigned chars range from 0 to 255 ].
  • Sanyam Khurana
    Sanyam Khurana
    simplycoder
    According to me, the output for this is specific to compiler.

    Case 1:
    When char is treated as signed char.
    It will print i=-128.
    For loop there has a semi-colon (😉
    loop would terminate after i=127
    thus when it would try to increment, cyclic property would then make it -128
    [Signed chars range from -128 to 127 ].

    Case 2:
    When char is treated as unsigned char,
    the for loop would never terminate causing an infinite loop.
    In this case, I would increment from 0 to 255 and then get reset to 0.
    thus the i>=0 condition would never fail.
    [Unsigned chars range from 0 to 255 ].

    Yeah, you got it right mate..!! 😁
  • Jeffrey Arulraj
    Jeffrey Arulraj
    Sanyam Khurana
    You're wrong...

    Look at the question carefully, and if I say carefully, I mean it..

    In programming even a little thing have tremendous powers.. 😛
    Mate thank you for telling my error Now I understood it clearly

    I was wrong @#-Link-Snipped-# Awesome mate

    But will not the loop get terminated by the semicolon
    Then how will it be repeated that many times
  • Sanyam Khurana
    Sanyam Khurana
    Jeffrey Samuel
    But will not the loop get terminated by the semicolon
    Then how will it be repeated that many times
    This is an empty loop, so the loop would execute till the conditional statement is true, and as soon as it becomes false, as in case 1 told by simplycoder, the loop will end, and the last value of i would be printed.

    Ok, tell which one is better and also explain the reason.

    //1)version of program
    
    for(i=1;i<=1000;i++)
    {
    for(j=1;j<=100;j++)
    {
    printf("hi");
    }
    }
    
    
    // 2) version of Program
    
    for(i=1;i<=100;i++)
    {
    for(j=1;j<=1000;j++)
    {
    printf("Hi");
    }
    }
    Tell the output of the program with explanation.

    what will be d output of the following code??
    
    #include
    int main()
    {
    int a=3;
    a=a++ * a++ * a++;
    
    printf("a=%d",a);
    
    return 0;
    }
    Although these are not really tough and tricky one, but just for beginning sharing these..

    void main()
    {
    int a=1;
    while (a<=5)
    {
    printf("%d",a);
    if (a>2)
    goto here;
    a++;
    }
    }
    void fun()
    {
    here:
    printf("OMG");
    }
    Explain output with explanation of the above mentioned code..
  • rahul69
    rahul69
    Sanyam Khurana
    Ok, tell which one is better and also explain the reason.

    //1)version of program
    
    for(i=1;i<=1000;i++)
    {
    for(j=1;j<=100;j++)
    {
    printf("hi");
    }
    }
    
    
    // 2) version of Program
    
    for(i=1;i<=100;i++)
    {
    for(j=1;j<=1000;j++)
    {
    printf("Hi");
    }
    }
    IMO second code is better, as it will have less time complexity
    For first one, in the inner loop 100 statements for entering inside the loop and one statement for exiting the inner loop, so total inner statements= 100+1=101, now these multiplied by outer loop ie 101 * 1000 = 101000
    Similarly For second one, 1001 * 100 =100100
    so second one is better!
    Sanyam Khurana
    Tell the output of the program with explanation.

    what will be d output of the following code??
    
    #include
    int main()
    {
    int a=3;
    a=a++ * a++ * a++;
    
    printf("a=%d",a);
    
    return 0;
    }
    Post Increment ! ie use then change, so used as 3*3*3=27 👍
  • Sanyam Khurana
    Sanyam Khurana
    Adding some more output questions..

    Explain the output of the program

    void main()
    {
    char *p;
    p="Hello";
    printf("%c\n",*&*p);
    getch();
    }



    Show the output and also explain the reason behind your output

    #include
    int main()
    {
    char a,b;
    printf("%d ",12);
    printf("%d ",143);
    printf("%d ",scanf("%d%d",&a,&b));
    }
    Adding one more tricky question....

    Write a PROGRAM to find a number is EVEN OR ODD without using any control construct(if,switch,loop) , relational operators and ternary operators.
  • Vishal Sharma
    Vishal Sharma
    Sanyam Khurana
    Adding one more tricky question....

    Write a PROGRAM to find a number is EVEN OR ODD without using any control construct(if,switch,loop) , relational operators and ternary operators.
    #include
    
    int main() {
        int x;
        scanf("%d",&x);
        ((x%2)&1 && printf("odd"))||printf("even");
    }
  • Aadit Kapoor
    Aadit Kapoor
    #include
    int main()
    {
    char print[100] = "HelloWorld";
    int i;
    for (i=0;i<99;i++)
    {
    printf("%c\n",print);
    }
    }
  • Aadit Kapoor
    Aadit Kapoor
    #include
    int main()
    {
    char print[100] = "HelloWorld";
    int i;
    for (i=0;i<99;i++)
    {
    printf("%c\n",print);
    }
    }

    ITS PRINT
  • Aadit Kapoor
    Aadit Kapoor
    Why is this website not accepting array sign?
  • Aadit Kapoor
    Aadit Kapoor
    Sanyam Khurana
    Show the output and also explain the reason behind your output

    #include
    int main()
    {
    char a,b;
    printf("%d ",12);
    printf("%d ",143);
    printf("%d ",scanf("%d%d",&a,&b));
    }
    The output will be 12 and 143.
    then if we type two char's then it will give the value accordingly.I think it will give the asci value of the char's
  • Aadit Kapoor
    Aadit Kapoor
    Sanyam Khurana
    Adding one more tricky question....

    Write a PROGRAM to find a number is EVEN OR ODD without using any control construct(if,switch,loop) , relational operators and ternary operators.
    #include
    int main()
    {
    int i;
    printf("Enter a number:\n");
    scanf("%d",&i);

    int y = i % 2;
    printf("%d\n",y);
    }
    if y = 1 then it is odd.
    if y = 0 then it is even.
  • Vishal Sharma
    Vishal Sharma
    Aadit Kapoor
    The output will be 12 and 143.
    then if we type two char's then it will give the value accordingly.I think it will give the asci value of the char's
    it doesn't give the ascii value.. if you look at the declaration, a and b are characters but in scanf() we ask for an integer (presence of %d) hence if you enter 2 characters there, the printf() will print zero as it expects an integer not character! and if you enter two integer values, it'll print 2 because scanf returns the number of inputs it takes!
  • Aadit Kapoor
    Aadit Kapoor
    Thank you for correcting me
  • Aadit Kapoor
    Aadit Kapoor
    Sanyam Khurana
    Although these are not really tough and tricky one, but just for beginning sharing these..

    void main()
    {
    int a=1;
    while (a<=5)
    {
    printf("%d",a);
    if (a>2)
    goto here;
    a++;
    }
    }
    void fun()
    {
    here:
    printf("OMG");
    }
    Explain output with explanation of the above mentioned code..
    There will be no output. An error would be generated
  • Sanyam Khurana
    Sanyam Khurana
    Aadit Kapoor
    The output will be 12 and 143.
    then if we type two char's then it will give the value accordingly.I think it will give the asci value of the char's
    It would print 12143 and then something else, and that's what the tricky part is here..

    So think carefully and try again...

    Aadit Kapoor
    There will be no output. An error would be generated
    What kind of error, explain it in detail, so that others can also learn from this..

    If there's an output, explain how you came to that conclusion and if there's an error, explain why error is there.

    Aadit Kapoor
    #include
    int main()
    {
    char print[100] = "HelloWorld";
    int i;
    for (i=0;i<99;i++)
    {
    printf("%c\n",print);
    }
    }
    I think this would print only H 99 times, as you have given print in the statement so array is always taken as a pointer to the first element, so only H will be printed.

    Ok, here's another one..

    What will the output of the following C++ code be?

    #include
    using namespace std;
    
    void check_arr_size(int array[20]); //Function Prototype
    
    int main()
    {
    int array[20];
    cout << "In main: size of array - " << sizeof(array) << endl;
    check_arr_size(array);
    return 0;
    }
    
    void check_arr_size(int array[20]) //Function definition
    {
    cout << "Inside function: size of array - " << sizeof(array) << endl;
    }
  • Aadit Kapoor
    Aadit Kapoor
    Aadit Kapoor
    There will be no output. An error would be generated
    The error generated will be that no label has been defined.
  • Aadit Kapoor
    Aadit Kapoor
    Sanyam Khurana
    It would print 12143 and then something else, and that's what the tricky part is here..

    So think carefully and try again...


    What kind of error, explain it in detail, so that others can also learn from this..

    If there's an output, explain how you came to that conclusion and if there's an error, explain why error is there.


    I think this would print only H 99 times, as you have given print in the statement so array is always taken as a pointer to the first element, so only H will be printed.

    Ok, here's another one..

    What will the output of the following C++ code be?

    #include
    using namespace std;
    
    void check_arr_size(int array[20]); //Function Prototype
    
    int main()
    {
    int array[20];
    cout << "In main: size of array - " << sizeof(array) << endl;
    check_arr_size(array);
    return 0;
    }
    
    void check_arr_size(int array[20]) //Function definition
    {
    cout << "Inside function: size of array - " << sizeof(array) << endl;
    }
    I know the output but i can't understand.Can you tell me please?
  • Sanyam Khurana
    Sanyam Khurana
    #define int char
    void main()
    {
    int i=65;
    printf("sizeof(i)=%d",sizeof(i));
    getch();
    }

    write output with explaination.
  • Aadit Kapoor
    Aadit Kapoor
    Sanyam Khurana
    #define int char
    void main()
    {
    int i=65;
    printf("sizeof(i)=%d",sizeof(i));
    getch();
    }

    write output with explaination.
    There wil be no output because in '#define int char' we cannot use use int and char because it is a keyword
  • Aadit Kapoor
    Aadit Kapoor
    #include 
    #include 
    void add(int *);
    int main()
    {
    int x = 12;
    int *p = &x;
    int **c = &p;
    int ***f  = &c;
    int ****d = &p;
    x++;
    printf("**f = *p + x\n");
    ***f = *p + x;
    printf("Now printing **c\n");
    printf("%d\n",**c);
    printf("Allocting memory!\n");
    int *ptr = (int *)malloc(sizeof(***f));
    if (*ptr == NULL)
    {
       printf("Error!\n");
    }
       int i;
       for (i=0;i<12;i++)
       {
       printf("Using add(int*) function\n");
       printf("Changing a value with 10-:\n");
       int a = 10;
       add(&a);
       printf("%d\n",a);
       }
    
       return 0;
    }
    void add(int *a)
    {
       *a = *a + 10;  
    }
    
    
    what is the ouput?
  • vaibhav bhanawat
    vaibhav bhanawat
    #include
    #include
    void main()
    {
    clrscr();
    int large[5]={4,2,1,3,5};
    int i,j,p,q;
    p=large[0];
    for(i=1;i<5;i++)
    {
    if(p)
    p=large;
    }
    q=large[0];
    for(i=0;i<5;i++)
    {
    if(q>large)
    q=large;
    }
    printf("biggest number in given array is: %d\nsmallest number is%d",p,q);
    getch();
    }
    answer of ur question is.......!!!!!!!!
    here is an code for largest and smallest number from an array.....
  • vaibhav bhanawat
    vaibhav bhanawat
    write a program to print 1 to 100 number ......!
    without using loops and also without goto statement......!
  • vaibhav bhanawat
    vaibhav bhanawat
    FIND FRACTIONAL POWER OF A NUMBER WITHOUT USING ANY PREDEFINED FUNCTION IN C
    don't use pow function.......
  • vaibhav bhanawat
    vaibhav bhanawat
    A program to calculate the area of any 2D geometrical figure when proper inputs are provided.
  • Jeffrey Arulraj
    Jeffrey Arulraj
    vaibhav bhanawat
    for(i=1;i<5;i++)
    {
    if(p)
    p=large;
    }
    q=large[0];
    for(i=0;i<5;i++)
    {
    if(q>large)
    q=large;
    }


    answer of ur question is.......!!!!!!!!
    here is an code for largest and smallest number from an array.....
    It will show error in this segment
    I am sure that you will have to specify the location of the element in the array as well when you are comparing

    So this has to be

    if(p)
  • Aadit Kapoor
    Aadit Kapoor
    Hey Vaibhav in which year you are in?
  • rahul69
    rahul69
    Sanyam Khurana
    What will the output of the following C++ code be?

    #include
    using namespace std;
    
    void check_arr_size(int array[20]); //Function Prototype
    
    int main()
    {
    int array[20];
    cout << "In main: size of array - " << sizeof(array) << endl;
    check_arr_size(array);
    return 0;
    }
    
    void check_arr_size(int array[20]) //Function definition
    {
    cout << "Inside function: size of array - " << sizeof(array) << endl;
    }
    Output will be compiler dependent. Inside main() the size of array will be printed, ie 20*sizeof(int) {integer size, dependent on compiler 😨}
    Inside the function, as arrays are passed by reference (C++) so it will print the size of pointer, which is of integer type hence size is sizeof(int)
    {again dependent on compiler}
    😀.
    So if I am using a 32 bit compiler, the two sizes should be 80 and 4 respectively.
    😀
  • Sanyam Khurana
    Sanyam Khurana
    What will be the output of following Java Code fragment?

    String str1 = "abc:5";
    String str2 = "abc:5";
    String str3 = "abc:"+5;
    String str4 = "abc:"+(1+4);
    String str5 = "abc:"+str1.length();
    System.out.println(str1 == str1);
    System.out.println(str1 == str2);
    System.out.println(str1 == str3);
    
    System.out.println(str1 == str4);
    System.out.println(str1 == str5);
    System.out.println(str1 == new String(str1));
  • rahul69
    rahul69
    vaibhav bhanawat
    write a program to print 1 to 100 number ......!
    without using loops and also without goto statement......!
    #include
    using namespace std;
    int fun(int i)
    {
    if(i==101)
    return 1;
    cout<Using no loops here, but recursion 😀
                                        
  • Sanyam Khurana
    Sanyam Khurana
    vaibhav bhanawat
    A program to calculate the area of any 2D geometrical figure when proper inputs are provided.
    Could you please elaborate this?

    may be giving some example problem, and what is needed would be helpful and appreciated.

    Does we have to let user choose, what figure he wants and then accept the related data or something else is required to be done here?
  • Sanyam Khurana
    Sanyam Khurana
    rahul69
    Output will be compiler dependent. Inside main() the size of array will be printed, ie 20*sizeof(int) {integer size, dependent on compiler 😨}
    Inside the function, as arrays are passed by reference (C++) so it will print the size of pointer, which is of integer type hence size is sizeof(int)
    {again dependent on compiler}
    😀.
    So if I am using a 32 bit compiler, the two sizes should be 80 and 4 respectively.
    😀
    But then shouldn't it be 40 and 2 respectively?

    first, 20*(sizeof(int)) =40 and inside the function, the size of pointer ie. 2 bytes..

    Plus, I have a doubt, someone told be that all types of pointer occupy same memory space ie 2 bytes, whether it's integer type, float type, or any other. Is it true?
  • Jeffrey Arulraj
    Jeffrey Arulraj
    Sanyam Khurana
    Plus, I have a doubt, someone told be that all types of pointer occupy same memory space ie 2 bytes, whether it's integer type, float type, or any other. Is it true?
    No Pointers get allocated only when they get defined

    Their defnition will determine their size. If a pointer is declared as a Char it will use 1 bit and for float it uses 4 bit once it is defined for a float variable
  • Sanyam Khurana
    Sanyam Khurana
    Jeffrey Samuel
    No Pointers get allocated only when they get defined

    Their defnition will determine their size. If a pointer is declared as a Char it will use 1 bit and for float it uses 4 bit once it is defined for a float variable
    And what about Generic Pointers?

    Do they have a size of zero when unallocated to any memory location?
    or get highest size of data type?
  • Jeffrey Arulraj
    Jeffrey Arulraj
    Pointer gets allocated only if it points to a data location

    And Generic pointer if it is not pointing to any data type it will have zero bytes and it will take the size of the data it is pointing to

    Hope I am clear here
  • Sanyam Khurana
    Sanyam Khurana
    Jeffrey Samuel
    Pointer gets allocated only if it points to a data location

    And Generic pointer if it is not pointing to any data type it will have zero bytes and it will take the size of the data it is pointing to

    Hope I am clear here
    Ok, thanks mate for clearing this..!

    __________________________________________________________________

    Adding one more question
    Write a Program to generate all combination of 3 no. entered by user..
    eg. if 1 2 and 3 are entered then output should be..

    123
    132
    213
    231
    312
    321
  • vaibhav bhanawat
    vaibhav bhanawat
    after printing the data in file in file hand
    Sanyam Khurana
    Could you please elaborate this?

    may be giving some example problem, and what is needed would be helpful and appreciated.

    Does we have to let user choose, what figure he wants and then accept the related data or something else is required to be done here?
    yes its user choose
    we have to find any polygon area....we have to given certain co ordinates or information regarding the area...
  • vaibhav bhanawat
    vaibhav bhanawat
    in file handling fputs converts \n to \r\n why......?????????????
    whats the need to do these.....
    but if we read the same line using fgets the reverse conversion happens....???????
    give the suitable answer.....
  • Sanyam Khurana
    Sanyam Khurana
    vaibhav bhanawat
    after printing the data in file in file hand

    yes its user choose
    we have to find any polygon area....we have to given certain co ordinates or information regarding the area...
    Ok, here it is..

    #include
    #include
    void main()
    {
    float n,s,r,area;
    cout<<"Enter sides of polygon";
    cin>>n;
    cout<<"\n Enter length of the side";
    cin>>s;
    cout<<"\n Enter Apothem";
    cin>>r;
    area=0.5*n*s*r;
    cout<<"Area of the Polygon is "<
                                        
  • vaibhav bhanawat
    vaibhav bhanawat
    rahul69
    #include
    using namespace std;
    int fun(int i)
    {
    if(i==101)
    return 1;
    cout<Using no loops here, but recursion 😀
    here is more easy one .........
    #include
    #include
    void main()
    {
    extern int i;
    if(i<=100)
    {
    printf("%d\n",i++);
    main();
    }
    else
    getch();
    }
    int i=0;
  • Sanyam Khurana
    Sanyam Khurana
    Aadit Kapoor
    I know the output but i can't understand.Can you tell me please?
    It would print 12143 and then 2 after this, so the output will be actually 121432.

    This is because, in the last statement, we have scanf function inside the printf function, so it would actually print the no. of variables ie 2 inside scanf .
  • Sanyam Khurana
    Sanyam Khurana
    Write the output of the below given code fragment and explain reason for the output too...

    #include
    #include
    void main()
    {
    clrscr();
    int i=10, j=2;
    int *ip= &i, *jp = &j;  //Pointers to hold address of i and j
    int k = *ip/*jp;
    printf(“%d”,k);
    getch();
    }
    
    
  • Aadit Kapoor
    Aadit Kapoor
    Sanyam Khurana
    Write the output of the below given code fragment and explain reason for the output too...

    #include
    #include
    void main()
    {
    clrscr();
    int i=10, j=2;
    int *ip= &i, *jp = &j;  //Pointers to hold address of i and j
    int k = *ip/*jp;
    printf(“%d”,k);
    getch();
    }
    
    

    Ouput = 5
    *ip = 10
    *jp = 2

    k = 10 / 2
    The '*" sign means value at address so
    k = 10/2
    k = 5
  • Sanyam Khurana
    Sanyam Khurana
    Explain output of this code fragment

    This question should be consider to be in C language (not C++)

    void main()
    {
    int a=10,b=20,max;
    max=maximum(a,b);
    printf("maximum=%d",max);
    getch();
    }
    int maximum(int a,int b)
    {
    return a*(a>b)+b*(b>a);
    }
    Aadit Kapoor
    Ouput = 5
    *ip = 10
    *jp = 2

    k = 10 / 2
    The '*" sign means value at address so
    k = 10/2
    k = 5
    No, you're wrong, it's not that easy, have a look at it carefully.
  • Aadit Kapoor
    Aadit Kapoor
    Sanyam Khurana
    Explain output of this code fragment

    This question should be consider to be in C language (not C++)

    void main()
    {
    int a=10,b=20,max;
    max=maximum(a,b);
    printf("maximum=%d",max);
    getch();
    }
    int maximum(int a,int b)
    {
    return a*(a>b)+b*(b>a);
    }

    No, you're wrong, it's not that easy, have a look at it carefully.
    The answer is correct if you do not believe me,try compiling the code in c
  • Sanyam Khurana
    Sanyam Khurana
    Aadit Kapoor
    The answer is correct if you do not believe me,try compiling the code in c
    First, I would like to know which compiler you are using?
    Second, don't just use any compiler, if you don't do it yourself, then there's no use (Personal Opinion)
    Third, Output will be:
    Compiler Error: “Unexpected end of file in comment started in line 7”.
    Explanation:
    The programmer intended to divide two integers, but by the “maximum munch” rule, the compiler treats the operator sequence / and * as /* which happens to be the starting of comment. To force what is intended by the programmer,
    int k = *ip/ *jp;
    // give space explicity separating / and *
    //or
    int k = *ip/(*jp);
    // put braces to force the intention
  • Vishal Sharma
    Vishal Sharma
    vaibhav bhanawat
    write a program to print 1 to 100 number ......!
    without using loops and also without goto statement......!
    #include
    int main() {
        static int i = 1;
        printf("%7d",i);
        i++;
        if(i <= 100)
            main();
        else
            return 0;
    }
  • Sanyam Khurana
    Sanyam Khurana
    Adding few more questions,

    Write a Program that divides two numbers without using / operator and also print it's remainder.

    Write the output of the following code fragment


    #define int char
    void main()
    {
    int i=65;
    printf("sizeof(i)=%d",sizeof(i));
    getch();
    }
    
    Write a PROGRAM to find out square root of a number without using sqrt function.
  • Jeffrey Arulraj
    Jeffrey Arulraj
    Sanyam Khurana
    Adding few more questions,

    Write the output of the following code fragment


    #define int char
    void main()
    {
    int i=65;
    printf("sizeof(i)=%d",sizeof(i));
    getch();
    }
    
    Is the answer something like
    sizeof(i)=2

    Cos integer is 2 bit large and so expecting the answer to be 2
  • Vishal Sharma
    Vishal Sharma
    Jeffrey Samuel
    Is the answer something like
    sizeof(i)=2

    Cos integer is 2 bit large and so expecting the answer to be 2
    nope! it'll be 1
  • Sanyam Khurana
    Sanyam Khurana
    Jeffrey Samuel
    Is the answer something like
    sizeof(i)=2

    Cos integer is 2 bit large and so expecting the answer to be 2
    Although you are close to the answer but this answer isn't right.

    Hint: Read the entire program carefully (from very first line to the very end), and I'm sure you'll come up with the right answer.

    One more question..
    int a;
    void main()
    {
    int a;
    printf("%d....%d",::a,a);
    getch();
    }
    Do it without using Compiler
    write output without explaination.


    Vishal0203
    nope! it'll be 1
    Absolutely Right..!
  • Jeffrey Arulraj
    Jeffrey Arulraj
    I got the reason why it must be one #define

    I missed it really a tricky one mate Thanks for this one
  • Vishal Sharma
    Vishal Sharma
    int a;
    void main()
    {
    int a;
    printf("%d....%d",::a,a);
    getch();
    }
    i think the answer will be 0....
    as a is global so initial value is zero and we are printing scope of a that is global a
    and the next a is local a viz not initialized so it'll be a garbage value
  • Sanyam Khurana
    Sanyam Khurana
    Vishal0203
    nope! it'll be 1
    Absolutely Right
    Jeffrey Samuel
    I got the reason why it must be one #define

    I missed it really a tricky one mate Thanks for this one
    Even I missed it mate, and the reason is it's not tricky, but we get so much excited, that in over excitement we don't look at the code properly and unfortunately do errors.

    Vishal0203
    i think the answer will be 0....
    as a is global so initial value is zero and we are printing scope of a that is global a
    and the next a is local a viz not initialized so it'll be a garbage value
    Yes, it will first print 0 because of global variables are initialised to zero, and then print some garbage value corresponding to the local variable a.
  • Aadit Kapoor
    Aadit Kapoor
    Sanyam Khurana
    First, I would like to know which compiler you are using?
    Second, don't just use any compiler, if you don't do it yourself, then there's no use (Personal Opinion)
    Third, Output will be:
    Compiler Error: “Unexpected end of file in comment started in line 7”.
    Explanation:
    The programmer intended to divide two integers, but by the “maximum munch” rule, the compiler treats the operator sequence / and * as /* which happens to be the starting of comment. To force what is intended by the programmer,
    int k = *ip/ *jp;
    // give space explicity separating / and *
    //or
    int k = *ip/(*jp);
    // put braces to force the intention
    I am using clang compiler.It is obvious that now one writes int k = *ip/*jp;
    Every programmer gives space.I am not using any compiler.I first posted the answer then when you told me it is wrong i checked it with a compiler.

    Sanyam Khurana
    Although you are close to the answer but this answer isn't right.

    Hint: Read the entire program carefully (from very first line to the very end), and I'm sure you'll come up with the right answer.

    One more question..
    int a;
    void main()
    {
    int a;
    printf("%d....%d",::a,a);
    getch();
    }
    Do it without using Compiler
    write output without explaination.



    Absolutely Right..!
    Basic rules:
    FIRST: C does not have :😔Scope resolution operator).
    SECOND: Please the full code.

    Aadit Kapoor
    Basic rules:
    FIRST: C does not have :😔Scope resolution operator).
    SECOND: Please the full code.
    The answer is garbage values for both of the a's
  • Vishal Sharma
    Vishal Sharma
    Basic rules:
    FIRST: C does not have :😔Scope resolution operator).
    SECOND: Please the full code.
    no one said that this thread is ONLY for C programming language
  • Aadit Kapoor
    Aadit Kapoor
    Vishal0203
    no one said that this thread is ONLY for C programming language
    I Agree,but we we can't write mixed code.We cannot mix C and C++.
  • Sanyam Khurana
    Sanyam Khurana
    Design a program to simulate a calculator, but wait, not that one with the old simple sweet switch case asking what you have to do with two values.

    Instead, we want something like this,

    Say, a person wants to add 5 to 6, so he would just write 5+6 on the console and he receives the output 11.

    Similarly for multiplication 5*6, should return 30 multiplying the two numbers.

    Likewise for division and subtraction.
  • Aadit Kapoor
    Aadit Kapoor
    Sanyam Khurana
    Design a program to simulate a calculator, but wait, not that one with the old simple sweet switch case asking what you have to do with two values.

    Instead, we want something like this,

    Say, a person wants to add 5 to 6, so he would just write 5+6 on the console and he receives the output 11.

    Similarly for multiplication 5*6, should return 30 multiplying the two numbers.

    Likewise for division and subtraction.
    #include
    #include
    #define CHECK_FOR_ZERO(x) { if (x==0) printf("Cannot divide by zero! ERROR 100\n"); exit(0);}
    /* A simple Calculator */
    /* Created by Aadit Kapoor */
    int main()
    {
    int check = 0; /* For while loop */
    while (check == 0)
    {
    int n,n2; /* Numbers */
    char op; /* Operator */
    printf("Enter numbers (type '0q0' to quit): ");
    scanf("%d%c%d",&n,&op,&n2); /* In form (number-operator-number) */
    if (op == '+')
    {
    printf("Calculated Result = %d\n",n + n2);
    }
    else if(op == '-')
    {
    printf("Calculated Result = %d\n",n-n2);
    }
    else if(op == '*')
    {
    printf("Calculated Result = %d\n",n * n2);
    }
    else if (op == '/')
    {
    CHECK_FOR_ZERO(n2); /* CHECK_FOR_ZERO(x) */
    printf("Calculated Result = %d\n",n / n2);
    }
    else if(n == 0 && op == 'q' && n2 == 0)
    {
    printf("Bye!\n");
    exit(0);
    }
    else
    {
    printf("Invalid operation!\n");
    printf("Try again!\n");
    }
    }
    return 0;
    }
  • Sanyam Khurana
    Sanyam Khurana
    Aadit Kapoor
    #include
    #include
    #define CHECK_FOR_ZERO(x) { if (x==0) printf("Cannot divide by zero! ERROR 100\n"); exit(0);}
    /* A simple Calculator */
    /* Created by Aadit Kapoor */
    int main()
    {
    int check = 0; /* For while loop */
    while (check == 0)
    {
    int n,n2; /* Numbers */
    char op; /* Operator */
    printf("Enter numbers (type '0q0' to quit): ");
    scanf("%d%c%d",&n,&op,&n2); /* In form (number-operator-number) */
    if (op == '+')
    {
    printf("Calculated Result = %d\n",n + n2);
    }
    else if(op == '-')
    {
    printf("Calculated Result = %d\n",n-n2);
    }
    else if(op == '*')
    {
    printf("Calculated Result = %d\n",n * n2);
    }
    else if (op == '/')
    {
    CHECK_FOR_ZERO(n2); /* CHECK_FOR_ZERO(x) */
    printf("Calculated Result = %d\n",n / n2);
    }
    else if(n == 0 && op == 'q' && n2 == 0)
    {
    printf("Bye!\n");
    exit(0);
    }
    else
    {
    printf("Invalid operation!\n");
    printf("Try again!\n");
    }
    }
    return 0;
    }
    Nice!
    But please place your quote in the quote tag always.
    Ok, one more quetion CEans..

    void main()
    {
    struct student
    {
    char name[30], rollno[6];
    }stud;
    FILE *fp = fopen(“somefile.dat”,”r”);
    while(!feof(fp))
    {
    fread(&stud, sizeof(stud), 1 , fp);
    puts( stud.name);
    }
    }
    Explain the output with explanation.
  • avii
    avii
    Print 1 to 100, without using loops, recursions in C.
  • Sanyam Khurana
    Sanyam Khurana
    avii
    Print 1 to 100, without using loops, recursions in C.
    Already solved here, by @#-Link-Snipped-# in post #123

    EDIT: Oops, my bad, it uses recursion.
    Can we use goto in this?
  • avii
    avii
    ^no. No go to also.
  • Vishal Sharma
    Vishal Sharma
    avii
    ^no. No go to also.
    Okay this is another way! it doesn't use goto, recursion, no loops!
    unlike my post #123, in this main() doesn't call itself, it is called by printer() so it doesn't use recursion!


    #include
    #include
    int printer();
    int i = 1;
    int main() {
        printf("%4d",i);
        printer();
    }
    
    int printer() {
        i++;
        if(i > 100)
            exit(0);
        main();
    }
  • Sanyam Khurana
    Sanyam Khurana
    Vishal0203
    Okay this is another way! it doesn't use goto, recursion, no loops!
    unlike my post #123, in this main() doesn't call itself, it is called by printer() so it doesn't use recursion!


    #include
    #include
    int printer();
    int i = 1;
    int main() {
        printf("%4d",i);
        printer();
    }
    
    int printer() {
        i++;
        if(i > 100)
            exit(0);
        main();
    }
    I couldn't find it how to do it, first I though it to have a class but then realised that it has to be in C. Very nice buddy, this idea didn't strike my mind, one function calling another one, and it's not recursion actually.

    Ok, here's some more questions !

    Write output of the below mentioned code fragment.

    #define swap1(a,b) a=a+b;b=a-b;a=a-b;
    main()
    {
    int x=5,y=10;
    swap1(x,y);
    printf("%d %d\n",x,y);
    swap2(x,y);
    printf("%d %d\n",x,y);
    }
    int swap2(int a,int b)
    { int temp;
    temp=a;
    b=a;
    a=temp;
    return 1 ;
    }
    
    Write output with explanation

    void main()
    {
    static int i=5;
    if(--i)
    {
    main();
    printf("%d ",i);
    }
    getch();
    }
    
  • Vishal Sharma
    Vishal Sharma
    #define swap1(a,b) a=a+b;b=a-b;a=a-b;
    main()
    {
    int x=5,y=10;
    swap1(x,y);
    printf("%d %d\n",x,y);
    swap2(x,y);
    printf("%d %d\n",x,y);
    }
    int swap2(int a,int b)
    { int temp;
    temp=a;
    b=a;
    a=temp;
    return 1 ;
    }
    Swap2 procedure is wrong... still, if we correct it, we'll get same answer printed on screen i.e. 10 5
    1st case we aren't defining new variables a and b hence x and y replace the a and b in 1st statement and the values get swapped to 10 and 5
    But, int second case the new values of x and y i.e 10 5 are passed which are stored in new variables a and b whose scope is only inside the swap2 block! Hence the values of a and b are swapped but not x and y hence again 10 5 is printed

    void main()
    {
    static int i=5;
    if(--i)
    {
    main();
    printf("%d ",i);
    }
    getch();
    }
    Pretty easy! only 1 point to remember... the control of program is always returned back to calling function after execution of the function! The if condition stands true for 4 times hence main is called 4 times.
    after the 4th call of main() the condition goes false hence the control is returned to the 4th main() and printf() is executed and it prints the value 0 (since value is decremented in condition check and finally becomes zero)
    after the execution of 4th main the control is returned to the 3rd main() as this was the calling function for main() and again it prints the value 0
    this goes on until we reach 1st main() which is parent of all and after execution of this the program stops with the output

    0 0 0 0
  • Vishal Sharma
    Vishal Sharma
    sad was getting bored so painted a pic to explain the second code 😛
    I don't know how much it explains though!
  • Gaurav Deshmukh
    Gaurav Deshmukh
    Decypher

    Alice and Bob are being held at Azkaban(Prison). They want to escape and join Dumbledore's Army.
    Alice wants to tell Bob about the details of the plan but wants to keep their escape plan from Dementors(the guards).
    So Alice encrypts the message before passing the chits to Bob's cell.
    However Bob was careless and he disposed the chits in his cell's waste paper bin.
    The clever Dementor found the chits but couldn't make out what they said.
    So he hired a computer programmer to decode the message for him. Please help the Dementor to decypher the message.

    The code key that Alice used for this simple coding is a one for one character substitution based upon a single arithmetic
    manipulation of the printable portion of the ASCII character set.

    INPUT
    The Encrypted message in a single line. The maximum number of charaters in a message is 100.
    (DO NOT PRINT ANY PROMPT MESSAGE TO ENTER THE ENCRYPTED MESSAGE.)

    OUTPUT
    The decrypted message in a single line. (Do not print any other message other than the decrypted message.)

    SAMPLE INPUT 1
    [YHUZMVYT'[V'HUPTHN\Z'MVYT3

    SAMPLE OUTPUT 1
    TRANSFORM TO ANIMAGUS FORM,

    SAMPLE INPUT 2
    HUK'LZJHWL'^OLU'[OL`'IYPUN'MVVK5

    SAMPLE OUTPUT 2
    AND ESCAPE WHEN THEY BRING FOOD.
  • rahul69
    rahul69
    Gaurav v. Deshmukh
    Decypher

    Alice and Bob are being held at Azkaban(Prison). They want to escape and join Dumbledore's Army.
    Alice wants to tell Bob about the details of the plan but wants to keep their escape plan from Dementors(the guards).
    So Alice encrypts the message before passing the chits to Bob's cell.
    However Bob was careless and he disposed the chits in his cell's waste paper bin.
    The clever Dementor found the chits but couldn't make out what they said.
    So he hired a computer programmer to decode the message for him. Please help the Dementor to decypher the message.

    The code key that Alice used for this simple coding is a one for one character substitution based upon a single arithmetic
    manipulation of the printable portion of the ASCII character set.

    INPUT
    The Encrypted message in a single line. The maximum number of charaters in a message is 100.
    (DO NOT PRINT ANY PROMPT MESSAGE TO ENTER THE ENCRYPTED MESSAGE.)

    OUTPUT
    The decrypted message in a single line. (Do not print any other message other than the decrypted message.)

    SAMPLE INPUT 1
    [YHUZMVYT'[V'HUPTHN\Z'MVYT3

    SAMPLE OUTPUT 1
    TRANSFORM TO ANIMAGUS FORM,

    SAMPLE INPUT 2
    HUK'LZJHWL'^OLU'[OL`'IYPUN'MVVK5

    SAMPLE OUTPUT 2
    AND ESCAPE WHEN THEY BRING FOOD.
    Easy enough!
    Here's the solution:
    #include
    #define max 100
    using namespace std;
    main()
    {
    int i;      
    char a[max];
    cin>>a;
    for(i=0;a[i]!='\0';i++)
    a[i]-=7;
    cout<
                                        
  • Vishal Sharma
    Vishal Sharma
    Gaurav v. Deshmukh
    Decypher

    Alice and Bob are being held at Azkaban(Prison). They want to escape and join Dumbledore's Army.
    Alice wants to tell Bob about the details of the plan but wants to keep their escape plan from Dementors(the guards).
    So Alice encrypts the message before passing the chits to Bob's cell.
    However Bob was careless and he disposed the chits in his cell's waste paper bin.
    The clever Dementor found the chits but couldn't make out what they said.
    So he hired a computer programmer to decode the message for him. Please help the Dementor to decypher the message.

    The code key that Alice used for this simple coding is a one for one character substitution based upon a single arithmetic
    manipulation of the printable portion of the ASCII character set.

    INPUT
    The Encrypted message in a single line. The maximum number of charaters in a message is 100.
    (DO NOT PRINT ANY PROMPT MESSAGE TO ENTER THE ENCRYPTED MESSAGE.)

    OUTPUT
    The decrypted message in a single line. (Do not print any other message other than the decrypted message.)

    SAMPLE INPUT 1
    [YHUZMVYT'[V'HUPTHN\Z'MVYT3

    SAMPLE OUTPUT 1
    TRANSFORM TO ANIMAGUS FORM,

    SAMPLE INPUT 2
    HUK'LZJHWL'^OLU'[OL`'IYPUN'MVVK5

    SAMPLE OUTPUT 2
    AND ESCAPE WHEN THEY BRING FOOD.
    this was asked in aspirations exam today 😛
  • Sanyam Khurana
    Sanyam Khurana
    Give the output with explanation :

    void main()
    {
    int i=1,j=2;
    switch(i)
    {
    case 1: printf("GOOD");
    break;
    case j: printf("BAD");
    break;
    }
    getch();
    }

    Write a function ``replace'' which takes a pointer to a string as a parameter, which replaces all spaces in that string by minus '-' signs, and delivers the number of spaces it replaced.
    Thus

    char *cat = "The cat sat";
    n = replace( cat );
    should set
    cat to "The-cat-sat"
    and
    n to 2.
  • vaibhav bhanawat
    vaibhav bhanawat
    if i want to convert C code into setup file than what should i do
    C code convert into software .....
    that converted setup we can installed in any PC
  • Aadit Kapoor
    Aadit Kapoor
    vaibhav bhanawat
    if i want to convert C code into setup file than what should i do
    C code convert into software .....
    that converted setup we can installed in any PC
    You can use visual studio to convert a project into an installer.
  • Aadit Kapoor
    Aadit Kapoor
    void Forgot_code(struct inventory *v2)
    {
        signed int x;
        printf("Forgot your password started!\n");
        while(1)
    {
        printf("Type this captcha to begin\n");
        printf("Captcha :  2x + 12 = 3x + 23\t Find x!");
        scanf("%d",&x);
        if (x == -11)
        {
            struct inventory *size_for_read_check_info =(struct inventory*)malloc(sizeof(struct inventory *));
            printf("Changing unlock code to the default unlock code\n");
            size_for_read_check_info->unlock_code = 1212;
            printf("%d\n",size_for_read_check_info->unlock_code );
            Read_Check_information(&size_for_read_check_info);
            break;
        }
        else
        {
            printf("Try again!\n");
        }
    }   
    

    void Read_Check_information(struct inventory *v3)
    {
        char check_name[32];
        int check_value;
        int check_code;
        printf("Enter your name:\n");
        scanf("%s",&check_name);
        printf("Input your UNLOCK LOCK CODE (type '203' to reset!\n");
        scanf("%d",&check_code);
        if (strcmp(check_name,v3->name_of_owner) == 0 && check_code == v3->unlock_code)
        {
            printf("Welcome!\n");
    
        }
        else if (check_code == 203)
        {
            struct inventory *size_for_forgot_code = (struct inventory *)malloc(sizeof(struct inventory *));
            Forgot_code(&size_for_forgot_code);
            free(size_for_forgot_code);
        }
        else
        {
            system("clear");
            printf("Error 444!\n");
            exit(0);
        }
    
    }

    In the forgot_code function the size_for_check_info unlock code is changing to 1212 but why my Read_Check_information not changing the unlock code.
  • Aadit Kapoor
    Aadit Kapoor
    #include 
    #include 
    #define MAX 100
    
    void Start_Processing()
    {
        char dot  = '.';
        int i;
        printf("Storing password");
        for (i=0;i<10;i++)
        {
            printf("%c",dot);
            Sleep(1000);
        }
    }
    void Display_password(char pass_d[MAX])
    {
        printf("Your password is %s\n",pass_d);
    }
    void getpassword(char pass[MAX])
    {
        int num_of_char;
        printf("How many characters are there in your password?\n");
        scanf("%d",&num_of_char);
    
        int i;
        printf("Enter your desired password:\n");
        for (i=0;i


    A simple password program.
    Complied with gcc
    any suggestions please post!
  • Vishal Sharma
    Vishal Sharma
    Write a program to find longest alphabatecial ordered substring of a given string

    Ex given string is "abcdabf"
    Longest substring is "abcd"

    Ex2 S-"abadghacr"
    Ans-adgh
    In case of ties
    Print the first one

    Ex3-S-"abcbcd"
    Ans-abc
  • Sanyam Khurana
    Sanyam Khurana
    Write the output of the below mentioned code fragment.

    void main()
    {
    static char s[] = "Hello!";
    printf("%d\n", *(s+strlen(s)));
    getch();
    }
    Assume all the necessary header files included.
  • Aadit Kapoor
    Aadit Kapoor
    Can someone explain 2 dimensional and 3 dimensional arrays in c?
  • Aadit Kapoor
    Aadit Kapoor
    Sanyam Khurana
    Give the output with explanation :

    void main()
    {
    int i=1,j=2;
    switch(i)
    {
    case 1: printf("GOOD");
    break;
    case j: printf("BAD");
    break;
    }
    getch();
    }
    OUTPUT : GOOD
    because int i = 1
    case 1: i is already one then it will print GOOD.
  • Aadit Kapoor
    Aadit Kapoor
    Aadit Kapoor
    OUTPUT : GOOD
    because int i = 1
    case 1: i is already one then it will print GOOD.
    OH SORRY!
    OUPUT IS ERROR!
    because case accepts only chars,strings,integers BUT NO variable.
  • Sanyam Khurana
    Sanyam Khurana
    Why is this thread dead 😲😔
    Isn't there anyone to share & try out stuff.. 😭
  • Abhishek Rawal
    Abhishek Rawal
    Sanyam Khurana
    Why is this thread dead 😲😔
    Isn't there anyone to share & try out stuff.. 😭
    Okay, here you go then : #-Link-Snipped-#
    Take a look at bugs we are having, fix it up, upstream the patch, claim your bounty.
    For example Bug #1073426 “Dock disappears after a short amount of use.” : Bugs : Plank ,fix it & claim the bounty. Good way to earn money & learn something new & challenging.
  • Sanyam Khurana
    Sanyam Khurana
    Abhishek Rawal
    Okay, here you go then : #-Link-Snipped-#
    Take a look at bugs we are having, fix it up, upstream the patch, claim your bounty.
    For example Bug #1073426 “Dock disappears after a short amount of use.” : Bugs : Plank ,fix it & claim the bounty. Good way to earn money & learn something new & challenging.
    Not into Linux so much :/

    But I would try & see this.
  • Vishal Sharma
    Vishal Sharma
    An array consists of binary number, swap all 0's to the end.
    Example : 100110111101 gives 111111110000
  • avii
    avii
    Vishal0203
    An array consists of binary number, swap all 0's to the end.
    Example : 100110111101 gives 111111110000
    binstring = '1010101010'
    newstring = '1'*(len(binstring) - binstring.count('0')) + '0'* binstring.count('0')
  • Vishal Sharma
    Vishal Sharma
    avii
    binstring = '1010101010'
    newstring = '1'*(len(binstring) - binstring.count('0')) + '0'* binstring.count('0')
    i'd appreciate a solution in C. And, convert the same input string instead of using a new one
  • avii
    avii
    ^I don't like C. So used Python. and strings are immutable in python, so its not possible to 'convert' it
  • Vishal Sharma
    Vishal Sharma
    avii
    ^I don't like C. So used Python. and strings are immutable in python, so its not possible to 'convert' it
    I know python strings are immutable, I mentioned the conversion for C. Python also provides a bunch of predefined functions which are so good that you don't actually need to think much whereas C makes you think and that is what expected. I would not like to continue the discussion over the strength of programming language. Anyway, let someone else answer it in C!
  • Harshad Italiya
    Harshad Italiya
    Vishal0203
    An array consists of binary number, swap all 0's to the end.
    Example : 100110111101 gives 111111110000
    Array of binary number. Do you mean like this
    Array[]="10001101011101" ; 
  • durga ch
    durga ch
    avii's solution was best. but a non-pythonic way of doing it (elaborate).


    s = '100110111101'
    sn = '' # intiatize a new str
    for i in s:
    if i =='1':
    sn += i​
    sn += ('0' * (len(s) - len(sn)))
    prints '111111110000'
  • Harshad Italiya
    Harshad Italiya
    I am not sure if I understand your question properly but here is one lengthy code without thinking too much.

    #-Link-Snipped-#
    void main()
    {
        unsigned char tuArray[]="1110111";
        unsigned char tuArraySize;
        unsigned char tuCnt;
        unsigned char tuNoOfZero=0;
    
        tuArraySize = strlen(tuArray);
        //Findout no of Zero
        for(tuCnt=0; tuCnt
  • Vishal Sharma
    Vishal Sharma
    durga
    avii's solution was best. but a non-pythonic way of doing it (elaborate).


    s = '100110111101'
    sn = '' # intiatize a new str
    for i in s:
    if i =='1':
    sn += i​
    sn += ('0' * (len(s) - len(sn)))
    prints '111111110000'
    how about converting the same string to the required form?
  • Vishal Sharma
    Vishal Sharma
    Harshad Italiya
    I am not sure if I understand your question properly but here is one lengthy code without thinking too much.

    #-Link-Snipped-#
    void main()
    {
        unsigned char tuArray[]="1110111";
        unsigned char tuArraySize;
        unsigned char tuCnt;
        unsigned char tuNoOfZero=0;
    
        tuArraySize = strlen(tuArray);
        //Findout no of Zero
        for(tuCnt=0; tuCnt
    don't you think you made it more complicated? 😀 it can be done in one pass.. think that way!
  • Harshad Italiya
    Harshad Italiya
    Vishal0203
    don't you think you made it more complicated? 😀 it can be done in one pass.. think that way!
    It can be as I said I have not thought too much on that as I am not sure if I have understand your question properly. But Now I will try to get some easy way. 😀
  • durga ch
    durga ch
    not possible. That of code was made in python
    Vishal0203
    how about converting the same string to the required form?
  • Vishal Sharma
    Vishal Sharma
    Oh my god! I'll stop commenting
  • SurEC93
    SurEC93
    Hello all! The new version of forum is cool😀

    It's been a while I have practiced these kind of c programs.
    Below is one that I was trying.
    printing magic numbers: a magic no is a no that is same as the sum of factorials of its individual digits.
    (eg. 145= 1!+4!+5!)

    void main()
    {
    long int x,n,p,a[10],c,temp,q,sum,s[10];
    clrscr();
     
         for(x=1;x<=100;x++)            // checking for no.s from 1 to 100
        {
        c=0;
        sum=0;
        p=x;
        temp=x;
            while(temp!=0)            // to find no. of digits in no
            {
            temp=temp/10;
            c++;
            }
     
            for(n=1;n<=c;n++)
            {
            a[n]=x%10;
            x=x/10;                // separating the digits
            }
     
            for(n=c;n>0;n--)
            {
            s[n]=1;
                for(q=a[n];q>0;q--)        // eg 5 then it will run 5 4 3 2 1
                {
                s[n]=s[n]*q;        // finding factorial
                }
            sum=sum+s[n];            // taking sum of factoials eg. 1!+9!+5! for 195
            }
     
        if(p==sum)                // checking criteria
        {
        printf("%d \n",p);
        }
           }
    }
    Can't get what's wrong. Plz figure out.
  • Vishal Sharma
    Vishal Sharma
    SurEC93
    Hello all! The new version of forum is cool😀

    It's been a while I have practiced these kind of c programs.
    Below is one that I was trying.
    printing magic numbers: a magic no is a no that is same as the sum of factorials of its individual digits.
    (eg. 145= 1!+4!+5!)

    void main()
    {
    long int x,n,p,a[10],c,temp,q,sum,s[10];
    clrscr();
    
         for(x=1;x<=100;x++)            // checking for no.s from 1 to 100
        {
        c=0;
        sum=0;
        p=x;
        temp=x;
            while(temp!=0)            // to find no. of digits in no
            {
            temp=temp/10;
            c++;
            }
    
            for(n=1;n<=c;n++)
            {
            a[n]=x%10;
            x=x/10;                // separating the digits
            }
    
            for(n=c;n>0;n--)
            {
            s[n]=1;
                for(q=a[n];q>0;q--)        // eg 5 then it will run 5 4 3 2 1
                {
                s[n]=s[n]*q;        // finding factorial
                }
            sum=sum+s[n];            // taking sum of factoials eg. 1!+9!+5! for 195
            }
    
        if(p==sum)                // checking criteria
        {
        printf("%d \n",p);
        }
           }
    }
    Can't get what's wrong. Plz figure out.
    That's a very complicated code you've written and hence it doesn't interest me going through it.. Please divide your program in functions where it gets easy to go through (I haven't seen the code)
  • Harshad Italiya
    Harshad Italiya
    Vishal0203
    That's a very complicated code you've written and hence it doesn't interest me going through it.. Please divide your program in functions where it gets easy to go through (I haven't seen the code)
    Please share the solution for the previous question. I have not got chance to spend time on that but now I think it is time to post the solution.
  • Harshad Italiya
    Harshad Italiya
    #-Link-Snipped-# will you please share your solution for that 0-1 swapping code.
  • Vishal Sharma
    Vishal Sharma
    I'll lay the method here,
    Keep 2 pointers, 1 at the start and 1 at the end.
    compare, swap and increment/decrement (increment 1st pointer, decrement 2nd pointer) the pointers accordingly.
    This continues until 1st and 2nd pointers meet
  • durga ch
    durga ch
    that looks like a variation of quick sort to me, being language specific(python) ,, swapping a within a list is possible, that would need the str to be converted to a list though, I still don't know if the same string can be skimmed that way and be swapped, other python-enthusiasts might chip in.
  • Vishal Sharma
    Vishal Sharma
    According to me python makes life easy,
    And so coding these small problems in python doesn't improve thinking skills
  • durga ch
    durga ch
    I would disagree. Python has many inbuilt functions which makes life easy, but that does-not in anyway deter you from full-filling the requirement of your project. It helps in abstracting all complexities of a language and thus aiding in the user to focus on real problem and not language nauseas.
    for example - python network programming gives you the flexibility to code at a higher application layer or as low as socket layer, in sense it gives more choice of usage. Anyways, each to their own.

You are reading an archived discussion.

Related Posts

Here is your chance to express how addicted you are.I welcome all CEans to express how sticky you are in CE. First my turn: *I usually open fb , twitter...
So I bought a Western Digital (WD) My Passport 1TB external HDD from Flipkart and it arrived just a few moments ago. I quickly unboxed the drive and connected it...
what is the difference between project and product???.. can anybody tell main difference..
All of us at some point of time had watched cartoon network and animax especially at your childhood days but which cartoon do you miss very much? mine: *tom and...
while there is a elastic limit for tensile ,compressive and shear stresses, is there a elastic limit for thermal stress?where the solid comes back to its original state when the...