write a c program that http://gyazo.com/614ad16944c56d97947b2bba6c77e8e3
im not good at programming, not sure where to start.
I can code this in C++,you can code it in C similarly,I'll explain the logic and everything. #include<iostream.h> #include<conio.h> int main() { clrscr(); int Input,NumberOfTimes=0; cout<<"Enter the Number : "; cin>>Input; for(int i=0;i<Input;i++) { if(Input%2!=0) { Input=Input/2; NumberOfTimes++; } } cout<<"The number of times the Number can be halved = > " <<NumberOfTimes; getch(); } Do you get what I did? Till the number doesn't become odd,i.e the remainder is NON 0 then we will keep haling the number using a for loop. Any doubts?
i cant use for loops, only while loops...
can you please help me with this using while loops?
Replace ----------------------------- for(int i=0;i<Input;i++) { if(Input%2!=0) { Input=Input/2; NumberOfTimes++; } } ------------------------------ with ------------------------------ while(Input%2!=0) { Input=Input/2; NumberOfTimes++; }
@Omniscience ?
not working...how do i count how many times it has been havled?
If its an even number then on dividing by 2 the remainder will be 0,for odd it will be non 0. Then the number will be halved i.e Input=Input/2; And If number is halved then we increment the variable NumberOfTimes++; then finally print it.This is the logic.I don't know why it isn't working with C maybe some syntax thing but you know the logic try to code yourself though i don't think there is a fault in my program it should work well :/
``` int halfCount = 0; while (n % 2 == 0) { // Check that n is even n = n / 2; // Haves the number halfCount++; // Adds to half count } ```
Also, the input and output are very different in C from C++. If you are trying to learn C, then use of the C++ libraries will hurt you rather than help you.
How about: #include <stdio.h> #include <stdlib.h> int evenHalf( int number ) { number /= 2; if( number % 2 ) return 0; else return( evenHalf( number ) + 1 ); } int main( int argc, char* argv[] ) { if( argc > 1 ) printf( "%d\n", evenHalf( atoi( argv[ 1 ] ) ) ); else printf( "Usage: %s <integer>\n", argv[ 0 ] ); return( 0 ); }
Not to demean this site, but if you're looking for help with C programming this is the site I always use: It's filled with a lot of really experienced programmers, but they expect you to do the work. They will most def help you solve your problem. http://cboard.cprogramming.com/
but the logic remains the same
Join our real-time social learning platform and learn together with your friends!