Ok everyone so i have a 9 digit number in input (123456789) and i need to break it down to first middle and last three numbers (123,456,789).
I know that i can use modulo to get the last three digits.
first_group_of_three = input number % 1000;
But i have no idea how to get the other two groups.
Any help would be appreciated.
UPDATE !
Thanks to milevyo answer i managed to figure it out.Now for the code freaks out there,i am a beginner programmer and i would like to ask what is a more efficient way to write this code(below),maybe using less variables or some other technique.I didn't transform it to char because we are not allowed to since we still "havent learned it"
scanf("%d" , &input_number);
last_group_of_three = input_number % 1000;
temp = (input_number-last_group_of_three)/1000;
middle_group_of_three = temp % 1000;
first_group_of_three = (temp-middle_group_of_three)/1000;
first_group_of_three = input number % 1000;
shift=(input number-first_group_of_three)/1000
second_group_of_three = shift % 1000;
and so on
Simplification: #Barmar
scanf("%d", &input_number);
last_group_of_three = input_number % 1000;
input_number /= 1000;
middle_group_of_three = input_number % 1000;
input_number /= 1000;
// % 1000 only if original input exceeded 9 digits
first_group_of_three = input_number % 1000;
Note: many compilers will optimize the % 1000 and / 1000 into a single operation providing the two results: remainder & quotient.
(OP has not mention what code should do with negative numbers.)
You can input the numbers as string in a char table and then the first 3 numbers will stay the 4th char of table will be the char ',' and the 5th,6th,7th char will be the next 3 numbers etc. So you will finally create the string "123,456,789", then print.
Related
I am trying to find each digit of a number entered by the user.
The length of the number is up to the user.
So far I have:
managed to limit what the user enters by using long long card, meaning they cannot enter more than about 18 or 19 characters and only numbers are accepted.
managed to get the first and last digit of that number, as well as the count of the number.
Now I wanted to:
specifically ask for no more than 16 digits max - > but it keeps saying undeclared identifier and am not sure where I go wrong
be able to identify each digit, i.e.:
53689
1st digit:5
2nd digit:3
3rd digit:6
etc.
I learned about modulus but I can't figure out how to tell it to stop at the 2nd last/3rd last digit.
I feel it's something really simple but how? especially if I don't know if the user enters 5 numbers or 15, otherwise I could say (repeat modulus x-1 times) or something like that.
Just for now, my code in case you see anything for #1.
Before I tried to limit the entry-conditions, it worked fine showing me card, card length and 1st,last digit.
#include <cs50.h>
#include <stdio.h>
//finding first 2 numbers and last number and checking what card type
int main(void)
{
int count = 0;
do
{
long long card = get_long_long("Enter your card number: ");
}
while (card ! = 0)
{
card = card / 10;
count++;
}
printf("Card number: %llu\n", card);
printf("Number of digits: %d \n", count);
firstdigit = card;
while (firstdigit >= 20)
{
firstdigit = firstdigit / 10;
}
printf("First digit = %d \n", firstdigit);
lastdigit = card % 10;
printf("Last digit= %d \n", lastdigit);
return 0;
}
info: Yes it is from CS50 credit, I can't understand the full exercise yet so I decided to take it apart and only learn how to write a program that analyses the number for first 2 digits and tells me what card type it is. To do so I'm trying to learn how to count every number on any given number length for practice, for me to actually understand this slowly, so please don't share a full answer to the credit problem.
I also haven't learned arrays or more complex solutions yet either.
As others have advised, "break the problem down into smaller pieces".
Here's an example of that approach. Instead of dealing with a massive number all at once, this 'segments' the number into the typical 4 sections embossed into a credit card. This might give you a start toward a solution...
int main() {
int count = 0;
long long card = get_long_long("Enter your card number: ");
long long cpy = card;
int blk4 = cpy % 10000; // 4 rightmost digits as int
cpy = cpy / 10000; // shift right
int blk3 = cpy % 10000; // next 4 digits as int
cpy = cpy / 10000; // shift right
int blk2 = cpy % 10000; // next 4 digits as int
cpy = cpy / 10000; // shift right
int blk1 = cpy % 10000; // leftmost 3-4 digits as int
printf( "Card number: %04d %04d %04d %04d\n", blk1, blk2, blk3, blk4 );
return 0;
}
Having shown that, please be advised that a credit card "number" is not a "number" in the usual sense. It is a string made-up only of digits. Trying to solve this CV50 problem with "integers" is going to lead to tears. It's time to learn about arrays of characters (even if every character is an ASCII digit)...
I am stuck in a problem where the user inputs the total number of digits used in numbering the pages and the program gives the total number of pages in the book.
(i.e. a book of 10 pages needs 11 digits to number because the numbers 1-9 are written with one digit and the number 10 is written with two digits; an 11 pages book requires 13 digits ...).
I tried it by using a while loop but it does not run as it exceeds the execution time.
My C code looks like this:
#include <stdio.h>
int main() {
int n, pages = 9;
scanf("%d", &n);
if (n <= 9) {
printf("%d",n);
}
else if (n % 2 == 0) {
printf("Invalid input");
}
else {
while (n < 9) {
pages++;
n -= 2;
}
}
return 0;
}
Can anyone please help me with this problem?
Consider using successive tests like this:
if the number <= 9, the number of pages is number, else set pages = 9 and subtract 9 from number.
if the number <= 90 * 2, the number of pages is pages + number / 2, else set pages += 90 and subtract 90 * 2 from number.
if the number <= 900 * 3, the number of pages is pages + number / 3, else set pages += 900 and subtract 900 * 3 from number.
etc.
You can write a loop to solve the problem without making an assumption on the range of the type used to store number and pages.
int number_of_pages(int number_of_digits) {
int n1 = 9, n2 = 1, pages = 0;
while (number / n2 > n1) {
pages += n1;
number -= n1 * n2;
n1 *= 10;
n2 += 1;
}
return pages + number / n2;
}
else if(n%2==0)
{
printf("Invalid input");
}
Please note that there are books with more than 100 pages:
A book with 102 pages has 198 digits!
while(n!=0)
{
pages++;
n-=2;
}
This loop will run forever:
Because n is initially an odd number, n-2 is also odd. So n will always be odd (maybe negative) if n-=2 is the only instruction that modifies n. n cannot become 0, so the loop will run forever.
You also have to consider that books with more than 100 pages or with more than 1000 pages may exist.
I would do it the other way round and count pages up from 1 to N. I would sum up the digits required for the given number of pages and stop when the number of digits is exceeded:
int n, pages=0, digits=0;
int realdigits=0, neededdigits, tooLarge;
/* "realdigits" is the number of digits required
* by "pages" pages; loop until
* "realdigits" >= "digits" */
while(realdigits < digits)
{
pages++;
/*
* Add some code that calculates:
* neededdigits = Number of digits required by
* the number "pages"
*/
realdigits += neededdigits;
}
/* Case: "(pages-1)" pages need less digits
* than "digits" but "pages" pages need more
* digits... */
if(realdigits > digits)
{
printf("Invalid number\n");
}
else
{
printf("%d pages\n", pages);
}
I would use a loop based on a condition to calculate the number of digits required by the number pages:
neededdigits = 1;
tooLarge = 10; /* Number that is too large for digits */
while(pages >= tooLarge)
{
neededdigits++;
tooLarge *= 10;
}
Note that in "C-like" programming languages (C, C++, Java, C#, PHP ...) you may use the for keyword for "condition-based" loops ...
In your posts body you do not ask a question (apart from "Can somebody help me?", which is not considered a question here). In your comments you ask for the main() function, or the logic, or the pseudo code. Sorry, that is not how StackOverflow is meant to be used.
But finally you ask how to arrive at the needed formula.
With How do I ask and answer homework questions? in mind I will help you with that.
make a table of the simplest case (1,2,3,4,5,6,7,8,9) pages and digits, the same
find the formula for that
check the next complex case (10,11,12,13,14,...99) pages and digits, there is a very simple relation
consider which influence the pages 1...9 have on the formula, think offset
consider the next complex case (100, 101, .... 999)
and proceed to the mentioned limit of 2 billion pages
No loops! Uses log10() and pow() from math library.
Based on formula found on OEIS A058183: "Number of digits in concatenation of first n positive integers."
#include <math.h>
int digits_for_pages(unsigned n) {
// oeis A058183
return (n+1)*floor(log10(10*n)) - (pow(10, floor(log10(10*n)))-1)/(10-1);
}
https://ideone.com/7GJYXq
I've been trying to work with modulos in my code for my school project, but I've encountered one "issue" :
In my program, I want to recover my results and transform them into (printed on stdout) percentages.
For example : I find my number (4 / 48), and I get "0.08333333333", multiply it by 100 to get "8.333333333", I will print the first number as an int (so it will basically output 8), and then I want to print the first two digits after that, so I will just use a modulo 10 to get "33".
But, my "issue" is when I try to print two zero digits, it will simply display one of them, as the result is zero, so there is no need to have multiple zeros.
I figured how to print both zero-digits like so :
if (((int)(freq * 100) % 100) == 0) {
my_put_nbr((int)(freq * 100) % 10);
my_put_nbr((int)(freq * 100) % 10);
} else
my_put_nbr((int)(freq * 100) % 100);
where for example "freq" in this case is "8.333334" and will result in printing 8 then 33.
but I wanted to know if there was another actual proper way to do what I just did there.
I'm not very good at explaining things but I hope this is clear, otherwise please let me know.
If you have a value like 0.08333333 and you want to display it as 8.33, just do
printf( "%.2f\n", freq * 100.0 );
If you’re not allowed to use printf, then slap your instructor for making this harder than it needs to be it depends on how your my_put_nbr function is supposed to work and how you want to format the output. If the function prints out integer values and your freq value is always between 0 and 1 and you just want to display 0.0833 as 833, then all you need to do is
my_put_nbr( (int) freq * 10000 );
That will capture up to the first two digits following the decimal point, including zeros - that is, 0.0100 will be converted to 100.
If your my_put_nbr is only supposed to print individual digits, then this takes a bit more work. You could use a loop like so:
for ( long mag = 1; mag < 100000; mag *= 10 )
{
if (freq * mag < 1) // prevents leading 0s from
continue; // being displayed
int digit = (long) (freq * mag) % 10;
my_put_nbr( digit );
}
I’m using long for my temporary calculations as int is not guaranteed to be wide enough to store 32-bit values (it’s very likely to be wide enough on any system built after 1990, but it is not guaranteed).
If that still doesn’t quite meet your needs, then it should at least give you some ideas.
when I try to print two zero digits, it will simply display one of them
You can try the following, it should print 2 digits.
printf("%2.2f", Value);
Hello I have code to find out the first two digits of a number and save them to a variable in C and the code only works for even length numbers. I need something that will work for both even and odd length numbers. The number I need for first2 is the first two numbers.
long long int input = 6789466321
first2 = input;
while(first2 >= 100)
{
first2 = first2 / 100;
}
Divide by 10 at a time instead of 100 so that you are only removing one digit each iteration.
A function to return the first 2 digits of a long given an input that is a positive number and at least 2 digits (e.g. 10 or above).
int getFirst2Digits(long input)
{
long local = input;
while (local >= 100)
{
local /= 10;
}
return local;
}
I'm new to C programming (I have some very basic experience with programming via vb.NET), and I'm attempting to write a program for the Project Euler Problem #1.
https://projecteuler.net/problem=1
Algorithm
The challenge requires the programmer to find the sum of all multiples of 3 or 5 (inclusive) below 1000 (I used intInput to allow the user to enter an integer in place of 1000).
My current solution takes the input, and decrements it by 1 until (intInput - n) % 3 = 0, that is, until the next nearest multiple of 3 under the input integer is found.
The program then cycles through all integers from 1 to ((intInput - n) / 3), adding each integer to the sum of the previous integers, so long as the current integer is not a multiple of 5, in which case, it is skipped.
The resultant sum is then stored in intThreeMultiplier.
The above process is then repeated, using 5 in place of 3 to find the highest multiple of 5 under intInput, and then cycles through integers 1 to ((intInput - n) / 5), not skipping multiples of 3 this time, and stores the sum in intFiveMultiplier.
The output sum is then calculated via sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier).
The Problem
Whenever I compile and run my code, the user is allowed to input an integer, and then the program crashes. I have determined that the cause has something to do with the first For loop, but I can't figure out what it is.
I have commented out everything following the offending code fragment.
Source Code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int intInput = 0; /*Holds the target number (1000 in the challenge statement.)*/
int n = 0;
int count = 0;
int intThreeMultiplier = 1;
int intFiveMultiplier = 1;
printf("Please enter a positive integer.\n");
scanf("%d",intInput);
for( ; (((intInput - n) % 3) != 0) ; n++)
{}
/*for(; count <= ((intInput - n) / 3); count++)
{
if ((count % 5) != 0)
{
intThreeMultiplier += count;
}
}
count = 0;
for(n = 0 ; ((intInput - n) % 5) != 0 ; n++)
{}
for(; count <= ((intInput - n) / 5) ; count++)
{
intFiveMultiplier += count;
}
int sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier);
printf("The sume of all multiples of 3 or 5 (inclusively) under %d is %d.",intInput, sum);*/
}
This is my first time posting on StackOverflow, so I apologize in advance if I have broken any of the rules for asking questions, and would appreciate any feedback with respect to this.
In addition, I am extremely open to any suggestions regarding coding practices, or any rookie mistakes I've made with C.
Thanks!
scanf("%d",intInput);
might be
scanf("%d", &intInput); // note the ampersand
scanf need the address the variable where the content is to be stored. Why scanf must take the address of operator
For debugging only, print the input to verify that the input is accepted correctly, something like
printf("intInput = %d\n", intInput);
The first thing you need when you are inputting intInput you should use:
scanf("%d", &intInput);
Because scanf() need as an argument of a pointer to your variable. You are doing this by just putting the & sign before your int.
In addition I think that you should double check your algorithm, because you are summing up some numbers more than once. :)