Convert characters in string to integers for multiplication - c

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;
}

Related

Why am I getting a character in output when my input is 5 or more than 5? It is pure mathematical equation. If anything is wrong please tell me

I have compiled this code and it works just fine up to value 4 then it starts returning character instead of integer. I am talking about first equation => x= num*2; Here when I enter num value as 5 the output returns a.
#include <stdio.h>
int main(void)
{
int num;
int x; This right here is an integer still it returns a character
char s[10] = "helloworld";
char f[10];
scanf("%d", &num); //
//printf("%d\n", num);
x = num * 2 ;
printf("%x\n", x);
scanf("%c", &f[10]);
if(s[10] = f[10]){
printf("helloworld");
}
}
please tell me if there is a mistake I am a newbie to coding.
As I see you are learning C language, and after reading your explanation, I feel that you want to print the integer value of variable x.
Kindly replace %x with %d in the print statement of variable x,
and you will be successfully able to print the value.
#include <stdio.h>
int main(void)
{
int num;
int x; // This right here is an integer still it returns a character
char s[10] = "helloworld";
char f[10];
scanf("%d", &num);
x = num * 2 ;
printf("%d\n", x); // %d for integer and %x for hexadecimal values
scanf("%c", &f[10]);
if(s[10] = f[10]){
printf("helloworld");
}
return 0;
}
Finally, do read more about format specifiers in scanf and
printf statements.

How to find the number of digits int digits in c upto 100 or 1000 digits?

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 get summation in C?

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;
}

how to use scanf to scan double and char at the same time into a double array in C

I have a project to do which asks me to record the address of two vectors into a double array according to user's input. However. For example, if user writes
3
1 2 3
3 4 5
it means that the vectors are 3 dimensional and the two vectors are (1,2,3)(3,4,5). If user writes,
2
1 2
2 3
it means that the vectors are 2 dimensional and the two vectors are (1,2)(2,3). I need to record the coordinates of these two vectors into two double arrays x, and y. How can I read the coordinates into these two arrays using scanf? (I don't know if the user writes in the correct format, it's possible for them to write letter or other symbol at the place where they are supposed to just write number. If they write chars other than number, i need to return -1.)
my code so far is
double x[100];
char c;
c = getchar();
do {
scanf("%lf",x)}
while (c!= '\n');
As far as I understand your problem, here is a code that should solve it.
#include <stdio.h>
#include <stdlib.h>
#define NB_VECTORS 2 //Increase if you have more than 2 vectors
int* readVector(int size) {
// Allocation fits the size
int* vector = malloc(size*sizeof(int));
//While the vector are the same size it works
for (int i = 0; i < size; i++)
if (scanf("%d", vector+i) != 1)
return null; //bad input
return vector;
}
int main(int argc, char** argv) {
int size;
scanf("%d", &size);
//Each line is vectorized inside vectors[i]
int* vectors[NB_VECTORS];#
for (int i = 0; i < NB_VECTORS; i++)
vectors[i] = readVector(size);
return 0;
}
[EDIT]
returns the number of items it has filled -> cf http://www.cplusplus.com/reference/cstdio/scanf/
Maybe you simply need something like this (simplistic, minimal, no error checking example):
int main()
{
int x[3], y[3];
int dimension;
scanf("%d", &dimension);
if (dimension == 3)
{
scanf("%d %d %d", &x[0], &x[1], &x[2]);
scanf("%d %d %d", &y[0], &y[1], &y[2]);
}
else if (dimension == 2)
{
scanf("%d %d", &x[0], &x[1]);
scanf("%d %d", &y[0], &y[1]);
}
...
return 0;
}
scanf is not a good function for parsing user input. It accepts 2.1sdsa2 as a float with the value 2.1 and it accepts 2.1sdsa2 as an int with value 2. The scanf should only be used when you know that the input is valid.
If you are required to use scanf, you can scan into a string and then write your own parse to check that the input is valid.
A simple example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10];
while (1 == scanf("%s", s))
{
printf("%s\n", s);
if (strcmp(s, "s") == 0) break;
}
return(0);
}
The program continues until the input is s
Example of output:
1 2.0 2.6
1
2.0
2.6
2a 4567 2.a23
2a
4567
2.a23
s
s
Notice that scanf returns when it sees a space. So the input 1 2 3 will be 3 loops (aka 3 substrings returned).
So instead of just printing, you could put your parser inside the while:
while (1 == scanf("%s", s))
{
// Parse the string s and add value to array
}

Write a program that multiplies user entered number till product of these numbers reach 1000

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;
}

Resources