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;
}
Related
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.
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;
}
I have to do a program to take a number and print all the digits one by one as characters.
The code I have written is here:
#include <stdio.h>
#include <stdlib.h>
char digito(int, int);
int numberofdigits(int);
int main(void)
{
int num=0, test=0, kdigits=0, k=0;
char ch='\0';
printf("Enter a positive number:\n");
test=scanf("%d", &num);
if (teste!=1 || num<=0)
{
printf("Error: not a valid number.\n");
exit(EXIT_FAILURE);
}
kdigits = numberofdigits(num);
for(k=0; k<kdigits; k++)
{
ch= digito(num, k);
printf("The digit %d of the number is %c\n", k, ch);
}
return EXIT_SUCCESS;
}
int numberofdigits(int _n)
{
int count=0;
while (_n!=0)
{
_n/=10;
count++;
}
return count;
}
char digito(int _number, int _kdigit)
{
int flag=0, digit=0;
char ch='\0';
for (flag=0; flag<=_kdigit; flag++)
{
digit=_number%10;
_number/=10;
}
ch= digit + '0';
return ch;
}
Now the code is working pretty fine for relatively small numbers (up to 8 or 9 digits I would say).
But then something odd is happening: I tried to print the digits of the number 11111111111122 and obtained
The digit 0 of the number is 3;
The digit 1 of the number is 7;
The digit 2 of the number is 3;
The digit 3 of the number is 6;
The digit 4 of the number is 1;
The digit 5 of the number is 7;
The digit 6 of the number is 0;
The digit 7 of the number is 3;
I wonder why? Is it because it's a very large number? Because I tried even larger numbers and what happens is that the program enters the initial if clause that verifies the scanf reading. And that's ok. But the problem is that the program should also do the same with this number since it's bigger that the largest int.
Can someone help me fix this please?
Thanks!
There are two answers to two questions:
Q1) Why do I get wrong digits for the example?
A1) As others have commented: Because the example number is too high for the data type used, it matches the number which you find in the lower 32 bits: 30716370.
Q2) Why is the initial check "<0" not triggering for the example but does trigger for other, higher examples?
A2) Because the 30716370 is smaller than the biggest positive number which can be represented by a 32 bit signed int, which is 2147483647 == 0x7FFFFFFF. That one however is smaller (even in the number of digits, but that is not the point) than 11111111111122.
30716370 <
2147483647 <
11111111111122
The even higher numbers will by chance have the bit31 set, which makes the lower 32bit look negative. You could probably find other numbers which are too high but do not seem negative.
The program below is sufficent enouhgh to find the length of any string length that is given to the input, however, i need to find the length of an integer variable, rather than a string.
Entering a number to this does work, but not if i scan s as a int type.
int main()
{
char s[1000];
char i;
int u=5;
do
{
char s[1000];
char i;
int u=5;
system("cls");
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d",i);
getch();
}
while(u==5);
getch();
}
So all i need is either this little program modified to accept intger variables, or a way to transform a calculated int variable into a string.
Any ideas?
Edit: Length = Amount of characters so 25 has 2, 3456 has 4 etc
You can calculate the length of n in base m with the formula:
ceil(log(n + 1, m))
Where ceil is the ceiling (round up) function, and log(a, b) is logarithms of a in base b.
You may use the below code to find the number of digits of an integer:
int count=0;
while(n!=0)
{
n/=10;
++count;
}
Where n is your input integer and count will be the it's length.
If you want to read an integer as an integer i,e with %d and count number of digits in that integer, have a look at below code snippet.
int no,length=0;
printf("Enter number");
scanf("%d",&no);
while(no!=0)
{
length+=1;
no=no%10;
}
printf("Length=%d",length);
To determine the number of characters to print a decimal number (assuming value is the int), you could do the following:
int intlen = 0;
if (value < 0) // for negative values, allow a char for the minus sign
{
value = -value;
++intlen;
}
while (value >= 10) // as long as the value is 1 or more,
{
value /= 10; // divide by 10,
++intlen; // ...and add one to the length
}
++intlen; // add one for last digit (even if it's zero)
It's probably easier to use the ceil/log function described above, but this one does not require the math library (if that is an issue)
Another brute-force approach would be as follows:
char temp[12];
int intlen = sprintf(temp,"%i",value);
This utilizes the fact that sprintf returns the number of characters placed in the string buffer.
#include<stdio.h>
main()
{
int count=1,n;
scanf("%d",&n);
while(n/=10)
count++;
printf("result=%d",count);
}
count gives the number of digits in number n
I am having trouble getting this to work. What I want to do is take user input example 1 2 3 and then multiple each character by 2 so output would be 2 4 6. Eventually I will take a long string of numbers and multiply every other character in the string by 2 leaving the rest untouched.
The problem I a having now is that I think it is multiplying the ASCII value by 2 not the actual integer by 2. Below is the code I have so far I haven't added any error checking to it yet to make sure the user inputs only numbers and not more than 16 etc. I am new to programming in C and am just doing this to learn.
#include <stdio.h>
int main(void){
char numbers[17];
int i;
printf("Please enter number\n");
scanf("%s", &numbers);
for(int i=0;i<strlen(numbers);i++){
printf("%c\n",numbers[i] * 2);
}
}
2 issues in your program
1)
scanf("%s", numbers);
2)
printf("%d\n",(numbers[i] - '0') * 2);
Here is a modfied program
#include <stdio.h>
#include <string.h>
int main()
{
char numbers[17];
int i, len;
printf("Please enter number\n");
scanf("%s", numbers);
len = strlen(numbers);
for(int i=0;i<len;i++)
{
printf("%d\n",(numbers[i] - '0') * 2);
}
}
Also, it's better to avoid scanf - http://c-faq.com/stdio/scanfprobs.html
Something like the following might be what you are after. It assumes numbers[i] contains an ASCII digit, converts it to the corresponding integer (by subtracting the ASCII value for zero), multiplies by 2 and then adds the value for ASCII zero to that result.
printf( "%c\n", ( numbers[i] - '0' ) * 2 + '0' );
That will work for characters 0 - 4. It's not clear from my reading of the OP what is desired for digits 5-9.
Try using the atoi function like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char numbers[17];
int i;
printf("Please enter number\n");
scanf("%s", numbers);
for(i=0;i<strlen(numbers);i++){
printf("%c\n", atoi(numbers[i]) * 2);
}
return 0;
}