I have started an intro to programming course that uses the C language and we have an assignment to make a program that takes a 5 digit number from the user such as 12345 and it prints it out as 1 2 3 4 5.
I tried to google around for help but all the answers given used code way too complicated for my understanding considering the course just started and we have only learned printf and scanf, if and switch statements and while and for loops.
I tried putting all the numbers given into separate int variables which made the program stop and then tried to put them into chars but the testing program said it was wrong since we are supposed to use int.
Is there a simple way to do this?
EDIT:
What I have tried:
#include <stdio.h>
int main(void) {
int num1,
num2,
num3,
num4,
num5;
printf("Give 5 digit number > ");
scanf("%d%d%d%d%d", &num1, &num2, &num3, &num4, &num5);
printf("Seperated number is %d %d %d %d %d", num1, num2, num3, num4, num5);
return (0);
}
Also tried that code but with char variable type but that wasn't allowed it has to be int.
The testing program gives an expected output which for 00001 is Given number 1 seperated is 0 0 0 0 1 or for -12321 is Given number -12321 seperated is -1 -2 -3 -2 -1
You can read user input into a char array using scanf.
Then using for loop you can loop through each char (1,2,3,4,5)
Use printf in the loop to print from array and a space. printf("%c ", input_from_user[i]);
I suppose the point here is understanding how C stores things. You're reading in characters (that is a set of 8-byte values that are commonly displayed as letters) and converting each one to an integer (commonly a 32-bit value that stores a number)
So you want to read the input using scanf to get a character string of your 5 digits, then use a for loop to go over each one, reading a single character from the string and converting it into an integer variable. then printf that variable plus a space, and move on to repeat the next digit.
If you read the digits in one by one then its even easier as you only need the for loop to read, convert, and print each digit as its read.
According to the question, you would be given a number of 5 digits and then you have to print the digits of that number as well.
So, in your program, you have taken five digits individually as input, to me it seems wrong. I am giving my solution below:
#include <stdio.h>
int main(void)
{
int num,idx=0,i=0;
int arr[5]; // for storing the five digits;
scanf("%d",&num);
while(num){ //loop will terminate when the num = 0
int digit = num%10;
num = num/10;
arr[idx] = digit;
idx++;
}
//Printing from the last, as the digit are stored in reverse order.
for(int i=4;i>=0;i--){
printf("%d ",arr[i]);
}
return 0;
}
I don't really understand the purpose of this exercise. If you are learning C, the last function you should learn is scanf. It boggles the mind that so many people teach it early. Try very hard not to use scanf at all until you understand the language well enough to realize that you probably never need it. That said, I suppose the point of the exercise is to do something like:
#include <stdio.h>
int
main(void)
{
unsigned num;
char buf[6];
printf("Give 5 digit number > ");
if( scanf("%u", &num) != 1 || num > 99999 ) {
fprintf(stderr, "Invalid input\n");
return 1;
}
printf("Separated number is");
snprintf(buf, sizeof buf, "%d", num);
for( int i = 0; buf[i]; i++ ) {
printf(" %c", buf[i]);
}
putchar('\n');
return 0;
}
Although likely beyond OP's stage, code can use recursion to print the value from most significant to least.
#include <stdio.h>
void print_digit(int n, int depth) {
if (depth > 1) print_digit(n/10, depth - 1); // print "left" digits first
printf(" %d", n%10);
}
void print_5(int n) {
// To do: checking for correct spelling
printf("Given number %d seperated", n); // or separated
print_digit(n, 5);
printf("\n");
}
int main(void)
{
print_5(1);
print_5(-12321);
return 0;
}
Output
Given number 1 seperated 0 0 0 0 1
Given number -12321 seperated -1 -2 -3 -2 -1
You could use your approach by limiting the number of bytes you read for each number:
#include <stdio.h>
int main(void) {
int num1, num2, num3, num4, num5;
printf("Give 5 digit number > ");
if (scanf("%1d%1d%1d%1d%1d", &num1, &num2,&num3, &num4, &num5) == 5) {
printf("Separated number is %d %d %d %d %d\n", num1, num2, num3, num4, num5);
}
return 0;
}
Note however that this is probably not what you are expected to do. You should instead read a single number and decompose it into its five digits:
#include <stdio.h>
int main(void) {
int num;
printf("Give 5 digit number > ");
if (scanf("%d", &num) == 1 && num >= 10000 && num <= 99999) {
printf("Separated number is %d %d %d %d %d\n",
num / 10000, num / 1000 % 10, num / 100 % 10, num / 10 % 10, num % 10);
}
return 0;
}
Related
I'm writing a program that takes in your student number(8 digits long), prints each digit on its own new line, and then gets the sum of all the digits in the number
(E.g. Student Number - 20305324, Sum - 19)
#include <stdio.h>
#include <string.h>
int main(void) {
char student_number[8];
int i = 0;
int sum = 0;
printf("Enter your student number: ");
scanf("%s", student_number);
// ensures input is only 8 digits - WORKS
while (strlen(student_number) < 8 || strlen(student_number) > 8){
printf("Enter your student number: ");
scanf("%s", student_number);
}
// prints each digit of the student number on a new line - WORKS
while (student_number[i] != '\0'){
printf("%c\n", student_number[i]);
i++;
}
// sum all the digits in the student number and print - DOESN'T WORK
for (i=0;i<8;i++){
sum = sum + student_number[i];
printf("%d\n", sum);
}
printf("Sum of the numbers is %d", sum);
}
OUTPUT
The problem I'm encountering is when my for loop attempts to add each digit in the student number. The output I expect here is 19, but for some reason the sum evaluates to some bizarre number like 403
}
Would someone mind pointing out where exactly the fault in my for loop is or if it is elsewhere? Thanks :)
Firstly, your array char student_number[8]; cannot hold 8-character string because there are no room for terminating null character. You must allocate one more element.
Then, you should convert the characters to corresponding numbers. Character codes for digits are defined to be continuous, so this can be done by subtracting '0' from the character code.
Also you should set a limit of length of string to read via scanf() to avoid buffer overrun. One more good practice is checking the return values of scanf() to see if something is successfully read.
Fixed code:
#include <stdio.h>
#include <string.h>
int main(void) {
char student_number[10]; // *** allocate enough elements (one more than needed to catch too long input)
int i = 0;
int sum = 0;
printf("Enter your student number: ");
if(scanf("%9s", student_number) != 1){ // *** limit the length to read and check the result
fputs("read error\n", stderr);
return 1;
}
// ensures input is only 8 digits - WORKS
while (strlen(student_number) < 8 || strlen(student_number) > 8){
printf("Enter your student number: ");
if(scanf("%9s", student_number) != 1){ // *** limit the length to read and check the result
fputs("read error\n", stderr);
return 1;
}
}
// prints each digit of the student number on a new line - WORKS
while (student_number[i] != '\0'){
printf("%c\n", student_number[i]);
i++;
}
// sum all the digits in the student number and print -DOESN'T WORK
for (i=0;i<8;i++){
sum = sum + (student_number[i] - '0'); // *** convert characters to numbers before adding
printf("%d\n", sum);
}
printf("Sum of the numbers is %d", sum);
}
When you read characters as a string, the values of the char objects are codes for the characters. Your C implementation is likely using ASCII codes, in which 48 is the code for “0”, 49 is the code for “1”, 65 is the code for “A”, and so on.
To convert a code x for a digit to the value of the digit, use x - '0'.
I think that the task was to read the number not the string.
void printDigitsAndSum(unsigned number)
{
unsigned mask = 1;
unsigned sum = 0;
while(number / (mask * 10)) mask *= 10;
while(mask)
{
printf("%u\n", number / mask);
sum += number / mask;
number %= mask;
mask /= 10;
}
printf("Sum: %u\n", sum);
}
int main(void)
{
unsigned number;
if(scanf("%u", &number) == 1)
printDigitsAndSum(number);
else printf("Wrong number\n");
}
https://godbolt.org/z/1edceh
This is my code:`
#include <stdio.h>
void main() {
int n;
int count = 0;
printf("Enter an integer: ");
scanf("%d", &n);
// iterate until n becomes 0
// remove last digit from n in each iteration
// increase count by 1 in each iteration
while (n != 0) {
n /= 10; // n = n/10
++count;
}
printf("Number of digits: %lld", count);
}
I am able to run the code finely but when I enter 15 or 16 digits of number as input then it always shows me that the number of digits is 10. And another problem with this code is that suppose if I input 000 then I want the output to be 3 digits but this code is not able to do that as the condition in the while loop becomes instantly false. So how write a code that enables me to take upto 100 or 1000 digits as input and also enables me to input 0s as well.
Note: This program should be solved using a loop and in C language
I found a answer to the question here in stackoverflow written in c++ that I couldn't even understand as I am a beginner and I am learning C.
Link to the answer:
How can I count the number of digits in a number up to 1000 digits in C/C++
Instead of reading a number, read a string and count the digits:
#include <stdio.h>
int main() {
char buffer[10000];
int n;
printf("Enter an integer: ");
if (scanf("%9999s", buffer) == 1) {
for (n = 0; buffer[n] >= '0' && buffer[n] <= '9'; n++)
continue;
printf("Number of digits: %d\n", n);
}
return 0;
}
You can also use the scanf() scanset feature to perform the test in one step:
#include <stdio.h>
int main() {
char buffer[10000];
int n;
printf("Enter an integer: ");
if (scanf("%9999[0-9]%n", buffer, &n) == 1) {
printf("Number of digits: %d\n", n);
}
return 0;
}
32 bits signed integer has the max value equals 2,147,483,647 so, if you input a bigger one, it will not be stored. I'd make it receiving a string and get its length, like so:
#include <stdio.h>
#include <string.h>
int len = strlen("123123123123132");
You are taking int variable and you are trying to count a number like whose digit is 100 or 1000. it will not fit with int. so take input as a string and count the length of string.
How to make a program to read elements from input like:
1 3
and give me the summation of that:
4
#include <stdio.h>
int main(void){
char x[3];
scanf(" %c",&x);
printf("%d\n",x[0]+x[2]);
}
In your approach you seem to read in a string and treat several positions of that string as numbers. Besides the fact that there are several mistakes in implementing this approach, the main thing actually is that you've taken the wrong approach. Drawbacks (not all, just some) are: you only consider numbers of exactly one digit; you assume that user input is exactly mapped to your array with exactly one "blank" position between the numbers of interest (as you access x[0]+x[2] with hard-coded indexes 0 and 2); you are limited to exactly two "numbers" to be summed up; ...
I'd rather scan integral values (i.e. using %d and data type int) within a loop until one enters something that is not a valid number. This solves all of above mentioned issues:
int main() {
int sum=0;
int num=0;
printf("type in numbers to be summed up (type a non-number to exit):\n");
while (scanf("%d",&num)==1) {
sum += num;
}
printf("sum: %d\n",sum);
}
Intput/Output:
type in numbers to be summed up (type a non-number to exit):
10 20 30 x
sum: 60
There's a few things missing here.
For one thing, you're only reading one character with %c. You're storing it in &x, which, though confusing, is technically legal: since it's a sequence of 3 char-sized elements in memory, &x is a valid character address. However, x[1] and x[2] remain uninitialized; you're not setting them anywhere.
Secondly, you're not converting it to an integer value so it still has the value of the character '1' not decimal 1. '1' + '1' (note single quotes) will evaluate to 49 + 49 (note lack of quotes), 49 being the ascii equivalent to the character '1' - very different from the decimal value 1.
Finally, you're only summing the first and third character (the latter, being uninitialized, has an unknown value, certainly not one from your input). The second character is not a part of the final result.
If you want to read 3 integers, you should scan for ints, not characters, and you should scan for the number of them you wish to read. That would allow you to read numbers above 9 correctly.
But perhaps you do want to scan for one digit at a time; in which case, you'll certainly want to convert each digit character to it's integer equivalent. Since the digits 0 to 9 are contiguous and in ascending order in ascii, you can simiply subtract '0' from the character to get its decimal equivalent ( '1' - '0' == 1, '9'-'0'==9, etc.) But for this to work, you must ensure that you really have read a digit and not just any char. You might do so by verifying that its value was between '0' and '9', inclusive.
Regardless of whether you wish to sum integers or digits, you'll want to ensure you're reading each value you're going to sum before computing the final sum.
It might make more sense, given your use case, to keep scanning for ints in a loop until you run out of ints on the input stream. You don't really need to store them each; you can read one int at a time and add it to a running total.
Putting that all together, you might end up with something like this. Take these ideas and implement your running sum, and you'll have what you want for characters.
#include <stdio.h>
int main() {
char c; // we'll store our input here as we go
while( scanf(" %c", &c) == 1 ) { //one thing matched
if(c >= '0' && c <= '9'){ // it's a digit
printf("Read %c, decimal value of digit is %d\n", c, (int)(c-'0') );
}else {
printf("Invalid digit %c\n", c);
}
}
}
I run like this:
$ gcc -o t t.c && echo '1 2 3 4 5' | ./t
Read 1, decimal value of digit is 1
Read 2, decimal value of digit is 2
Read 3, decimal value of digit is 3
Read 4, decimal value of digit is 4
Read 5, decimal value of digit is 5
Change to scanf("%d") like described below to read multi-digit integers instead, changing the code accordingly.
#include <stdio.h>
int main() {
int c; // we'll store our input here as we go
while( scanf(" %d", &c) == 1 ) { //one thing matched
printf("Read %d; wasn't that easy?\n", c);
}
}
$ gcc -o t2 t2.c && echo '1 2 3 4 5' | ./t2
Read 1; wasn't that easy?
Read 2; wasn't that easy?
Read 3; wasn't that easy?
Read 4; wasn't that easy?
Read 5; wasn't that easy?
That approach can read any integer repesentation up to the min/max size of int, including multiple digits and even negative numbers:
$ gcc -o t2 t2.c && seq -1 -10 | ./t2
Read -1; wasn't that easy?
Read -2; wasn't that easy?
Read -3; wasn't that easy?
Read -4; wasn't that easy?
Read -5; wasn't that easy?
Read -6; wasn't that easy?
Read -7; wasn't that easy?
Read -8; wasn't that easy?
Read -9; wasn't that easy?
Read -10; wasn't that easy?
You could try:
int n1;
int n2;
scanf("%d %d", &n1, &n2);
int sum = n1 + n2;
printf("%d\n", sum);
If you want to add more than two numbers together, you could try:
printf("Enter how many numbers you want to add:\n");
int n;
scanf("%d", &n);
int sum;
for (int i = 0; i < n; i++) {
int in;
scanf("%d", &in);
sum += in;
}
printf("%d\n", sum);
Note:
At first the answer had C++ in the title and so I answered with C++ like this:
If you don't mind using cin and cout, you could try:
int n1;
int n2;
cin >> n1 >> n2;
cout << n1 + n2;
Running this program with n integers will return their sum by iterating from argv[1] to argv[n]. argv[0] is the name of the program.
Example:
./sum 1 3 returns 4
Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i;
int sum;
if (argc > 1)
{
for (i = 1; i < argc; i++)
{
sum += (int)strtol(argv[i], NULL, 10);
}
printf("%d\n", sum);
}
else
{
fprintf(stderr,"Invalid number of arguments\n");
return(EXIT_FAILURE);
}
return(EXIT_SUCCESS);
}
You could use an array and a loop. This is a simple method.
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0, allocation[5],i,num;
printf("enter the number of elements");
scanf("%d",&num); // how many numbers are there??
printf("Enter the elements");
for(i=0;i<num;i++)
{
scanf("%d",&allocation[i]); //allocate the elements in the array say 3,4,5
sum=sum+allocation[i];
//0+3, sum=3
//3+4, sum=7
//7+5, sum=11
}
printf("Sum= %d",sum); //print Sum=11
getch();
}
#include <stdio.h>
int main () {
int num1,num2;
printf("Enter two numbers");
scanf("%d %d", &num1 &num2);
printf("Sum is = %d", num1+num2);
return 0;
}
My console keeps on crashing after entering a few numbers. I am trying to get an array of 10 numbers from the user thru the console and then taking count of positives, negatives, evens, and odds. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int pos, neg, even, odd;
int nums[10];
printf("Give me 10 numbers: ");
pos = neg = even = odd = 0;
for(int i = 0; i < 10; i++){
scanf(" %d", nums[i]);
if(nums[i] > 0){
pos++;
if(nums[i] % 2 == 0){
even++;
}
else{
odd++;
}
}
else{
neg++;
}
}
printf("Positives: %d, Negatives: %d, Evens: %d, Odds: %d\n", pos, neg, even, odd);
return 0;
}
In your code,
scanf(" %d", nums[i]);
should be
scanf(" %d", &(nums[i]));
or,
scanf(" %d", nums+i);
as you need to pass the pointer to variable as the format specifier's argument in scanf() .
To elaborate, %d expects a pointer to int and what you're supplying is an int variable. it invokes undefined behavior.
That said,
Always check the return value of scanf() to ensure proper scanning.
int main() should be int main(void) to conform to the standard.
Modify scanf like scanf(" %d", &nums[i]);
scanf(" %d", nums[i]);
Scanf expects a pointer to a location to write to, and you're not giving it one.
Change your scanf to:
scanf(" %d", &(nums[i]));
to make your program work.
With this change I tested your program with stdin of
20 10 9 1 39 1 2 2 31 1
And recieved output:
Give me 10 numbers: Positives: 10, Negatives: 0, Evens: 4, Odds: 6
ideone of the thing for your testing purposes.
Change scanf(" %d", nums[i]); to scanf(" %d", &nums[i]);, because scanf() needs addresses. The parentheses around nums[i] isn't necessary, and may effect readability.
Also note that 0 is even, but not negative.
When scanf is usedto convert numbers, it expects a pointer to the corresponding type as argument, in your case int *:
scanf(" %d", &nums[i]);
This should get rid of your crash. scanf has a return value, namely the number of conversions made or the special value EOF to indicate the end of input. Please check it, otherwise you can't be sure that you have read a valid number.
When you look at your code, you'll notice that you don't need an array. Afterreading the number, you don't do aything with the array. You just keep a tally of odd, even and so on numbers. That means you just need a single integer to store the current number. That also extends your program nicely to inputs of any length.
Here's a variant that reads numbers until the end of input is reached (by pressing Ctrl-D or Ctrl-Z) or until a non-number is entered, e.g. "stop":
#include <stdlib.h>
#include <stdio.h>
int main()
{
int count = 0;
int pos = 0;
int neg = 0;
int even = 0;
int odd = 0;
int num;
while (scanf("%d", &num) == 1) {
count++;
if (num > 0) pos++;
if (num < 0) neg++;
if (num % 2 == 0) even++;
if (num % 2 != 0) odd++;
}
printf("%d numbers, of which:\n", count);
printf(" %d positive\n", pos);
printf(" %d negative\n", neg);
printf(" %d even\n", even);
printf(" %d odd\n", odd);
return 0;
}
Change scanf statement after for loop to
scanf(" %d", &nums[i]);
I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}