Looping to look for non-repeated digits - c

I have a C program that I am working on which entails to find the first nonrepeated, last nonrepeated digit in an array. I am lost in how to accomplish this. Can anybody help me with the loop control variable to get those two things done ? My loop keeps returning a negative number.
Here is what I have:
for(p = 0; p <= i;p ++ ){
for(u=p+1;u>=1;u--){
if(digits[p] > digits[u]);
firstnon = digits[p];
}
}
if(firstnon){
printf("The first non-repeated digit is: %d",firstnon);
}
else{
printf("There isn't any non-repeated digits");
}
printf("\n");
for(c=0;c<= sizeof(digits)/sizeof(int);c++){
for(k=1;k<sizeof(digits);k++){
if(digits[c]==digits[k]){
lastnon = digits[k];
}
}
}
if(c==k){
printf("The last non-repeated digit is: %d\n",lastnon);
}

Have some problems in your code:
This line: if(digits[p] > digits[u]); don't do what you expect i think, see the last char ;, this kill the propose of the if statement. And the following line don't belong to the if block.
This sizeof(digits) return the size of digits in bytes, if the elements of digits are not bytes, you would be indexing the array with out of bound index (with k).
I don't understand really the search for last non-repeating digit, you are setting lastnon when digits[c] == digits[k], i don't think that it correct if i understand correctly the problem statement.
Here is a naive approach:
#include <stdio.h>
int main() {
int p, u, firstnon = -1, lastnon = -1, digit_repeat;
int digits[10] = { 1, 2, 3, 1, 3, 5, 1, 2, 4, 3};
int digits_size = sizeof(digits) / sizeof(digits[0]);
for (p = 0; p < digits_size; p++) {
digit_repeat = 0;
for (u = 0; u < digits_size; u++) {
if (p != u && digits[p] == digits[u]) {
digit_repeat = 1;
break;
}
}
if (!digit_repeat) {
firstnon = p;
break;
}
}
if (firstnon != -1) {
printf("The first non-repeated digit is: %d", digits[firstnon]);
} else {
printf("There isn't any non-repeated digits");
}
printf("\n");
for (p = digits_size - 1; p >= 0; p--) {
digit_repeat = 0;
for (u = 0; u < digits_size; u++) {
if (p != u && digits[p] == digits[u]) {
digit_repeat = 1;
break;
}
}
if (!digit_repeat) {
lastnon = p;
break;
}
}
if (lastnon != -1) {
printf("The last non-repeated digit is: %d", digits[lastnon]);
} else {
printf("There isn't any non-repeated digits");
}
printf("\n");
return 0;
}
To find the first non repeating digits.
Iterate through the digits.
In every digits, check the other digits (all) for the same digit in another position.
If there is another, continue
If there only one, saved, and break search.
The same apply for last non repeating digits, but the iteration is in reverse.
Some improve version.
#include <stdio.h>
int main() {
int p;
int digits[10] = { 1, 2, 3, 1, 3, 5, 1, 2, 4, 3};
int digits_size = sizeof(digits) / sizeof(digits[0]);
int used_digits[10] = { 0 };
int used_digits_size = sizeof(used_digits) / sizeof(used_digits[0]);
for (p = 0; p < digits_size; p++) {
used_digits[digits[p]]++;
}
for (p = 0; p < used_digits_size; p++) {
if (used_digits[p] == 1) {
printf("The first non-repeated digit is: %d", p);
break;
}
}
if (p == used_digits_size) {
printf("There isn't any non-repeated digits");
}
printf("\n");
for (p = used_digits_size - 1; p >= 0; p--) {
if (used_digits[p] == 1) {
printf("The last non-repeated digit is: %d", p);
break;
}
}
if (p == -1) {
printf("There isn't any non-repeated digits");
}
printf("\n");
return 0;
}
This version use an array to storage the usage of digits. The non-repeating digits are the one with usage == 1. Search this forward and backward to find first and last non repeating digit.

Related

Floating Point Exception - One Variable Stopped Getting Updated

