I need to get an integer form the user and put the number in array of chars with "+" or "-"
and it print only + and not - if the number is under zero, and it not print the numbers that the user put at all
if can someone tell me what is the problem in my code?
Thank you
int main()
{
int number = 0, i = 0;
char numberArray[MAX_LEN] = {0};
int length = 0;
int save = 0;
int j = 0;
printf("Enter num: ");
scanf("%c", &number);
if(number >= 0)
{
numberArray[i] = '+';
}
else
{
numberArray[i] = '-';
}
save = number;
length = findLength(number);
number = save;
j = length;
for(i = 1; i <= length; i++)
{
numberArray[j] = number % 10;
number /= 10;
j--;
}
printf("%s", numberArray);
}
int findLength(int number)
{
int length = 0;
while(number > 0)
{
number /= 10;
length++;
}
return length;
}
int main(void)
{
int number;
char number_str[10];
scanf("%d", &number);
sprintf(number_str, "%+d", number);
printf("%s\n", number_str);
}
To read your binary integer:
printf("Enter num: ");
scanf("%d", &number);
To print with +/-:
printf ("%+d\n", number);
To write the formatted integer to a string:
sprintf (numberArray, "%+d\n", number);
Here is a good reference for printf format strings:
http://www.cplusplus.com/reference/cstdio/printf/
scanf("%c", &number);
will give you the ASCII value of one char given in the input, that's why the numbers that printed aren't those you write.
you should change it to
scanf("%d", &number);
this way it will get the right input
if (number < 0) {
printf("%d", -number);
} else {
printf("+%d", number);
}
should suffice. Let the standard library routines do their work.
Related
I want to input an array of integers then print out the even numbers from the inputted numbers..
example is if I input 2466688992,
it will output 24666882;
I have a my code below:
#include<stdio.h>
int main()
{
int a[5],i;
printf("Enter array of numbers: ");
scanf("%d",&a);
for(i=0; i<sizeof(a); i++){
if(a[i]%2==0)
printf("%d",a[i]);
}
getch();
return 0;
}
It resulted into garbage : 2468000075416640419940000004225568000
This is the function that prints even numbers in an integer :
#include<stdio.h>
int main(){
int num,rem,even=0,digit;
printf(" Enter an integer number: ");
scanf("%d",&num);
printf("\n The even digits present in %d are \n",num);
while(num>0){
digit = num % 10;
num = num / 10;
rem = digit % 2;
if(rem == 0)
even++;
printf("\n %d.",digit);
}
return 0;
}
You should scan the array as a string (unless you want to impose the number of items in the array), and then parse the string to store the different numbers:
long a[50];
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
int j = 0;
for (int i = 0; i < len; ) {
long sign = 1;
long n = 0;
if (buf[i] == '+') {
++i;
}
else if (buf[i] == '-') {
sign = -1;
++i;
}
if (isdigit(buf[i])) {
while (isdigit(buf[i])) {
n = 10 * n + buf[i++] - '0';
}
a[j] = n * sign;
}
else
i++;
}
for (int i = 0; i < j; i++)
if (!(a[i] ℅ 2)) // true if even
printf("%ld ", a[i]);
This will store all your digits in your array a of size j.
Edit: if you are talking about digits then its easier:
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
for (int i = 0; i < len; i++)
if (isdigit(buf[i]) && !((buf[i] - '0') ℅ 2)) // true if even, note that '0' equals 0x30 so there is no need to sub it to check for odd/even in reality.
printf("%c ", buf[i]);
test case:
input: 1234
output: 24
input: 2468
output: 2468
input: 6
output: 6
I have this code:
#include <stdio.h>
#include <math.h>
int main() {
int num;
printf("Enter a number: \n");
scanf("%d", &num);
int numberLength = floor(log10(abs(num))) + 1;
int inputNumberArray[numberLength];
int evenNumberCount = 0;
int even[10];//new even no. array
int i = 0;
do {
inputNumberArray[i] = num % 10;
num = num / 10;
i++;
} while (num != 0);
i = 0;
while (i < numberLength) {
if (inputNumberArray[i] % 2 == 0) {
evenNumberCount ++;
even[i] = inputNumberArray[i];
}
i++;
}
printf("array count %d\n", evenNumberCount);
i = 0;
for (i = 0; i < 8; i++) {
printf(" %d", even[i]);//print even array
}
i = 0;
int result = 0;
for (i = 0; i < 10; i++) {
if (evenNumberCount == 1) {
if (even[i] != 0) {
result = even[i];
} else {
break;
}
} else {
if (even[i] != 0) {
result = result + even[i] * pow(10, i);
} else
break;
}
}
printf("\nresult is %d", result);
/*
int a = 0;
a = pow(10, 2);
printf("\na is %d", a);
*/
}
when I enter number 1234, the result/outcome is 4, instead of 24.
but when I test the rest of test case, it is fine.
the wrong code I think is this: result = result + even[i] * pow(10, i);
Can you help on this?
Thanks in advance.
why do you have to read as number?
Simplest algorithm would be
Read as text
Validate
loop through and confirm if divisible by 2 and print live
next thing, have you try to debug?
debug would let you know what are doing wrong. Finally the issue is with indexing.
evenNumberCount ++; /// this is technically in the wrong place.
even[i]=inputNumberArray[i]; /// This is incorrect.
As the user Popeye suggested, an easier approach to accomplish this would be to just read in the entire input from the user as a string. With this approach, you can iterate through each letter in the char array and use the isdigit() method to see if the character is a digit or not. You can then easily check if that number is even or not.
Here is a quick source code I wrote up to show this approach in action:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char input[100] = { '\0' };
char outputNum[100] = { '\0' };
// Get input from user
printf("Enter a number: ");
scanf_s("%s", input, sizeof(input));
// Find the prime numbers
int outputNumIndex = 0;
for (int i = 0; i < strlen(input); i++)
{
if (isdigit(input[i]))
{
if (input[i] % 2 == 0)
{
outputNum[outputNumIndex++] = input[i];
}
}
}
if (outputNum[0] == '\0')
{
outputNum[0] = '0';
}
// Print the result
printf("Result is %s", outputNum);
return 0;
}
I figured out the solution, which is easier to understand.
#include <stdio.h>
#include <math.h>
#define INIT_VALUE 999
int extEvenDigits1(int num);
void extEvenDigits2(int num, int *result);
int main()
{
int number, result = INIT_VALUE;
printf("Enter a number: \n");
scanf("%d", &number);
printf("extEvenDigits1(): %d\n", extEvenDigits1(number));
extEvenDigits2(number, &result);
printf("extEvenDigits2(): %d\n", result);
return 0;
}
int extEvenDigits1(int num)
{
int result = -1;
int count = 0;
while (num > 1) {
int digit = num % 10;
if (digit % 2 == 0) {
result = result == -1 ? digit : result + digit * pow(10, count);
count++;
}
num = num / 10;
}
return result;
}
}
You are overcomplicating things, I'm afraid.
You could read the number as a string and easily process every character producing another string to be printed.
If you are required to deal with a numeric type, there is a simpler solution:
#include <stdio.h>
int main(void)
{
// Keep asking for numbers until scanf fails.
for (;;)
{
printf("Enter a number:\n");
// Using a bigger type, we can store numbers with more digits.
long long int number;
// Always check the value returned by scanf.
int ret = scanf("%lld", &number);
if (ret != 1)
break;
long long int result = 0;
// Use a multiple of ten as the "position" of the resulting digit.
long long int power = 1;
// The number is "consumed" while the result is formed.
while (number)
{
// Check the last digit of what remains of the original number
if (number % 2 == 0)
{
// Put that digit in the correct position of the result
result += (number % 10) * power;
// No need to call pow()
power *= 10;
}
// Remove the last digit.
number /= 10;
}
printf("result is %lld\n\n", result);
}
}
I am trying to input a phone number and print it out in this format (888)999-1111 format but when i am trying to print it out i get some weird output that is not what i am expecting to get back out. I am printing out the values of phone both in the input and in the print function bt they are different. The one in the input function is correct but it isnt correct in the print function. Thanks in advance for the help.
int phoneInput(void)
{
long int phone = 0;
printf("Input the politicians phone number with no speaces: ");
scanf("%ld", &phone);
printf("test : %ld", phone);
return phone;
}
int printPhone(long int phone)
{
int i = 10; //the number of digits in the phone
char output[11];
printf("Test: %ld", phone);
for (i = 0; i < 10; i ++)
{
while (phone > 0)
{
output[i] = phone % 10;
phone /= 10;
}
}
printf("- Phone number: (");
i = 0;
for (i = 0; i < 3; i++)
{
printf("%d", output[i]);
}
printf(")");
i = 3;
for(i = 3; i < 6; i++)
{
printf("%d", output[i]);
}
i = 6;
printf("-");
for(i = 6; i < 10; i++)
{
printf("%d", output[i]);
}
return 0;
}
The only reason you'd need to store a value as an int, a long int, or another numeric type is if you had to do arithmetic on it (unless it's required by a homework assignment specification). Don't be fooled by the fact that a phone number is composed of numbers - it makes most sense to be stored as a string!
If you can store the phone number as a string, you should:
char *phoneInput(void)
{
static char phone[100];
printf("Input the politicians phone number with no spaces: ");
fgets(phone, 100, stdin);
return phone;
}
Once you have that, it's easier to control how it is printed:
printf("(%.3s) %.3s-%.4s\n", phone, phone + 3, phone + 6);
A phone number should be stored as country, area, subscriber.
The example you gave would be 1 888 9991111
And note that any leading 00 for a country number is actually the local method of instructing the switch to dial an international number. In Spain it used to be 9 for a long time. The generic identification for international number dialing is now +.
See also https://www.internationalcitizens.com/international-calling-codes/
Sarah, first of all I would scan phone number as string, it is easier to do it that way. Another reason to scan it as string long int might not be sufficient enough, on some platforms long is 32 bits. But if you require 'long int` the best way would be:
printf ("(%ld)", number / 10000000); // prints area code (xxx)
printf (" %ld-", (number / 1000) % 1000); // prints xxx-
printf ("%ld\n", number % 10000); // prints xxxx\n
another way would be:
fscanf( stdin, " %3s%3s%4s", areacode, zone, number);
printf("(%s) %s-%s\n", areacode, zone, number);
In your existing code, the problem lies in the loops:
for (i = 0; i < 10; i ++)
{
while (phone > 0)
{
output[i] = phone % 10;
phone /= 10;
}
}
Your inner loop will keep executing without incrementing i causing the same position in the array to be written again and again.
i = 9;
do
{
output[i] = (phone % 10) + '0';
phone /= 10;
i--;
}while((phone > 0) && (i >= 0));
Please use "%c" in the printf while printing output.
List of issues in the code posted by OP. These are just issues in the
code posted by OP. The logic can be done in many other ways, but, this
answer purely focuses on issues in OP's code as-is:
phoneInput function should return long int instead of int
for and while loop - Two loops are not needed. This is the main error. This causes same position in array to be overwritten each time.
Loop counter for array position starts from 0, causing digits to be written in reverse order in the array
Since, you are using a char array, store and print char instead of int.
Complete code with issues fixed (as per OP's original code):
#include <stdio.h>
#include <string.h>
long int phoneInput(void)
{
long int phone = 0;
printf("Input the politicians phone number with no spaces: ");
scanf("%ld", &phone);
printf("test : %ld\n", phone);
return phone;
}
int printPhone(long int phone)
{
int i = 10; //the number of digits in the phone
char output[11];
memset(output, '0', sizeof(output));
printf("Test: %ld\n", phone);
i = 9;
do
{
output[i] = (phone % 10) + '0';
phone /= 10;
i--;
}while( (phone > 0) && (i >= 0));
printf("- Phone number: (");
i = 0;
for (i = 0; i < 3; i++)
{
printf("%c", output[i]);
}
printf(")");
i = 3;
for(i = 3; i < 6; i++)
{
printf("%c", output[i]);
}
i = 6;
printf("-");
for(i = 6; i < 10; i++)
{
printf("%c", output[i]);
}
return 0;
}
void main()
{
long int phone;
phone = phoneInput();
printPhone(phone);
}
Output:
Input the politicians phone number with no spaces: 8889991111
test : 8889991111
Test: 8889991111
- Phone number: (888)999-1111
I've made a few changes to your code. Please take a look.
long long int phoneInput(void)
{
long long int phone = 0;
printf("Input the politicians phone number with no speaces: ");
scanf("%lld", &phone);
printf("test : %lld", phone);
return phone;
}
int printPhone(long long int phone)
{
int i = 10; //the number of digits in the phone
char output[11];
printf("Test: %lld", phone);
i = 9; // removed for loop that was unnecessary.
while (phone > 0)
{
output[i] = phone % 10;
phone /= 10;
i--;
}
printf("- Phone number: (");
i = 0;
for (i = 0; i < 3; i++)
{
printf("%d", output[i]);
}
printf(")");
i = 3;
for(i = 3; i < 6; i++)
{
printf("%d", output[i]);
}
i = 6;
printf("-");
for(i = 6; i < 10; i++)
{
printf("%d", output[i]);
}
return 0;
}
int main(int argc, char const *argv[])
{
long long int n = phoneInput();
printPhone(n);
return 0;
}
void printTelephoneNumber(vector phoneNum) {
string phonePad[10] {
"000", "111", "ABC", "DEF", "GHI", "JKL", "MNO", "PRS", "TUV", "WXY"
};
size_t PHONE_NUMBER_LENGTH = phoneNum.size();
size_t LETTERS_PER_KEY = 3;
size_t maxcount = (size_t )pow(LETTERS_PER_KEY, PHONE_NUMBER_LENGTH);
// Could have used: colIndex[PHONE_NUMBER_LENGTH] = {0};
vector<int> letterIndex(PHONE_NUMBER_LENGTH, 0); // Use either name: colIndex or charIndex
for(int count=0; count<maxcount; count++) {
// print string
string str = "";
for(int i=0; i<PHONE_NUMBER_LENGTH; i++) {
str += phonePad[phoneNum[i]][letterIndex[i]];
}
cout << str << endl;
// Update next letter (column) indicies
int nextCount = count + 1; // next count
size_t i = PHONE_NUMBER_LENGTH - 1;
do {
letterIndex[i] = nextCount % LETTERS_PER_KEY;
nextCount = nextCount / LETTERS_PER_KEY;
i--;
} while(nextCount > 0);
}
}
Algorithm: There are 3^n combinations for n digits phone number. examples: phoneNum[n] = {2,3,4} => 3^3 = 27. Use extra space for tracking letters in a digit => letterIndex[PHONE_NUMBER_LENGTH]
while (phone > 0)
{
output[i++] = (phone % 10) + '0';
phone /= 10;
}
and
printf("%c", output[i]);
are the changes that need to be made in your code to make it work.
The first change (+ '0') is to convert from int to char.
The second one is because you want to print a char and not an int.
I advise you to check the manual of printf and the ascii table to understand better.
Assigned task is to ask for # of values, and then at the end output the minimum, maximum, and average values and at this point I've run out of bug fixes
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
int ErrorDetection = 1;
char valCounter;
int valnumber;
int Incrementer;
int StoredValue;
int MinimumValue = 100;
int MaximumValue = 0;
float Average;
int AddToStored;
int Sum = 0;
printf("MIN, MAX, and MEAN CALCULATOR\n\n");
while (ErrorDetection != 0)
{
printf("How many values are to be entered?\n");
scanf("%s", &valCounter);
if (valCounter > '0' && valCounter < '9') {
ErrorDetection = 0;
}
else {
ErrorDetection = 1;
printf("INPUT ERROR!\n");
}
valCounter = valCounter - 47;
}
for (Incrementer = 1; Incrementer < valCounter; Incrementer++)
{
ErrorDetection = 1;
while (ErrorDetection != 0) {
printf("Value %d: ", Incrementer);
scanf(" %d", &StoredValue);
if (StoredValue > 0 && StoredValue < 9) {
ErrorDetection = 0;
}
else {
ErrorDetection = 1;
printf("INPUT ERROR!\n");
continue;
}
}
if (StoredValue > MaximumValue) {
MaximumValue = StoredValue;
}
if (StoredValue <= MinimumValue) {
MinimumValue = StoredValue;
}
Sum = Sum + StoredValue;
}
valCounter = valCounter - 1;
Average = (float)Sum / (float)valCounter;
printf(
"Minimum value is %d, maximum value is %d, and average value is %g.\n",
MinimumValue, MaximumValue, Average
);
}
If you input a 2 digit number things begin to breakdown, but at the same time I don't know how to go through with errorchecking if I allow multiple digit answers, as I make use of ASCII conversions to check if an input is a number or not.
You have undefined behavior here.
char valCounter;
scanf("%s", &valCounter);
You have declared valCounter as char type but trying to read string type.
Hence change the scanf to.
scanf("%c", &valCounter);
I would suggest you declare valCounter as int
int valCounter;
scanf("%d", &valCounter);
in that case your if will become.
if ((valCounter > 0) && (valCounter < 9))
and you don't need
valCounter = valCounter - 47; //remove
Also your for loop should start from 0 instead of 1
for(Incrementer = 1 ; Incrementer < valCounter; Incrementer++)
should be
for(Incrementer = 0 ; Incrementer < valCounter; Incrementer++)
Your problem is here.
char valCounter;
scanf("%s", &valCounter);
You're telling scanf to read a string, but you're passing it the address of a character. You should be asking for an integer, and giving it the address of an integer.
int valCounter;
scanf("%d", &valCounter)
There's more information here, including reasons why scanf might not be the best idea:
How to scanf only integer?
I made a C program to check if a number is palindrome or not. I used the following code, but it shows numbers like 12321 as non palindrome. Can you please explain me the mistake in the program below?
#include <stdio.h>
int main()
{
int i, x, n, c, j;
int d=0;
printf ("enter total digits in number: ");
scanf ("%d", &i);
printf ("\nenter number: ");
scanf ("%d", &n);
j=n;
for (x=1; x<=i; x++)
{
c= j%10;
d=c*(10^(i-x))+d;
j=(j-c)/10;
}
if (d==n)
{
printf ("\npalindrome");
}
else
{
printf ("\nnon palindrome");
}
return 0;
}
^ is the xor operator.
In order to raise power, you need to include math.h and call pow
d = (c * pow(10, i - x)) + d;
this algorithm is as simple as human thinking, and it works
#include <stdio.h>
int main() {
int i=0,n,ok=1;
char buff[20];
printf("Enter an integer: ");
scanf("%d", &n); // i am ommiting error checking
n=sprintf(buff,"%d",n); //convert it to string, and getting the len in result
if(n<2) return 0;
i=n/2;
n--;
while(i && ok) {
i--;
//printf("%c == %c %s\n", buff[i],buff[n-i],(buff[i]==buff[n-i])?"true":"false");
ok &= (buff[i]==buff[n-i]);
}
printf("%s is %spalindrome\n",buff, ok?"":"not ");
return 0;
}
// Yet another way to check for palindrome.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int n, rn, tn;
printf("Enter an integer: ");
scanf("%d", &n);
// reverse the number by repeatedly extracting last digit, add to the
// previously computed partial reverse times 10, and keep dropping
// last digit by dividing by 10
for (rn = 0, tn = n; tn; tn /= 10) rn = rn * 10 + tn % 10;
if (rn == n) printf("%d is palindrome\n", n);
else printf("%d is not palindrome\n", n);
}
A loop like this might do:
int src; // user input
int n; // no of digits
int res = 0;
int tmp; // copy of src
// .... read the input: n and src ....
tmp = src;
for(int i = 0; i < n; i ++)
{
int digit = tmp % 10; // extract the rightmost digit
tmp /= 10; // and remove it from source
res = 10*res + digit; // apend it to the result
}
// ...and test if(res == src)...