This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Program not doing what it should - C
Hello,
Following program only read numbers from input and do stop when rull is violated, but 1 big problem is that it doesn't stop reading numbers and worse, don't print on screen what it should.
The code:
#include <stdio.h>
#include <string.h>
void SIFT(int x_arr[ ], int y_arr[]);
int main ()
{
int x[20] = {0} , y[20] = {0};
int m=0,temp=0,curr=0,i=0,j=0;
printf("Please enter your numbers now:\n\n");
/*enter numbers one by one. if x[i+1] value < x[i] value, err msg.
when user want to end the series he must enter '0' which means end of string (it wont included in x[]) */
while ( (scanf("%d",&temp) ) != '0' )
{
if (temp >= curr)
{
x[i] = temp;
curr = temp;
i++;
}
else
{
printf("The numbers are not at the right order !\n\nProgram will now terminate...\n\n");
}
}
SIFT(x,y);
for (i=0 ; y[i]=='0' ; i++) /*strlen(y) without ('0')'s includes*/
m++;
/*Prints m , y's organs*/
printf("\n\nm = %d",m);
printf("Y = ");
while (y[j]!='0')
{
printf ("%d ,",y[j]);
j++;
}
return 0;
}
void SIFT(int x_arr[ ], int y_arr[])
{
int i=0,j=0;
while (x_arr[i] != '0')
{
if (x_arr[i] == x_arr[i+1]) /*if current val. equals next val. -> jump dbl at x_arr*/
{
y_arr[j] = x_arr[i];
i+=2;
j++;
}
else
{
y_arr[j]=x_arr[i];
i++;
j++;
}
}
}
Please help me solve this problem...
thnx.
As a first hint, scanf returns the number of items read, so the condition (scanf("%d",&temp) ) != '0' will only be hit if you read 48 items (the ASCII value of 0). This isn't going to happen with that format specifier so that's why you've got the loop.
Related
I am solving this problem:
Given a string str containing alphanumeric characters, calculate sum
of all numbers present in the string.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test
cases follow. Each test case contains a string containing alphanumeric characters.
Output:
Print the sum of all numbers present in the string.
Constraints:
1 <= T<= 105
1 <= length of the string <= 105
Example:
Input:
4
1abc23
geeks4geeks
1abc2x30yz67
123abc
Output:
24
4
100
123
I have come up with the following solution:
#include <stdio.h>
#include <string.h>
int main() {
//code
int t,j;
char a[100000];
scanf("%d",&t);
while(t--)
{
int sum=0,rev=0,i=0,l;
scanf("%s",a);
l=strlen(a);
for(i=0;i<l;i++)
{
if (isdigit(a[i])){
while(isdigit(a[i])){
rev = rev *10 + (a[i]-48);
i++;
}
}
sum+=rev;
rev=0;
}
printf("%d\n",sum);
}
return 0;
}
This code is working fine.
BUT if loop termination condition is changed from i < l to a[i]!='\0', then code doesn't work. Why?
I would loop backwards over the string. No nested loops. Just take the 10s exponent as you move left
You have the length of the string, so there should be no reason to check for NUL char yourself
(untested code, but shows the general idea)
#include <math.h>
l=strlen(a);
int exp;
exp = 0;
for(i = l-1; i >= 0; i--)
{
if (isdigit(a[i])) {
rev = a[i]-48; // there are better ways to parse characters to int
rev = (int) pow(10, exp) * rev;
sum += rev; // only add when you see a digit
} else { exp = -1; } // reset back to 10^0 = 1 on next loop
exp++;
}
Other solutions include using regex to split the string on all non digit characters, then loop and sum all numbers
You will have to change the logic in your while loop as well if you wish to change that in your for loop condition because it's quite possible number exists at the end of the string as well, like in one of your inputs 1abc2x30yz67. So, correct code would look like:
Snippet:
for(i=0;a[i]!='\0';i++)
{
if (isdigit(a[i])){
while(a[i]!='\0' && isdigit(a[i])){ // this line needs check as well
rev = rev *10 + (a[i]-48);
i++;
}
}
sum+=rev;
rev=0;
}
On further inspection, you need the condition of i < l anyways in your while loop condition as well.
while(i < l && isdigit(a[i])){
Update #1:
To be more precise, the loop while(isdigit(a[i])){ keeps going till the end of the string. Although it does not cause issues in the loop itself because \0 ain't a digit, but a[i] != '\0' in the for loop condition let's you access something beyond the bounds of length of the string because we move ahead 1 more location because of i++ in the for loop whereas we already reached end of the string inside the inner while loop.
Update #2:
You need an additional check of a[i] == '\0' to decrement i as well.
#include <stdio.h>
#include <string.h>
int main() {
//code
int t,j;
char a[100000];
scanf("%d",&t);
while(t--)
{
int sum=0,rev=0,i=0,l;
scanf("%s",a);
l=strlen(a);
for(i=0;a[i]!='\0';i++)
{
if (isdigit(a[i])){
while(a[i] != '\0' && isdigit(a[i])){ // this line needs check as well
rev = rev *10 + (a[i]-48);
i++;
}
}
if(a[i] == '\0') i--; // to correctly map the last index in the for loop condition
sum+=rev;
rev=0;
}
printf("%d\n",sum);
}
return 0;
}
Update #3:
You can completely avoid the while loop as well as shown below:
#include <stdio.h>
#include <string.h>
int main() {
//code
int t,j;
char a[100005];
scanf("%d",&t);
while(t--)
{
int sum=0,rev=0,i=0,l;
scanf("%s",a);
l=strlen(a);
for(i=0;i<l;i++) {
if (isdigit(a[i])){
rev = rev * 10 + (a[i]-48);
}else{
sum += rev;
rev = 0;
}
}
printf("%d\n",sum + rev); // to also add last rev we captured
}
return 0;
}
Other answers have pointed out the correct loop conditions to ensure proper operation of your program.
If you are allowed to use library functions other than isdigit, I would recommend using strtol with the EndPtr parameter (output parameter that points to the character in the string that caused strtol to stop scanning a number):
char str[] = "1abc23def5678ikl";
int main()
{
char *pStop = str;
int n, accum = 0;
size_t len = strlen(str);
do
{
n = strtol(pStop, &pStop, 10);
pStop++;
if(n)
{
printf("%d\n", n);
accum += n;
}
}
while(pStop < &str[len]);
printf("Total read: %d\n", accum);
return 0;
}
The Program:
This was supposed to be a simple reverse polish notation addition program, please ignore the EOF break thing, it's a placeholder.
Input is c, always one numeral number, it gets transfered to x where every next numeral c will be added to the number x, so for example when we input c as 1,2 and 3 x will be 123.
When we input 'e' it will mark the start of a new number, and x will be transfered to the stack[0] after the entire stack gets pushed back, and x will become 0. When inputing '+' addition happens, the last two numbers will be summed, x and the first number in the stack, or the first and second number in the stack, or the first number in the stack will duplicate itself.
The Problem:
The first number in the stack array will randomly become 0 and I cannot see where I made the error. The first number (stack[0]) only gets the value zero at the start, never again. At times when inputting '+' it will just get a value.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int stack[16];
int x;
int i;
char c;
//int c;
x=0;
for (i = 0; i < 16; i++)
{
stack[i]=0;
}
while(1)
{
//input character
scanf("%s", &c);
if (c == EOF) break;
//put x to stack
else if (c == 'e')
{for (i = 15; i >0; i--)
{
stack[i]=stack[i-1];
}
stack[0] = x;
x = 0;
}
//reverse polish addition
else if (c == '+')
//if x is 0 go immediately to the stack
{if (x == 0)
//if both x and the second number in array are 0 just duplicate the first number
if (stack[1] == 0)
stack[0] = stack[0] + stack[0];
//if only x is 0 add the first number on the second
else
{
stack[0]=stack[0]+stack[1];
//push back the array to fill the gap on the second number
for (i = 1; i <15; i++)
{
stack[i]=stack[i+1];
}
}
else
{
stack[0] = stack[0] + x;
x = 0;
}
}
else
{
x = x * 10 + ((int)c-0x30);
// putchar(c);
}
printf("X=%d\n",x);
//print stack
for (i = 0; i < 16; i++)
{
printf("%d \t",stack[i]);
}
printf("\n");
}
return 0;
}
Problem 1
scanf("%s", &c); causes undefined behavior. Use scanf(" %c", &c);.
Problem 2
c is never going to be equal to EOF by using scanf. Hence, the following line is useless.
if (c == EOF) break;
The following will take care of both problems.
// Use " %c" instead of "%c" to skip leading whitespace characters.
while ( scanf(" %c", &c) == 1 )
{
}
The question is that show the digits which were repeated in C.
So I wrote this:
#include<stdio.h>
#include<stdbool.h>
int main(void){
bool number[10] = { false };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] == true)
{
printf("%d ", digit);
}
number[digit] = true;
n /= 10;
}
return 0;
}
But it will show the repeated digits again and again
(ex. input: 55544 output: 455)
I revised it:
#include<stdio.h>
int main(void){
int number[10] = { 0 };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] == 1)
{
printf("%d ", digit);
number[digit] = 2;
}
else if (number[digit] == 2)
break;
else number[digit] = 1;
n /= 10;
}
return 0;
}
It works!
However, I want to know how to do if I need to use boolean (true false), or some more efficient way?
To make your first version work, you'll need to keep track of two things:
Have you already seen this digit? (To detect duplicates)
Have you already printed it out? (To only output duplicates once)
So something like:
bool seen[10] = { false };
bool output[10] = { false };
// [...]
digit = ...;
if (seen[digit]) {
if (output[digit])) {
// duplicate, but we already printed it
} else {
// need to print it and set output to true
}
} else {
// set seen to true
}
(Once you've got that working, you can simplify the ifs. Only one is needed if you combine the two tests.)
Your second version is nearly there, but too complex. All you need to do is:
Add one to the counter for that digit every time you see it
Print the number only if the counter is exactly two.
digit = ...;
counter[digit]++;
if (counter[digit] == 2) {
// this is the second time we see this digit
// so print it out
}
n = ...;
Side benefit is that you get the count for each digit at the end.
Your second version code is not correct. You should yourself figured it out where are you wrong. You can try the below code to print the repeated elements.
#include<stdio.h>
int main(void){
int number[10] = { 0 };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] > 0)
{
number[digit]++;;
}
else if (number[digit] ==0 )
number[digit] = 1;
n /= 10;
}
int i=0;
for(;i<10; i++){
if(number[i]>0)
printf("%d ", i);
}
return 0;
}
In case you want to print the repeated element using bool array (first version) then it will print the elements number of times elements occur-1 times and in reverse order because you are detaching the digits from the end of number , as you are seeing in your first version code output. In case you want to print only once then you have to use int array as in above code.
It is probably much easier to handle all the input as strings:
#include <stdio.h>
#include <string.h>
int main (void) {
char str[256] = { 0 }; /* string to read */
char rep[256] = { 0 }; /* string to hold repeated digits */
int ri = 0; /* repeated digit index */
char *p = str; /* pointer to use with str */
printf ("\nEnter a number: ");
scanf ("%[^\n]s", str);
while (*p) /* for every character in string */
{
if (*(p + 1) && strchr (p + 1, *p)) /* test if remaining chars match */
if (!strchr(rep, *p)) /* test if already marked as dup */
rep[ri++] = *p; /* if not add it to string */
p++; /* increment pointer to next char */
}
printf ("\n Repeated digit(s): %s\n\n", rep);
return 0;
}
Note: you can also add a further test to limit to digits only with if (*p >= '0' && *p <= '9')
output:
$./bin/dupdigits
Enter a number: 1112223334566
Repeated digit(s): 1236
Error is here
if (number[digit] == true)
should be
if (number[digit] == false)
Eclipse + CDT plugin + stepping debug - help you next time
As everyone has given the solution: You can achieve this using the counting sort see here. Time complexity of solution will be O(n) and space complexity will be O(n+k) where k is the range in number.
However you can achieve the same by taking the XOR operation of each element with other and in case you got a XOR b as zero then its means the repeated number. But, the time complexity will be: O(n^2).
#include <stdio.h>
#define SIZE 10
main()
{
int num[SIZE] = {2,1,5,4,7,1,4,2,8,0};
int i=0, j=0;
for (i=0; i< SIZE; i++ ){
for (j=i+1; j< SIZE; j++){
if((num[i]^num[j]) == 0){
printf("Repeated element: %d\n", num[i]);
break;
}
}
}
}
I wanted to make a C program that finds the numbers in the input array and then multiplies it all together, I made the program but it got an issue that I don't know, can anybody help me with it!?
Here is the code!
#include <stdio.h>
#include <stdlib.h>
int main ()
{
char t[10];
int n, z;
n = 0;
printf ("please enter a code: \n");
scanf ("%s", t);
while (n != '\0')
{
if (isdigit (t[n] == 0))
{
n++;
}
else
{
z = t[n];
z *= z;
}
}
printf ("%d", z);
}
Here is updated code. There is a comment for each bug that needed correction.
(Note that the comment describes the intention of the corrected code, it doesn't describe the bug.)
int temp;
z=1; // Initialize z
printf ("please enter a code: \n");
scanf ("%s", n);
while (t[n] != '\0') { // While there are more characters in the string
if (isdigit (t[n])) { // Check if the character is a digit
temp = t[n] - '0'; // Convert character digit to corresponding number.
z *= temp;
}
n++;
}
Your first problem is that you don't actually use t in your while loop. Your while loop only uses n which is set to 0 and never modified.
Your second problem is that you may be better off to use scanf("%d", &number); to scan numbers straight away.
z should be initialized to 1. and remove "z = t[n];"
#include <stdio.h>
#include <string.h>
main()
{
char a[5] ;
int b=1, n=0,m=0;
scanf("%s",a);
while (n <5 )
{
if (!isdigit(a[n]))
{
n++;
m++;
}
else{
b *= (a[n]-'0');
n++;
}
}
if(m==5) b=0;
printf("%d\n",b);
}
I'm having difficult while trying to install a cross compiler under linux.
I downloaded a toolchain that seems to be ok but what's next ? what orders I need to type in the console to make it to be installed ?
The purpose is to convert a C code to MIPS (little endian) code.
Actually I need it once for only 2 codes, so if someone can only show me those codes in MIPS, I will be more than happy...
first code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 128
int main ()
{
char mychar , string [SIZE];
int i;
int count =0 ;
printf ("Please enter your string: \n\n");
fgets (string, SIZE, stdin);
printf ("Please enter char to find: ");
mychar = getchar();
for (i=0 ; string[i] != '\0' ; i++ )
if ( string[i] == mychar )
count++;
printf ("The char %c appears %d times\n" ,mychar ,count);
return 0;
}
second code:
#include <stdio.h>
#include <string.h>
void SIFT(int x_arr[ ], int y_arr[]);
int main ()
{
int x[20] = {0} , y[20] = {0};
int m=0,temp=0,curr=0,i=0,j=0;
printf("Please enter your numbers now:\n\n");
/*enter numbers one by one. if x[i+1] value < x[i] value, err msg.
when user want to end the series he must enter '0' which means end of string (it wont included in x[]) */
while ( (scanf("%d",&temp) ) != 5 )
{
if (temp >= curr)
{
x[i] = temp;
curr = temp;
i++;
}
else
{
printf("The numbers are not at the right order !\n\nProgram will now terminate...\n\n");
}
}
SIFT(x,y);
for (i=0 ; y[i]=='0' ; i++) /*strlen(y) without ('0')'s includes*/
m++;
/*Prints m , y's organs*/
printf("\n\nm = %d",m);
printf("Y = ");
while (y[j]!='0')
{
printf ("%d ,",y[j]);
j++;
}
return 0;
}
void SIFT(int x_arr[ ], int y_arr[])
{
int i=0,j=0;
while (x_arr[i] != '0')
{
if (x_arr[i] == x_arr[i+1]) /*if current val. equals next val. -> jump dbl at x_arr*/
{
y_arr[j] = x_arr[i];
i+=2;
j++;
}
else
{
y_arr[j]=x_arr[i];
i++;
j++;
}
}
}
You may want to try using crosstool-NG to build and install a toolchain for your system.
I'm not sure if this will help you but I've compiled your source files using ecc (http://ellcc.org) and got:
http://pastebin.com/keDPEcsc
and
http://pastebin.com/zQBsMVfS
Hope that helps.
you need to build you own version with toolchain - it is not a compiler on it's own, it will make one. look at http://www.kegel.com/crosstool/crosstool-0.43/doc/crosstool-howto.html