int main(void){
int range = 0, i = 0;
printf("Enter the number of digits of the number: ");
scanf("%d", &range);
int a[range];
int b[range];
printf("Enter the number: ");
for(i = 0; i < range; i++){
scanf("%1d", &a[i]);
}
replace(a, b, range);
swap(&b[0],&b[range]);
printf("Output: ");
for(i = range; i > 0; i--){
printf("%d", b[i]);
}
return 0;
}
void replace(int *a, int *b, int n){
int *p;
int temp;
for(p = a; p < a + n; p++){
temp = ((*p + 6) % 10) / 10;
p = b;
*p = temp;
}
}
void swap(int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
My problem is with the first for loop, the loop seems to just keep taking in input and doesn't end. I tried putting a print statement before the replace method and it didn't print so I knew the problem was with the for loop. How do I fix this issue?
The replace() function is a disaster
You've now posted the replace function and it is a disaster.
void replace(int *a, int *b, int n)
{
int *p;
int temp;
for (p = a; p < a + n; p++)
{
temp = ((*p + 6) % 10) / 10;
p = b;
*p = temp;
}
}
You attempt to iterate over the array a by making p point to each element in turn. But you then, in the body of the loop, assign b to p, which places it outside the array a, which means all bets are off. It's not clear whether b is less than a + n or not — it simply isn't defined. But given that you get an infinite loop, it probably is, so your code goes reading from and writing to the same couple of locations over and over (b[0], b[1]) and p never progresses nearer to a + n.
A simple fix uses indexes:
void replace(int *a, int *b, int n)
{
for (int i = 0; i < n; i++)
b[i] = ((a[i] + 6) % 10) / 10;
}
If you want to use pointers, then:
void replace(int *a, int *b, int n)
{
for (int *p = a; p < a + n; p++)
*b++ = ((*p + 6) % 10) / 10;
}
Note that the expression evaluates to zero. The modulo 10 operation produces a value in the range 0..9 (or -9..+9), and that divided by 10 is always 0. You'll need to work on that expression.
The call to swap() is broken
You have:
swap(&b[0], &b[range]);
This definitely accesses data out of the bounds of the b array. To be safe, you need to use:
swap(&b[0], &b[range-1]);
Your output loop is broken
You have:
printf("Output: ");
for(i = range; i > 0; i--){
printf("%d", b[i]);
}
You need to avoid accessing b[range] again, and you need to output a newline at the end:
printf("Output: ");
for (i = range; i > 0; i--)
printf("%d", b[i-1]);
putchar('\n');
The input code works
The input code works, as demonstrated by this minimal adaptation of what you've got:
#include <stdio.h>
int main(void)
{
int range = 0, i = 0;
printf("Enter the number of digits in the number: ");
if (scanf("%d", &range) != 1)
{
fprintf(stderr, "Oops 1\n");
return 1;
}
printf("Number of digits: %d\n", range);
int a[range];
printf("Enter the number: ");
for (i = 0; i < range; i++)
{
if (scanf("%1d", &a[i]) != 1)
{
fprintf(stderr, "Oops 2\n");
return 2;
}
printf("Digit %d: %d\n", i, a[i]);
}
printf("Reversed input: ");
for (i = range; i > 0; i--)
printf("%2d", a[i-1]);
putchar('\n');
return 0;
}
The 'reversed input' loop is an adaptation of the 'output' loop in the question — bug-fixed to avoid accessing the array out of bounds, and using a instead of b. The error messages are very uninformative (not suitable for production work), but they're adequate to identify which statement caused an error while you're debugging.
Example run:
$ ./example-input
Enter the number of digits in the number: 12
Number of digits: 12
Enter the number: 1234 5678 9101112
Digit 0: 1
Digit 1: 2
Digit 2: 3
Digit 3: 4
Digit 4: 5
Digit 5: 6
Digit 6: 7
Digit 7: 8
Digit 8: 9
Digit 9: 1
Digit 10: 0
Digit 11: 1
Reversed input: 1 0 1 9 8 7 6 5 4 3 2 1
$
Now, adapt this into your program and see where the problem really is.
Working code
#include <stdio.h>
static void swap(int *a, int *b);
static void replace(int *a, int *b, int n);
int main(void)
{
int range = 0, i = 0;
printf("Enter the number of digits in the number: ");
if (scanf("%d", &range) != 1)
{
fprintf(stderr, "Oops!\n");
return 1;
}
printf("Number of digits: %d\n", range);
int a[range];
int b[range];
printf("Enter the number: ");
for (i = 0; i < range; i++)
{
if (scanf("%1d", &a[i]) != 1)
{
fprintf(stderr, "Oops 2\n");
return 2;
}
printf("Digit %d: %d\n", i, a[i]);
}
printf("Reversed input: ");
for (i = range; i > 0; i--)
printf("%2d", a[i-1]);
putchar('\n');
replace(a, b, range);
swap(&b[0], &b[range-1]);
printf("Output: ");
for (i = range; i > 0; i--)
printf("%2d", b[i-1]);
putchar('\n');
return 0;
}
static void swap(int *p, int *q)
{
int t = *p;
*p = *q;
*q = t;
}
static void replace(int *a, int *b, int n)
{
for (int *p = a; p < a + n; p++)
*b++ = ((*p + 6) % 10);
}
Example output
$ ./example-input
Enter the number of digits in the number: 9
Number of digits: 9
Enter the number: 123 456 789
Digit 0: 1
Digit 1: 2
Digit 2: 3
Digit 3: 4
Digit 4: 5
Digit 5: 6
Digit 6: 7
Digit 7: 8
Digit 8: 9
Reversed input: 9 8 7 6 5 4 3 2 1
Output: 7 4 3 2 1 0 9 8 5
$
Related
I have built an algorithm that follows the following:
input n
print n
if n = 1 then STOP
if n is odd then n ←− 3n + 1
else n ←− n/2 GOTO 2
Whereby if n = 22 this should print out:
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
Given an input n, it is possible to determine the number of numbers printed before and including the 1 is printed. For a given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16.
Therefore I have to determine the cycle-length between and including two integers i,j respectively.
#include <stdlib.h>
#include <stdio.h>
#define MAXSIZE 100
int test(int i, int j){
int* z[MAXSIZE];
int n = j-i;
int *p;
p = &j;
int o = 0;
while(&free){
int k = 0;
printf("\n%d -> %d ->> %d & %d", i, j, n, *p);
while(&free){
if (i == 1){
break;
} else if ((i % 2) != 0)
{
i = 3*i+1;
} else{
i = i/2;
}
k++;
}
(*z)[o] = k;
o++;
if (n == 1){
break;
}
n--;
i = *p-n;
}
size_t size = sizeof(z)/sizeof(z[0]);
int m = 0;
for (int i = 0; i < size; i++){
//printf("\n RESULTS: -- %d", (*z)[i]);
if (m < (*z)[i]){
m = (*z)[i];
} else {
continue;
}
}
return m;
}
int main(){
int i=900;
int j=1000;
int result;
result = test(i,j);
printf("\n RESULT: %d", result);
return 0;
}
However, this is producing a segmentation fault which it caused my pointer deficiency, however, I cannot locate it.
UPDATE:
Based on the comments, I believe the programme now runs as intended
"producing a segmentation fault " that is because (*z) is UB.
z is an uninitialized array of pointers.
I need to write a program that allows user to enter an array of integers, finds the digit that appears most often in all entered numbers, and removes it from the elements of the array. If several digits appear the same number of times, the smallest of them should be deleted. If all digits of the element of the array are deleted, that element should become zero. In the end, such a modified array is printed.
Example of input and output:
Enter number of elements of the array: 5
Enter the array: 3833 8818 23 33 1288
After deleting, the array is: 8 8818 2 0 1288
Explanation: The numbers 3 and 8 appear the same number of times (6 times each), but 3 is less, so it was removed it from all members of the array. Element 33 consists exclusively of the digits 3, so that it becomes 0.
#include <stdio.h>
int main() {
int i,n,arr[100]; n;
printf("Enter number of elements of the array: ");
scanf("%d", &n);
printf("Enter the array: ");
for(i=0;i<n;i++) {
scanf("%d", &arr[i]);
}
return 0;
}
EDIT: I'm beginner to programming, and this task should be done using only knowledge learned so far in my course which is conditionals, loops, and arrays. This shouldn't be done with strings.
Divide the problem into separate tasks.
Write the code
In the code below I do not treat 0 as having digit 0. It is because it is not possible to remove 0 from 0. You can easily change this behaviour by changing while(){} loop to do{}while()
int removeDigit(int val, int digit)
{
int result = 0;
unsigned mul = 1;
int sign = val < 0 ? -1 : 1;
digit %= 10;
while(val)
{
int dg = abs(val % 10);
if(dg != digit)
{
result += dg * mul;
mul *= 10;
}
val /= 10;
}
return sign * result;
}
void countDigits(int val, size_t *freq)
{
while(val)
{
freq[abs(val % 10)]++;
val /= 10;
}
}
int findMostFrequent(const size_t *freq)
{
size_t max = 0;
for(size_t i = 1; i < 10; i++)
{
if(freq[i] > freq[max]) max = i;
}
return (int)max;
}
int main(void)
{
int table[20];
size_t freq[10] = {0,};
int mostfreq = 0;
srand(time(NULL));
for(size_t i = 0; i < 20; i++)
{
table[i] = rand();
printf("Table[%zu] = %d\n", i, table[i]);
countDigits(table[i], freq);
}
mostfreq = findMostFrequent(freq);
printf("Most frequent digit: %d\n", mostfreq);
for(size_t i = 0; i < 20; i++)
{
table[i] = removeDigit(table[i], mostfreq);
printf("Table[%zu] = %d\n", i, table[i]);
}
}
https://godbolt.org/z/PPj9s341b
Currently, I have a program the implements insertion sort and then uses binary search to search it (an array of ints). I currently have a 1 off error it seems.
My insertion sort should sort in descending order. Right now, it seems as if the value stored in the last position is missing.
#include <stdio.h>
void insertionSort(int nums[], int size)
{
int i, key, j;
for (i = 1; i < size; i++)
{
key = nums[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && nums[j] > key)
{
nums[j + 1] = nums[j];
j = j - 1;
}
nums[j + 1] = key;
}
}
int binarySearch(int nums[], int size, int searchVal)
{
int l = 0, r = size - 1;
while (l <= r)
{
int m = l + (r - l) / 2;
// Check if x is present at mid
if (nums[m] == searchVal)
return m;
// If x greater, ignore left half
if (nums[m] < searchVal)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was
// not present
return -1;
}
int main()
{
int n;
printf("Enter the number of elements (between 1 and 50) in the array: \n");
scanf("%d", &n);
int i, nums[n];
printf("Enter %d positive integers: \n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &nums[i]);
}
int x = 0;
insertionSort(nums, n);
printf("Enter a positive integer or -1 to quit: \n");
scanf("%d", &x);
do
{
int ind = binarySearch(nums, n, x);
if (ind > 0)
{
printf("Found\n");
}
else
{
printf("Not Found\n");
}
printf("Enter a positive integer or -1 to quit: \n");
scanf("%d", &x);
} while (x != -1);
return 0;
}
Results:
Enter the number of elements (between 1 and 50) in the array:
9
Enter 9 positive integers:
7
4
10
49
6
12
32
17
Enter a positive integer or -1 to quit:
4
Not Found
Enter an positive integer -1 or to quit
12
Found
Enter a positive integer or -1 to quit:
5
Not Found
Enter a positive integer or -1 to quit:
49
Found
Enter a positive integer or -1 to quit:
-1
As you can see everything works but the first test where I test for the number 4. Does anyone know why I'm off by 1?
#include <stdio.h>
void insertionSort (int nums[], int size)
{
int i, key, j;
for (i = 1; i < size; i++) {
key = nums[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && nums[j] > key) {
nums[j + 1] = nums[j];
j = j - 1;
}
nums[j + 1] = key;
}
}
int binarySearch (int nums[], int size, int searchVal)
{
int l = 0, r = size - 1;
while (l <= r) {
int m = l + (r - l) / 2;
// Check if x is present at mid
if (nums[m] == searchVal)
return m;
// If x greater, ignore left half
if (nums[m] < searchVal)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was
// not present
return -1;
}
int main ()
{
int n;
printf
("Enter the number of elements (between 1 and 50) in the array: \n");
scanf ("%d", &n);
int i, nums[n];
printf ("Enter %d positive integers: \n", n);
for (i = 0; i < n; i++) {
scanf ("%d", &nums[i]);
}
int x = 0;
insertionSort (nums, n);
printf ("Enter a positive integer or -1 to quit: \n");
scanf ("%d", &x);
do {
int ind = binarySearch (nums, n, x);
if (ind >= 0) {
printf ("Found\n");
} else {
printf ("Not Found\n");
}
printf ("Enter a positive integer or -1 to quit: \n");
scanf ("%d", &x);
} while (x != -1);
return 0;
}
Try this one
just one error that is solve- if(ind>=0)
While you have discovered that checking the (ind > 0) causes failure to find the elements at index 0 and (ind >= 0) provides a solution, let's look at a short test case that validates the binarySearch() finds all elements of your sorted array without the user having to continually enter or redirect information to your program.
Any time you are testing algorithms, provides a simple validation framework that tests all elements, numbers, etc. without a user input requirement. Take your '9' numbers for example. Simply including an initialized array and sorting and then looping over all values will validate whether the binarySearch() is performing as intended. (it will save you no end of grief in the process as well). A short code exercising your search over the complete array can be as simple as:
int main (void) {
int nums[] = { 7, 4, 10, 49, 6, 12, 32, 17, 21 },
n = sizeof nums / sizeof *nums;
insertionSort (nums, n);
for (int i = 0; i < n; i++)
printf (" %2d (%s)\n", nums[i],
binarySearch (nums, n, nums[i]) >= 0 ? "found" : "not found");
}
Example Use/Output
$ ./bin/bsearchtest
4 (found)
6 (found)
7 (found)
10 (found)
12 (found)
17 (found)
21 (found)
32 (found)
49 (found)
Each element is now listed as "found" or "not found" and the code exits on its own.
I want do a program of factorization like this: 72 = 3 * 2 ^ 3 ^ 2
in C language, how can i do the program ?
I tried to do this but I can not do it :
#include <stdio.h>
int main(){
int n;
int j;
printf("Insert a positive integer number greater than 1\n")
scanf("%d", &n);
j = 2;
do
{
if( n % j == 0)
{
printf("%d\n", j);
n = n / j;
}
else{
j++;
}
}
while ( n > 1);
}
Assuming that given 72, you want to output 2^3 X 3^2 this code should do it:
/* Decides when to print multiplication sign */
const char *get_mult_string()
{
static int first_divisor=1;
if (first_divisor==1) {
first_divisor=0;
return "";
} else {
return " X ";
}
}
void factorize() {
int n;
int j;
printf("Insert a positive integer number greater than 1: ");
scanf("%d", &n);
j = 2;
int power_count=0;
do {
if (n % j == 0) {
power_count++;
n = n / j;
}
else {
if (power_count>0) {
printf("%s(%d^%d)", get_mult_string(), j, power_count);
power_count=0;
}
j++;
}
}
while (n > 1);
if (power_count>0) {
printf("%s(%d^%d)\n", get_mult_string(), j, power_count);
}
}
Try creating an array, where each slot represents a prime number, and initialize them all to 0. For example, array[0] means 2, array[1] 3, array[2] 5, array[3] 7, array[4] 11.
Rather than printing out the prime number when you reach it, as you do in your code, increment that slot in the array. In the end, you can call something like printf("2^%d * 3^%d * 5^%d * 7^%d * 11^%d",array[0],array[1],array[2],array[3],array[4]).
Note: switch statements would probably be your friend here.
I wrote a simple program in c that accepts two numbers and then splits the first number considering the digits of the second number like this:
Input:
362903157 2313
Output:
36
290
3
157
Everything works just fine, except when there are zeroes in the first number, my program skips them. For instance the upper example gives me this output:
36 293 1 570
And that is mycode:
#include <stdio.h>
int nDigits(unsigned i) {
int n = 1;
while (i > 9) {
n++;
i /= 10;
}
return n;
}
// find the highest multiple of 10
int multipleOfTen(int num){
int multiple = 1;
while(multiple <= num){
multiple *= 10;
if(multiple > num){
multiple /= 10;
break;
}
}
return multiple;
}
int main(){
int n, m, digit;
scanf("%d %d", &n, &m);
int lengthOfM = nDigits(m);
for (int i = 0; i < lengthOfM; i++){
digit = m / multipleOfTen(m); //2
for(int j = 1; j <= digit; j++){
printf("%d", n/multipleOfTen(n));
n = n% multipleOfTen(n);
}
printf("\n");
m = m % multipleOfTen(m);
}
return 0;
}
What should I change in my program so that the zeroes won't be ignored?
Instead of calling multipleOfTen() in each loop, call it once and save the result for both n and m. Then in each loop divide those results by 10
#include <stdio.h>
int nDigits(unsigned i) {
int n = 1;
while (i > 9) {
n++;
i /= 10;
}
return n;
}
// find the highest multiple of 10
int multipleOfTen(int num){
int multiple = 1;
while(multiple <= num){
multiple *= 10;
if(multiple > num){
multiple /= 10;
break;
}
}
return multiple;
}
int main(){
int n, m, digit;
int i, j;
int n10, m10;
scanf("%d %d", &n, &m);
int lengthOfM = nDigits(m);
n10 = multipleOfTen(n); //get the multiple of ten once
m10 = multipleOfTen(m);
for ( i = 0; i < lengthOfM; i++){
digit = m / m10;
m10 /= 10;
for( j = 0; j < digit; j++){
printf("%d", n/n10);
n = n% n10;
n10 /= 10;// divide by 10
}
printf("\n");
m = m % multipleOfTen(m);
}
return 0;
}
I suppose an approach like this is inadmissible?
#include <stdio.h>
#include <string.h>
int main ( void ) {
char n[64];
char m[64];
char * p = n;
int i = 0;
int c;
scanf("%63[0-9] %63[0-9]", n, m);
while ((c = m[i++]) != '\0') {
int j = c - '0';
while (j-- > 0) if (*p) putchar(*p++);
putchar(' ');
}
putchar('\n');
return 0;
}
when n=903157 and after n = n% multipleOfTen(n); n becomes 3157 not 03157 so when u dividing again in line printf("%d", n/multipleOfTen(n)); it prints 3 not 0 what you want!!
Fix your code to produce right output.