everyone. Could anybody help me correct the code?
#include<stdio.h>
int main (void) {
int first = 0, second = 0, product, count = 2, lcm = 0, countProduct = 0;
printf("Enter the first integer: ");
scanf("%d", &first);
printf("Enter the second integer: ");
scanf("%d", &second);
product = -1;
while (product % first != 0 && product % second != 0){
if (first % second == 0) {
lcm = first;
break;
}else if (second % first == 0)
{
lcm = second;
break;
} else if (first > second)
{
countProduct = first * count;
count++;
if (countProduct % first == 0 && countProduct % second == 0)
{
lcm = countProduct;
product = lcm;
}
} else
{
countProduct = second * count;
count++;
if (countProduct % first == 0 && countProduct % second == 0)
{
lcm = countProduct;
product = lcm;
}
}
}
printf("GCD of %d and %d is %d\n", first, second, first*second / lcm);
return 0;
}
What I found out so far is that when I assign 1 to first followed by any other number, the lcm variable does not get updated but remains the value during initialization.
Everything other set I did gave me the expected output except for this.
Thank you so much.

finding prime numbers between a range in C

I am trying to find the prime numbers in a range using C language. My code does not give an output and I think there is a logical error here which I cannot figure out. Can anyone please help?
#include <stdio.h>
int main() {
int lowerLevel;
int upperLevel;
int i; //counter variable
int prime = 0;
int flag = 0;
printf("Enter the lower limit and upper limit of the range followed by a comma :");
scanf("%d %d", &lowerLevel, &upperLevel);
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
}
Your code does not check for prime numbers, it merely checks that there is at least one even number between 2 and upperlevel, which is true as soon as upperlevel >= 2. If there is such an even number, nothing is printed.
You should instead run a loop from lowerlevel to upperlevel and check if each number is a prime and if so, print it.
Here is a modified version:
#include <stdio.h>
int main() {
int lowerLevel, upperLevel;
printf("Enter the lower limit and upper limit of the range: ");
if (scanf("%d %d", &lowerLevel, &upperLevel) != 2) {
return 1;
}
for (int i = lowerLevel; i <= upperLevel; ++i) {
int isprime = 1;
for (int p = 2; p <= i / p; p += (p & 1) + 1) {
if (i % p == 0) {
isprime = 0;
break;
}
}
if (isprime) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
This method is simplistic but achieves the goal. More efficient programs would use a sieve to find all prime numbers in the range without costly divisions.
Optimal method with Sieves of Eratosthenes
You should use the sieves of Eratostenes algorithm, it is way more efficient to get the different prime number.
it does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime number, 2
Basically you consider all numbers prime by default, and then you will set as false the prime number, see below code:
#include <stdio.h>
/// unsigned char saves space compared to integer
#define bool unsigned char
#define true 1
#define false 0
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
void printPrimesRange(int lowerLevel, int n) {
if (lowerLevel < 0 || n < lowerLevel) // handle misused of function
return ;
bool isPrime[n + 1];
memset(isPrime, true, n + 1);
int cnt = 0; // NB: I use the counter only for the commas and final .\n, its optional.
if (lowerLevel <= 2 && n >= 2) { // only one even number can be prime: 2
++cnt;
printf("2");
}
for (int i = 3; i <= n ; i+=2) { // after what only odd numbers can be prime numbers
if (isPrime[i]) {
if (i >= lowerLevel) {
if (cnt++)
printf(", ");
printf("%d", i); // NB: it is better to print all at once if you can improve it
}
for (int j = i * 3; j <= n; j+=i*2) // Eratosthenes' Algo, sieve all multiples of current prime, skipping even numbers
isPrime[j] = false;
}
}
printf(".\n");
}
int main(void) {
int lowerLevel;
int upperLevel;
printf("Enter the lower limit and upper limit of the range with a space in-between:"); // space, not comma
scanf("%d %d", &lowerLevel, &upperLevel);
printPrimesRange(lowerLevel, upperLevel);
return 0;
}
Let's follow the logic of your code:
#include <stdio.h>
#include <string.h>
int main() {
int lowerLevel;
int upperLevel;
int i; //counter variable
int prime = 0;
int flag = 0;
printf("Enter the lower limit and upper limit of the range followed by a comma :");
scanf("%d %d", &lowerLevel, &upperLevel);
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
}
First of all, you have a loop:
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
this loop tries to find a number i that is a multple of 2, because as soon you get one, you jump out of the loop. So your loop can be expressed better as:
for (i = 2; i <= upperLevel && i % 2 != 0; ++i) {
}
/* i > upperLevel || i % 2 == 0 */
if (i <= upperLevel && i % 2 == 0) {
flag = 1;
}
We still need to check if i <= upperLevel && i % 2 == 0 to set the variable flag = 1 if we exited the loop because i was a multiple of 2, but the break; is not necessary because we are already out of the loop.
Now let's check that the first value we initialize i is, indeed 2 (which is a multiple of 2) and the consecuence of this is that the loop is never going to be entered. Se we can eliminate it completely, giving to:
i = 2;
if (i <= upperLevel && i % 2 == 0) {
flag = 1;
}
now, the second clause of the if test is always true, so we can take it off, giving:
i = 2;
if (i <= upperLevel) {
flag = 1;
}
Now, let's append the second part:
i = 2;
if (i <= upperLevel) {
flag = 1;
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
so, the first thing we see here is that your ++i; statement is nonsense, as it is the last statement to be
executed before exiting the program, so we can also take it off.
i = 2;
if (i <= upperLevel) {
flag = 1;
}
if (flag == 0) {
printf("%d", i);
}
return 0;
Now we see that you print the value of i only if the value of flag is zero, but flag only conserves its zero value if the value of i > upperLevel, and as i is fixed, the printing of i only occurs if you input a value of upperlevel that is less than 2.
We can rewrite the above code as this:
if (2 > upperLevel) {
printf("%d", 2);
}
Your program will print 2 only if you provide a value of upperLevel less than 2.

how to extract the even number from user input, and combine them as a new number in C program

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

C: functions won't run in a loop and read from a file

I am trying to make a program that will convert a number into its prime factorization. For example, 2048=2^11 the program will output 211 (since this value will be used in a different function.). The program then prints the prime factorization and the number in a file. The issue I'm having is having the two functions, digitCount and FdigitCount, run in a loop and read the values from the file and then compare the amount of digits in the prime factorization to the number of digits in the normal number, then if it is less, printing the numbers out.
int digitCount(int n){
int digits = 0;
while(n!=0) {
n/=10; //divides the number by 10 and adds one to the digits until it is no longer divisible by 10.
++digits;
}
return digits;
}
int fdigitCount(int p){ //this function is used the count the digits of the prime factorization.
int fdigits = 0;
while(p!=0) {
p/=10; //divides the number by 10 and adds one to the fdigits until it is no longer divisible by 10.
++fdigits;
}
return fdigits;
}
int main(void) {
FILE* primes = NULL; //file pointer to the file that will contain all the prime factors of a number
int num;
int count;
int digits;
int limit;
int i;
int j=2;
int fdigits;
int frugalNum;
int normNum;
primes = fopen("primes.txt", "w+");
if (primes == NULL){
printf("Could not open primes.txt");
}
printf("Enter a limit: ");
scanf("%d", &limit);
for (i=2; i <= limit; i++){
num = i;
j = i;
count = 0;
if (num%2 == 0){
while (num%2 == 0)
{
num = num/2;
count++;
}
if (count > 1){
fprintf(primes, "2%d", count);
}
else {
fprintf(primes, "2");
}
}
else if(num%2 != 0) {
for (int i = 3; i <= sqrt(num); i = i+2)
{
// While i divides n, print i and divide n
count = 0;
while (num%i == 0)
{
num = num/i;
count++;
}
if (count > 1){
fprintf(primes, "%d%d", i, count);
}
else if (count==1){
fprintf(primes, "%d", i);
}
}
}
if (num > 2){
fprintf (primes, "%d", num);
}
fprintf(primes, " %d", j);
fprintf(primes, "\n");
}
while (!feof(primes)){
fscanf(primes, "%d %d", &frugalNum, &normNum);
if (fdigitCount(frugalNum) < digitCount(normNum)){
printf("%d\n", normNum);
}
}
fclose(primes);
return 0;
}
You shouldn't read the file by looping until feof() returns true. It returns true after you've passed the EOF, and so the last values you read will be garbage. Change your loop to:
while (fscanf(primes, "%d %d", &frugalNum, &normNum) == 2) {
/* Do stuff with frugalNum and normNum */
}
Additionally, I couldn't help noticing that digitCount() and fdigitCount() do exactly the same thing. Why do you need both of them?

Weird bug which seems to be solved by adding a surplus line of code. Game of fifteen

This is a puzzle game where in a 4x4 grid one has to arrange 15 numbered tiles in order.
Most of the scenarios, the program runs fine. However, when swapping the "1" digit to the nth row, n-2th column, the program seems to bug and duplicate the number 1.
Here's the catch. When I add a random line of code, say
int blah = 0;
or
printf("abc");
The problem just magically disappears.
Because I'm unable to locate the source of the problem, I'll have to post up the entirety of it.
To see the problem, run the code without any command line arguments, then enter 2 followed by 1.
When I added the random line of code at the end of my main() function, the problem just disappears. Please try it out, and help me find out what's happening; it's really confusing.
#include <stdio.h>
#include <stdlib.h>
int n=4;
int win(int board[n][n]);
void print(int board[n][n]);
int main(int argc, char * argv[])
{
if(argc != 2)
{
printf("No valid number accepted. Board size set as 4x4.\n");
}
else if(argc == 2)
{
n = atoi(argv[1]);
if(n<2 || n>5)
{
printf("No valid number accepted. Board size set as 4x4.\n");
}
else
{
printf("Preparing board of size %dx%d\n",n,n);
}
}
int board[n][n];
printf("\n The aim of the game is to sort the board so that it runs in ascending order, from 1 to %d, from left to right and up to down starting from the top left square. To make a move, enter the number of the tile you want to move. No diagonal movement is allowed.\n\n",n*n-1);
int c = n*n-1;
for(int x = 0;x<n;x++)
{
for(int y=0;y<n;y++)
{
board[x][y] = c;
c--;
}
}
if(n%2==0)
{
int temp1 = board[n-1][n-2];
board[n-1][n-2] = board[n-1][n-3];
board[n-1][n-3] = temp1;
}
print(board);
int spacex = n-1;
int spacey = n-1;
char buffer[10];
while(win(board) == 0)
{
printf("To move, enter the number you wish to move. Take note that this number must be adjacent to the blank space. Diagonal movement is not allowed.\nYour move: ");
fgets(buffer,10,stdin);
int move;
char temp[20];
if(sscanf(buffer," %d %s",&move,temp)!= 1)
{
printf("Enter a number please.\n");
continue;
}
if(move == board[spacex+1][spacey])
{
board[spacex][spacey] = board[spacex+1][spacey];
board[spacex+1][spacey] = 0;
spacex++;
}
else if(move == board[spacex-1][spacey])
{
board[spacex][spacey] = board[spacex-1][spacey];
board[spacex-1][spacey] = 0;
spacex--;
}
else if(move == board[spacex][spacey+1])
{
board[spacex][spacey] = board[spacex][spacey+1];
board[spacex][spacey+1] = 0;
spacey++;
}
else if(move == board[spacex][spacey-1])
{
board[spacex][spacey] = board[spacex][spacey-1];
board[spacex][spacey-1] = 0;
spacey--;
}
else if(move == 0)
{
printf("Enter a valid digit please.\n");
continue;
}
else
{
printf("Enter a valid number please.\n");
continue;
}
printf("\n");
print(board);
}
printf("You won!\n");
}
///////////////////////////////////////////////////////
void print(int board[n][n])
{
for(int x=0;x<n;x++)
{
for(int y=0;y<n;y++)
{
if(board[x][y] == 0)
{
printf("__ ");
}
else
printf("%2d ",board[x][y]);
}
printf("\n\n");
}
}
///////////////////////////////////////////////////////
int win(int board[n][n])
{
int check = 1;
for(int x=0;x<n;x++)
{
for(int y=0;y<n;y++)
{
if(board[x][y] != check)
{
if(x==n-1 && y == n-1);
else
{
return 0;
}
}
check++;
}
}
return 1;
}
Any other comments about the code would be greatly appreciated too. Thanks in advance!
Code is reading out of bounds.
These two variables point to the last elements of the array board:
int spacex = n-1;
int spacey = n-1;
but are used incorrectly in all if statements. whenever a +1 is used, they will read out of bounds or read an incorrect element:
if(move == board[spacex+1][spacey])
{
board[spacex][spacey] = board[spacex+1][spacey];
board[spacex+1][spacey] = 0;
spacex++;
}
else if(move == board[spacex-1][spacey])
{
...
else if(move == board[spacex][spacey+1])
{
board[spacex][spacey] = board[spacex][spacey+1];
...

Resources