my C code is too awkward [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Assume the character a,b,c,d,e represent the number 1 to 9, and they cannot be equal to
each other.
Question:
How many equals that can meet (ab * cde = adb * ce).
Example:
36 * 495 = 396 * 45.
Here is my code,and the result is right.However,i think my code is too awkward,especially in (if(a!=b&&a!=c&&a!=d&&a!=e&&b!=c&&b!=d&&b!=e&&c!=d&&c!=e&&d!=e&&c*d*e!=0))
I would appreciate it if someone could give me a better solution.
#include<stdio.h>
main(){
int a,b,c,d,e,m,n,i=0;
long f1,f2,f3,f4;
for(m=11;m<=99;m++){
a=m/10;
b=m%10;
if(a!=b&&a*b!=0)
{
for(n=101;n<=999;n++)
{
c=n/100;
d=n%100/10;
e=n%10;
if(a!=b&&a!=c&&a!=d&&a!=e&&b!=c&&b!=d&&b!=e&&c!=d&&c!=e&&d!=e&&c*d*e!=0)
{
f1=a*10+b;
f2=c*100+d*10+e;
f3=a*100+d*10+b;
f4=c*10+e;
if(f1*f2==f3*f4) i++;
printf("\n%d%d*%d%d%d*=%d%d%d*%d%d\n",a,b,c,d,e,a,d,b,c,e);
}
}
}
}
printf("%d\n",i);
return 0;
}

If you can, instead of
int a,b,c,d,e;
Try to use
int numbers[5];
And then to check if your numbers are all different, you can use for loops
doubleOccurence = FALSE; /* where FALSE = 0 */
for (i=0; i < 4; i++) {
for (j=i+1; j < 5; j++) {
doubleOccurence = doubleOccurence || (numbers[i] == numbers[j]);
}
}
It looks a bit clearer to me.

Unfortunately you can't really iterate through a list of variables you are better off with an array of numbers like Julien mentions in his answer.
int nums[5];
replace a with nums[0], b with nums[1], etc....
But then I would go one step further to tidying up your code and call a function that takes in the array to check uniqueness:
if(listIsUnique(nums, 5)) // yes hardcoded the 5, but that can be sorted
{
...
}
And then:
bool listIsUnique(int* nums, int len)
{
for (int i = 0; i < len; i++)
for (int j = i + 1; j < len; j++)
if (nums[i] == nums[j])
return false; // return false as soon as you find a match - slightly faster :)
return true; // if we get here its a unique list :)
}
Note: code is untested, there may be mistakes :o

Related

Nesting For loop in c , at i = 4 ; j will be 2 how does it satisfy the condition? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
{
for (int i = 0; i <= 5; i++)
{
for (int j = 5; j >= i; j--)
{
printf("+");
}
printf("\n");
}
}
At i = 4; j will be 2 how does it satisfy the condition of j>=i?
You seem to be thinking that "j will be 2" because you see two "+" in output in that line.
But that only means that the inner loop is executed twice. Which is because (quoting Barmars comment):
When i == 4, the inner loop will only loop twice, with j == 5 and j == 4.
You analysed the detailed behaviour of your code based on output, which is good. But if something puzzles you then you either need more output on exactly the detail which puzzles you; e.g. by actually outputting the value in question for verifying your assumptions. Or you could use a debugger.
For example. I changed your code in a way which probably makes things very obvious:
#include <stdio.h>
int main(void)
{
for (int i = 0; i <= 5; i++)
{
printf("%d: ", i);
for (int j = 5; j >= i; j--)
{
printf("%d", j);
}
printf("\n");
}
}
It gets you an output (e.g. here https://www.onlinegdb.com/online_c_compiler ) of:
0: 543210
1: 54321
2: 5432
3: 543
4: 54
5: 5
Where the line 4: 54 indicates two inner loop iterations, with values for j of 5 and 4, while i is 4.

Why does this program result in an infinite loop output? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
This code is an exercise from a daily programming mailing list. I am trying to print out a list of given words in reverse order. The words are delimited by spaces. When running the code below, it enters into an infinite loop just printing the (new) first word. I have looked through the conditions and everything looks OK to me. I think it may take a fresh set of eyes to point out a simple mistake, but I can't find anything. Thanks to anyone who can lend a hand.
*Note: I am planning on adding back in the spaces to the output after this is figured out. I am aware the output will just be one long string without spaces so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char *words;
words = "here world hello spam foo bar baz";
int space_indices[10];
int counter = 0;
// Find the spaces and keep track of the index numbers in the space_indices array
for (int i = 0; i < strlen(words); i++) {
if (words[i] == ' ') {
space_indices[counter] = i;
counter++;
}
}
for (int i = counter - 1; i >= 0; i--) {
if ( i = counter - 1) {
// Print the first word
for (int j = space_indices[i] + 1; j < strlen(words); j++) {
printf("%c", words[j]);
}
} else if (i >= 0) {
// Print the other words except for the last
for (int j = space_indices[i] + 1; j < space_indices[i + 1]; j++) {
printf("%c", words[j]);
}
} else {
// Print the last word
for (int j = 0; j < space_indices[0]; j++) {
printf("%c", words[j]);
}
}
}
}
As Havenard explained, the problem was that I was not using a comparison operation, I was using an assignment operator.
This:
if ( i = counter - 1)
should be:
if ( i == counter - 1)

Converting "c99" loop to regular stuff [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Story: I tried to convert a c99 script to regular gcc.
Problem: The output is empty.
Expected output: 3,2,1
length is the number of elements in the array.
Update: the script is designed to sort the elements of the array in a descending order.
The code:
#include <stdio.h>
int main() {
int arr[] = { 1,2,3 };
int temp = 0;
int length = sizeof(arr) / sizeof(arr[0]);
int i = 0;
int j = i + 1;
for (i < length; i++;) {
for (j < length; j++;) {
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
int y = 0;
for (y < length; y++;) {
printf("%d ", arr[y]);
}
return 0;
}
Your syntax for for loops is the issue.
Here is the correct way to write your loops.
int i, j;
for (i = 0; i < length; ++i) // for (initialisation; test condition; operation)
{
for (j = i + 1; j < length; ++j) // note that j is initialized with i + 1 on each iteration of
// the outer loop. That's what makes the bubble sort work.
{
/* test and swap if needed */
}
}
for (i = 0; i < length; ++i) // note that i is reset to zero, so we can scan the array from
// a known position (the top) to bottom.
{
/* printout */
}
Your semicolon is in the wrong place, move it to the far left just inside the parentheses.
Loop syntax is:
for (intializer; break condition; iterator)

How would I traverse a 2D array by finding the local maxima by checking if all the numbers around it are smaller than it? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How would I traverse a 2D array by finding the local maxima by checking if all the numbers around it are smaller than it? I am really confused on how I would do this in code. I need to get the position and I only need local maximums, not absolute maximums.
void reportMaxima(int rows, int cols, int grid[ rows ][ cols ])
{
}
This should work:
#include <stdbool.h>
#include <string.h>
void report_maxima(int rows, int cols, int arr_in[rows][cols],
bool arr_out[rows][cols])
{
int i, j;
int k, l;
memset(arr_out, 0, rows * cols * sizeof(arr_out[0][0]));
// memset(arr_out, 0, sizeof(arr_out)); I think this doesn't work :(
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
for (k = i - 1; k <= (i + 1); k++) {
if (k < 0)
continue;
if (k >= rows)
break;
for (l = j - 1; l <= (j + 1); l++) {
if (l < 0)
continue;
if (l >= cols)
break;
if (arr_in[i][j] < arr_in[k][l])
goto not_maxima;
}
}
arr_out[i][j] = true;
continue;
not_maxima:
}
}
}
First you need a bool array where to store the output info: whether a point is a maxima (true) or not (false).
You need to initialize that array to 0 (false) before storing the points where it is true. The best way to do that is by using memset().
Then, you need obviously to iterate over the input array. (i and j do that)
For each point of the input array, you check all the neighbours. (k and l do that).
You need to be sure that the neighbour you are trying to access is inside the array bounds (the if - continue and if - break do that).
Then, you check if all those neighbours are smaller than the point you are on. The first neighbour you find that is greater than your point tells you that you are not in a local maxima, and you should skip to the next point. If after checking all the neighboours you haven't found any neighbour greater than your point, then you are in a local maxima. (or at least in an inflection point).
That last thing is important: If you want to be sure, you should add a lot of checking, which would slow down the algorithm a lot. It depends on your needs.
EDIT:
Fixed a bug when using incorrect input to sizeof().
Simply run throw all of the cells in the array using 2 for loops
int i,j;
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
if(check(i,j,rows,cols,grid)) {
//do something.
}
else {
//do something else.
}
}
}
Then in code you can check all of the numbers around it. The key for this task is to not be lazy, just check every cell around it. Make sure that you don't try to access memory that is not part of the array.
[i-1][j-1] , [i-1][j] , [i-1][j+1]
[i][j-1] , the cell , [i][j+1]
[i+1][j-1] , [i+1][j] , [i+1][j+1]
So you will need to verify that the +1's are smaller then rows and cols (respectively) and that the -1's are bigger-equal to 0. After that check if the cell in question is smaller then the specific cell next to it, If so return false. At the end of the functions, if no near cell is bigger return true.
bool check(int i, int j, int rows, int cols,int grid[rows][cols]) {
if((i - 1 >= 0) && (j - 1 >= 0) && (grid[i-1][j-1]) > (grid[i][j]))
return false;
if((i - 1 >= 0) && (grid[i-1][j] > grid[i][j]))
return false;
//etc...
return true;
}
There are more esthetic ways to do it, but when you begin to code readability should be the most important thing. If you use a helper function remember to declare it before using it, Good luck!

Prime number into an array in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I try to do a function in order to sort an array and display after that only the prime number. But all the elements of my array are random numbers, and the problem is that the function display only negative prime numbers and not positive like 7 and 3, what can I do in order to solve the problem
int prime_arr(int size, int *arr, int *sort_arr)
{
int i, j, k = 0, flag;
for (i = 0; i < size; i++)
{
flag = 0;
for (j = 2; j < arr[i]/2; j++)
{
if (arr[i] % j == 0){
flag = 1;
break;
}
}
if (flag == 0){
sort_arr[k++] = arr[i];
}
}
return j;
}
I see 3 problems with the code:
1. You should return k, not j. k is the size of sort_arr
2. You should loop until arr[i] / 2, not one less than that (see <= in code below)
3. You do not handle negative numbers. Change your loop to the following:
for (j = 2; j <= abs(arr[i])/2; j++)
Without the code that prints your values, I'm not sure exactly what you're looking for, but hopefully fixing these will fix your problem.

Resources