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.
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
-
aviiPlease explain me how does printing Hello World without semi colon improves my logic ?
-
Sanyam Khurana
Is not just about printing hello world but its more than thataviiPlease explain me how does printing Hello World without semi colon improves my logic ?
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
-> 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
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
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
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 SharmaAdding 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 KhuranaVishal0203
#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 SharmaSanyam KhuranaActually 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
I have designed this code for 10 elements and would work as given.Vishal0203Adding 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
#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
You need to swap the values instead of taking a separate array!Sanyam KhuranaI 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<
I mean the changes are to be made within the array which is used to take input from user -
Sanyam Khurana
Sorry, the question was actually that you don't have to use semi colon anywhere in the entire program. ๐Vishal0203I printed the statement without using semi colon. I don't think it needs to be pointed out
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...
Ok, will work on it..Vishal0203You 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 -
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
Ok, will work on it...Vishal0203You 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
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
I am just operating on the bits... I'll explain this in detail!Sanyam KhuranaOk, 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'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@#-Link-Snipped-# take time to read it and keep a paper and pen with you ๐
-
simplycoderSanyam KhuranaOk, 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.
I didn't find time to write a code, but here is an algorithm which I would use.Vishal0203Adding 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
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
I didn't find time to write a code, but here is an algorithm which I would use.
I think we can sort it normally!?
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 -
simplycoder
My bad, I have edited my previous post, your problem never said sorting, it was my wrong assumption, refer to above edited post.Vishal0203I think we can sort it normally!? -
Vishal Sharma
hehe but i gave an example ๐ anyway lets see if anyone tries your algorithm!simplycoderMy bad, I have edited my previous post, your problem never said sorting, it was my wrong assumption, refer to above edited post. -
Sanyam KhuranaOk, 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 KhuranaI 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 KhuranaOk, tell the output of this code
and reason too for your answer
#include
I know, vishal and crazycoder would immediately answer this.. ๐#include void main() { int a=-29, b=-3; printf('%d",a%b); getch(); } -
Vishal Sharma
I'm sorry but you need to swap...Sanyam KhuranaOk, 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< -
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
So lets wait for others to answer this! ๐Sanyam KhuranaOk, tell the output of this code
and reason too for your answer
#include
I know, vishal and crazycoder would immediately answer this.. ๐#include void main() { int a=-29, b=-3; printf('%d",a%b); getch(); } -
Vishal Sharma
umm... It gives the output but doesn't change the array... The question says "swap" , means the entire array will be modifiedsimplycoder@#-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
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
oops..Vishal0203I'm sorry but you need to swap...
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
means the same!Sanyam Khuranaoops..
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?๐
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
Its pretty simple if we think this as math question.Sanyam KhuranaOk, tell the output of this code
and reason too for your answer
#include
I know, vishal and crazycoder would immediately answer this.. ๐#include void main() { int a=-29, b=-3; printf('%d",a%b); getch(); }
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
Did I say these are kiddish ?Sanyam KhuranaIs 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.......
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:
This is 50th problem from project euler.
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?
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 RawalSee, 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
The prime 41, can be written as the sum of six consecutive primes:
the prime number is 9384209 ?????
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?
can anyone confirm this answer?? -
Abhishek RawalNope. Because 9,384,209 > 1,000,000.
-
Vishal Sharma
oh shit i took it for 10,000,000 ๐ my badAbhishek RawalNope. Because 9,384,209 > 1,000,000.
then is it 958577 ??? -
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.aviiDid 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.
Sorry, if you got offended. -
Vishal Sharma
it's okay guys forget about it!Sanyam KhuranaWhat 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.
and please confirm the answer i got? ๐ฒ -
Vishal Sharma
Answer to the above question!!Vishal0203Adding 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
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 KhuranaHere'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
Do you mean all a,b,c values above 100 and below 900 ?Sanyam KhuranaHere'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. -
Sanyam Khurana
Yes, we want Pythagorean Triplets..Vishal0203Do you mean all a,b,c values above 100 and below 900 ?
Which means you have to print all the three values between 100 to 900 ... -
Vishal Sharma
I dont think we have any triplet with all 3 numbers between 100 to 900Sanyam KhuranaYes, we want Pythagorean Triplets..
Which means you have to print all the three values 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 KhuranaFind the product of Pythagorean Triplet whose sum is 1000.
It's just unique.
PS: I just finished doing this one..! -
Sanyam Khurana
What I did for this one isSanyam KhuranaQ3. Write a Program to multiply two numbers without using "*" .
#include
#include void main() { int a,b,c; clrscr(); cout<<"Enter two numbers"; cin>>a>>b; for(i=0;i -
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
Yup you are right ...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
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 KhuranaAdding 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
It is printing triplets even like 3,4,5 and 5,12,13...Vishal0203I 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; }
We wanted from 100 to 900... -
rahul69Sanyam KhuranaHere'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
31875000?Sanyam KhuranaFind the product of Pythagorean Triplet whose sum is 1000.
It's just unique.
PS: I just finished doing this one..! -
Sanyam Khurana
Yes, that's correct..๐rahul6931875000?
and the triplets are
200, 375 and 425... -
Sanyam KhuranaAdding 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 KhuranaOne 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
Explain this mateSanyam KhuranaWrite a Program to find the largest palindrome is a string.
Largest palindrome is a string or in a string
A little confused here -
Sanyam Khurana
If you are given a string, which would contain a palindrome inside it ..you need to spot the biggest palindrome..Jeffrey SamuelExplain this mate
Largest palindrome is a string or in a string
A little confused here
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 Khuranaor 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 KhuranaHere'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 TiwariWhat 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
d) Won't compile,Shailaja TiwariWhat 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.
code would expect an object int x = int() = 3;
since this is not done, it would fail to compile throwing lvalue required error. -
Shailaja TiwariRight 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
Can we, however use conditional operators??Sanyam KhuranaHere'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..!! ๐ -
Sanyam Khurana
Can you please tell me, how this would expect an object, and what's the meaning of thissimplycoderd) 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.
Conditional Operators as in " ? : " ?rahul69Can we, however use conditional operators?? -
simplycoderSanyam KhuranaCan 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
Oh, I was just asking him about if he meant " ? : " as conditional operators ...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;
}
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; -
NikumbhSolution 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........ -
NikumbhVishal0203Adding 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........ -
NikumbhWrite 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"
-
NikumbhAnother 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
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 ๐Sanyam KhuranaCan you please tell me, how this would expect an object, and what's the meaning of this
Conditional Operators as in " ? : " ?
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
I did this program using data structures long back! Here it is!NikumbhWrite 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"
#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 SharmaNikumbhAnother 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]); } } -
NikumbhVishal0203I 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
thanks! ๐๐Nikumbh@#-Link-Snipped-# Great work buddy ! -
Sanyam KhuranaOk, 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 ArulrajI think we will have output in the form of
i=0
i=1
till
i=255
Sanyam KhuranaOk, 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 KhuranaJeffrey SamuelI 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.. ๐ -
simplycoderAccording 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 KhuranasimplycoderAccording 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
Mate thank you for telling my error Now I understood it clearlySanyam KhuranaYou're wrong...
Look at the question carefully, and if I say carefully, I mean it..
In programming even a little thing have tremendous powers.. ๐
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
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.Jeffrey SamuelBut will not the loop get terminated by the semicolon
Then how will it be repeated that many times
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
Although these are not really tough and tricky one, but just for beginning sharing these..int main() { int a=3; a=a++ * a++ * a++; printf("a=%d",a); return 0; }
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
IMO second code is better, as it will have less time complexitySanyam KhuranaOk, 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"); } }
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!
Post Increment ! ie use then change, so used as 3*3*3=27 ๐Sanyam KhuranaTell 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; } -
Sanyam KhuranaAdding 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
Adding one more tricky question....int main() { char a,b; printf("%d ",12); printf("%d ",143); printf("%d ",scanf("%d%d",&a,&b)); }
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 SharmaSanyam KhuranaAdding 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#include
int main()
{
char print[100] = "HelloWorld";
int i;
for (i=0;i<99;i++)
{
printf("%c\n",print);
}
} -
Aadit Kapoor#include
int main()
{
char print[100] = "HelloWorld";
int i;
for (i=0;i<99;i++)
{
printf("%c\n",print);
}
}
ITS PRINT -
Aadit KapoorWhy is this website not accepting array sign?
-
Aadit Kapoor
The output will be 12 and 143.Sanyam KhuranaShow 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)); }
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
#includeSanyam KhuranaAdding 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.
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
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 KapoorThe 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 KapoorThank you for correcting me
-
Aadit Kapoor
There will be no output. An error would be generatedSanyam KhuranaAlthough 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.. -
Sanyam Khurana
It would print 12143 and then something else, and that's what the tricky part is here..Aadit KapoorThe 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
So think carefully and try again...
What kind of error, explain it in detail, so that others can also learn from this..Aadit KapoorThere will be no output. An error would be generated
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.Aadit Kapoor#include
int main()
{
char print[100] = "HelloWorld";
int i;
for (i=0;i<99;i++)
{
printf("%c\n",print);
}
}
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
The error generated will be that no label has been defined.Aadit KapoorThere will be no output. An error would be generated -
Aadit Kapoor
I know the output but i can't understand.Can you tell me please?Sanyam KhuranaIt 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; } -
Sanyam Khurana
#define int char void main() { int i=65; printf("sizeof(i)=%d",sizeof(i)); getch(); }
write output with explaination. -
Aadit Kapoor
There wil be no output because in '#define int char' we cannot use use int and char because it is a keywordSanyam Khurana#define int char void main() { int i=65; printf("sizeof(i)=%d",sizeof(i)); getch(); }
write output with explaination. -
Aadit Kapoor
#include
what is the ouput?#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; } -
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 bhanawatwrite a program to print 1 to 100 number ......!
without using loops and also without goto statement......! -
vaibhav bhanawatFIND FRACTIONAL POWER OF A NUMBER WITHOUT USING ANY PREDEFINED FUNCTION IN C
don't use pow function....... -
vaibhav bhanawatA program to calculate the area of any 2D geometrical figure when proper inputs are provided.
-
Jeffrey Arulraj
It will show error in this segmentvaibhav bhanawatfor(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.....
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 KapoorHey Vaibhav in which year you are in?
-
rahul69
Output will be compiler dependent. Inside main() the size of array will be printed, ie 20*sizeof(int) {integer size, dependent on compiler ๐จ}Sanyam KhuranaWhat 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; }
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 KhuranaWhat 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));
-
rahul69vaibhav bhanawatwrite 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
Could you please elaborate this?vaibhav bhanawatA program to calculate the area of any 2D geometrical figure when proper inputs are provided.
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
But then shouldn't it be 40 and 2 respectively?rahul69Output 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.
๐
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
No Pointers get allocated only when they get definedSanyam KhuranaPlus, 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?
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
And what about Generic Pointers?Jeffrey SamuelNo 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
Do they have a size of zero when unallocated to any memory location?
or get highest size of data type? -
Jeffrey ArulrajPointer 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
Ok, thanks mate for clearing this..!Jeffrey SamuelPointer 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
__________________________________________________________________
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 bhanawatafter printing the data in file in file hand
yes its user chooseSanyam KhuranaCould 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?
we have to find any polygon area....we have to given certain co ordinates or information regarding the area... -
vaibhav bhanawatin 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
Ok, here it is..vaibhav bhanawatafter 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...
#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
here is more easy one .........rahul69#include
using namespace std; int fun(int i) { if(i==101) return 1; cout<Using no loops here, but recursion ๐
#include
#include
void main()
{
extern int i;
if(i<=100)
{
printf("%d\n",i++);
main();
}
else
getch();
}
int i=0; -
Sanyam Khurana
It would print 12143 and then 2 after this, so the output will be actually 121432.Aadit KapoorI know the output but i can't understand.Can you tell me please?
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 KhuranaWrite 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 KapoorSanyam KhuranaWrite 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 KhuranaExplain 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.Aadit KapoorOuput = 5
*ip = 10
*jp = 2
k = 10 / 2
The '*" sign means value at address so
k = 10/2
k = 5 -
Aadit Kapoor
The answer is correct if you do not believe me,try compiling the code in cSanyam KhuranaExplain 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. -
Sanyam Khurana
First, I would like to know which compiler you are using?Aadit KapoorThe answer is correct if you do not believe me,try compiling the code in c
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 Sharmavaibhav bhanawatwrite 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 KhuranaAdding 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
Is the answer something likeSanyam KhuranaAdding 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(); }
sizeof(i)=2
Cos integer is 2 bit large and so expecting the answer to be 2 -
Vishal Sharma
nope! it'll be 1Jeffrey SamuelIs the answer something like
sizeof(i)=2
Cos integer is 2 bit large and so expecting the answer to be 2 -
Sanyam Khurana
Although you are close to the answer but this answer isn't right.Jeffrey SamuelIs the answer something like
sizeof(i)=2
Cos integer is 2 bit large and so expecting the answer to be 2
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..!Vishal0203nope! it'll be 1 -
Jeffrey ArulrajI got the reason why it must be one #define
I missed it really a tricky one mate Thanks for this one -
Vishal Sharma
int a;
i think the answer will be 0....
void main()
{
int a;
printf("%d....%d",::a,a);
getch();
}
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
Absolutely RightVishal0203nope! it'll be 1
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.Jeffrey SamuelI got the reason why it must be one #define
I missed it really a tricky one mate Thanks for this one
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.Vishal0203i 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 -
Aadit Kapoor
I am using clang compiler.It is obvious that now one writes int k = *ip/*jp;Sanyam KhuranaFirst, 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
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.
Basic rules:Sanyam KhuranaAlthough 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..!
FIRST: C does not have :๐Scope resolution operator).
SECOND: Please the full code.
The answer is garbage values for both of the a'sAadit KapoorBasic rules:
FIRST: C does not have :๐Scope resolution operator).
SECOND: Please the full code. -
Vishal Sharma
Basic rules:
no one said that this thread is ONLY for C programming language
FIRST: C does not have :๐Scope resolution operator).
SECOND: Please the full code. -
Aadit Kapoor
I Agree,but we we can't write mixed code.We cannot mix C and C++.Vishal0203no one said that this thread is ONLY for C programming language -
Sanyam KhuranaDesign 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
#includeSanyam KhuranaDesign 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
#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
Nice!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;
}
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. -
aviiPrint 1 to 100, without using loops, recursions in C.
-
Sanyam Khurana
Already solved here, by @#-Link-Snipped-# in post #123aviiPrint 1 to 100, without using loops, recursions in C.
EDIT: Oops, my bad, it uses recursion.
Can we use goto in this? -
avii^no. No go to also.
-
Vishal Sharma
Okay this is another way! it doesn't use goto, recursion, no loops!avii^no. No go to also.
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
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.Vishal0203Okay 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(); }
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
#define swap1(a,b) a=a+b;b=a-b;a=a-b;
Swap2 procedure is wrong... still, if we correct it, we'll get same answer printed on screen i.e. 10 5
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 ;
}
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()
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.
{
static int i=5;
if(--i)
{
main();
printf("%d ",i);
}
getch();
}
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 Sharmawas getting bored so painted a pic to explain the second code ๐
I don't know how much it explains though! -
Gaurav DeshmukhDecypher
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
Easy enough!Gaurav v. DeshmukhDecypher
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.
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
this was asked in aspirations exam today ๐Gaurav v. DeshmukhDecypher
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. -
Sanyam KhuranaGive 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 bhanawatif 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
You can use visual studio to convert a project into an installer.vaibhav bhanawatif 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
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
#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 SharmaWrite 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 KhuranaWrite 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 KapoorCan someone explain 2 dimensional and 3 dimensional arrays in c?
-
Aadit Kapoor
OUTPUT : GOODSanyam KhuranaGive the output with explanation :
void main() { int i=1,j=2; switch(i) { case 1: printf("GOOD"); break; case j: printf("BAD"); break; } getch(); }
because int i = 1
case 1: i is already one then it will print GOOD. -
Aadit Kapoor
OH SORRY!Aadit KapoorOUTPUT : GOOD
because int i = 1
case 1: i is already one then it will print GOOD.
OUPUT IS ERROR!
because case accepts only chars,strings,integers BUT NO variable. -
Sanyam KhuranaWhy is this thread dead ๐ฒ๐
Isn't there anyone to share & try out stuff.. ๐ญ -
Abhishek Rawal
Okay, here you go then : #-Link-Snipped-#Sanyam KhuranaWhy is this thread dead ๐ฒ๐
Isn't there anyone to share & try out stuff.. ๐ญ
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
Not into Linux so much :/Abhishek RawalOkay, 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.
But I would try & see this. -
Vishal SharmaAn array consists of binary number, swap all 0's to the end.
Example : 100110111101 gives 111111110000 -
aviiVishal0203An array consists of binary number, swap all 0's to the end.
Example : 100110111101 gives 111111110000binstring = '1010101010' newstring = '1'*(len(binstring) - binstring.count('0')) + '0'* binstring.count('0')
-
Vishal Sharma
i'd appreciate a solution in C. And, convert the same input string instead of using a new oneaviibinstring = '1010101010' newstring = '1'*(len(binstring) - binstring.count('0')) + '0'* binstring.count('0')
-
avii^I don't like C. So used Python. and strings are immutable in python, so its not possible to 'convert' it
-
Vishal Sharma
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!avii^I don't like C. So used Python. and strings are immutable in python, so its not possible to 'convert' it -
Harshad Italiya
Array of binary number. Do you mean like thisVishal0203An array consists of binary number, swap all 0's to the end.
Example : 100110111101 gives 111111110000
Array[]="10001101011101" ;
-
durga chavii'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 += ('0' * (len(s) - len(sn)))
sn += iโ
prints '111111110000' -
Harshad ItaliyaI 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
how about converting the same string to the required form?durgaavii'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 += ('0' * (len(s) - len(sn)))
sn += iโ
prints '111111110000' -
Vishal Sharma
don't you think you made it more complicated? ๐ it can be done in one pass.. think that way!Harshad ItaliyaI 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
-
Harshad Italiya
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. ๐Vishal0203don't you think you made it more complicated? ๐ it can be done in one pass.. think that way! -
durga chnot possible. That of code was made in python
Vishal0203how about converting the same string to the required form? -
Vishal SharmaOh my god! I'll stop commenting
-
SurEC93Hello 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
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)SurEC93Hello 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. -
Harshad Italiya
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.Vishal0203That'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#-Link-Snipped-# will you please share your solution for that 0-1 swapping code.
-
Vishal SharmaI'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 chthat 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 SharmaAccording to me python makes life easy,
And so coding these small problems in python doesn't improve thinking skills -
durga chI 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...