Find common element in two from three arrays - c

I need to find elements of array which are hold in two of three given arrays.
It seems easy, but it's quite dificult and i have been strugling with this for few days.
I hope you can help me..
For input:
1 2 3 5
1 2 4 6 7
1 3 4 8 9 10
Output should be 3 (because 3,4,2 are common for two arrays)
for input
1 2 3 4
2 3 4
3 4 1
Output should be: 2 (because 1 is common for two arrays)
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main()
{
int duzina_prvog_niza = 0, duzina_drugog_niza = 0, duzina_treceg_niza = 0; //deklaracija duzina nizova
printf("Unesite broj clanova prvog niza:\n"); // unosimo duzine nizova i elemente nizova
do
{
scanf("%d", &duzina_prvog_niza);
} while (0 > duzina_prvog_niza || duzina_prvog_niza > 50); // mozda ne bi trebalo stavljati gornju granicu za duzinu niza
int niz1[duzina_prvog_niza]; //zavisi kako vam sistem provjere radi, mislim da nece praviti problem
// alociramo niz odgovarajuce duzine, iterativno popunimo niz uz odgovarajucu provjeru
for (int i = 0; duzina_prvog_niza > i; i++)
{
do
{
scanf("%d", &niz1[i]);
} while (0 > niz1[i] || niz1[i] > 10); // citaj elemente sve dok ne ucitas cifre iz odgovarajuceg opsega
}
for (int i = 0; duzina_prvog_niza > i; i++)
printf(" %d ", niz1[i]);
printf("\n");
// ** drugi niz ** -- bilo bi zgodno ovo sve strpati u jednu fju, meni je ovako bilo lakse.. c/p
printf("Unesite broj clanova drugog niza:\n");
do
{
scanf("%d", &duzina_drugog_niza);
} while (0 > duzina_drugog_niza || duzina_drugog_niza > 50);
int niz2[duzina_drugog_niza];
// alociramo niz odgovarajuce duzine, iterativno popunimo niz uz odgovarajucu provjeru
for (int i = 0; duzina_drugog_niza > i; i++)
{
do
{
scanf("%d", &niz2[i]);
} while (0 > niz2[i] || niz2[i] > 10); // citaj elemente sve dok ne ucitas cifre iz odgovarajuceg opsega
}
for (int i = 0; duzina_drugog_niza > i; i++)
printf(" %d ", niz2[i]);
printf("\n");
// ** treci niz **
printf("Unesite broj clanova treceg niza:\n");
do
{
scanf("%d", &duzina_treceg_niza);
} while (0 > duzina_treceg_niza || duzina_treceg_niza > 50);
int niz3[duzina_treceg_niza];
// alociramo niz odgovarajuce duzine, iterativno popunimo niz uz odgovarajucu provjeru
for (int i = 0; duzina_treceg_niza > i; i++)
{
do
{
scanf("%d", &niz3[i]);
} while (0 > niz3[i] || niz3[i] > 10); // citaj elemente sve dok ne ucitas cifre iz odgovarajuceg opsega
}
for (int i = 0; duzina_treceg_niza > i; i++)
printf(" %d ", niz3[i]);
printf("\n");
//pocetna vrijednost brojaca mora biti nula!
int brojac = 0;
int pomocni_brojac = 0;
// (S_1 intersect S_2) union (S_2 intersect S_3) union (S_3 intersect S_1) -- matematicko rjesenje problema
int x;
int pomocni_niz[duzina_prvog_niza + duzina_drugog_niza + duzina_treceg_niza];
for (int i = 0; duzina_prvog_niza + duzina_drugog_niza + duzina_treceg_niza > i; i++)
pomocni_niz[i] = 0;
int max;
if(duzina_prvog_niza>=duzina_drugog_niza && duzina_prvog_niza>=duzina_treceg_niza) max=duzina_prvog_niza;
if(duzina_drugog_niza>=duzina_prvog_niza && duzina_drugog_niza>=duzina_treceg_niza) max=duzina_drugog_niza;
if(duzina_treceg_niza>=duzina_drugog_niza && duzina_treceg_niza>=duzina_prvog_niza) max=duzina_treceg_niza;
//prolazimo kroz sve elemente u sva tri niza i poredimo sve elemente sa svim elementima
for (int i = 0; duzina_prvog_niza > i; i++)
{
for (int j = 0; duzina_drugog_niza > j; j++)
{
for (int k = 0; duzina_treceg_niza > k; k++)
{ // ako je element iz prvog niza jednak elementu iz drugog niza, ili je element
if (((niz1[i] == niz2[j]) && (niz2[j] == niz3[k]) && (niz1[i] == niz3[k])))
1;
else if ((niz1[i] != niz2[j]) && (niz2[j] == niz3[k]) && (niz1[i] != niz3[k]))
pomocni_niz[pomocni_brojac++] = niz2[j];
else if ((niz1[i] == niz2[j]) && (niz2[j] != niz3[k]) && (niz1[i] != niz3[k]))
pomocni_niz[pomocni_brojac++] = niz1[i];
else if ((niz1[i] != niz2[j]) && (niz2[j] != niz3[k]) && (niz1[i] == niz3[k]))
pomocni_niz[pomocni_brojac++] = niz2[j];
}
}
}
int y = 0;
for (int g = 0; pomocni_brojac > g; g++)
{
for (int l = 0; pomocni_brojac > l; l++)
{
if (pomocni_niz[g] == pomocni_niz[l])
y++;
}
if (y == 0)
brojac++;
y = 0;
}
for (int i = 0; brojac > i; i++)
printf("%d ", pomocni_niz[i]);
printf("U dva od tri niza se nalazi %d clanova.", brojac);
return 0;
}
Thanks!

There exists a pretty fast solution to your problem. You will need three more arrays each having a size of 100. Each array will record the frequency of any particular input array. The size of each frequency array is 100 since any input array will only consist of numbers in the range 0-99.
For example:
Input arrays:
A: 1 2 3 5
B: 1 2 4 6 7
C: 1 3 4 8 9 10
Frequency arrays:
0 1 2 3 4 5 6 7 8 9 10
A: 0 1 1 1 0 1 0 0 0 0 0
B: 0 1 1 0 1 0 1 1 0 0 0
C: 0 1 0 1 1 0 0 0 1 1 1
In the frequency arrays section:
The top row denotes number which may be present in any input array and the rows below contains their frequency in each input array..
Algorithm
1 : let frequencyA[100]
2 : let frequencyB[100]
3 : let frequencyC[100]
4 :
5 : for i = 0 to A.length-1
6 : if (frequencyA[A[i]] == 0) frequencyA[A[i]]++
7 : for i = 0 to B.length-1
8 : if (frequencyB[B[i]] == 0) frequencyB[B[i]]++
9 : for i = 0 to C.length-1
10: if (frequencyC[C[i]] == 0) frequencyC[C[i]]++
11:
12: for i = 0 to 99
13: if (frequencyA[i]+frequencyB[i]+frequencyC[i] == 2) Print i
The algorithm is pretty straight forward. The only that lines that deserve some explanation are mentioned below.
Line 5-10:
For each input array, we loop though each of its element and record their frequency. We record the frequency of any particular element only once, that is, if any element repeats in a single array, we will record its frequency only once. This is made sure by the if condition which checks if we have recorded the frequency of any element before or not.
Line 12-13:
We start a loop from 0 to 99 since they are the possible values of the array. In the loop, we check if sum of the frequency in the all the three frequency arrays of any element is 2 or not. If its 2, then that element is present in present exactly twice else not.
Time Complexity
The algorithm has a time complexity of O(A.length + B.length + C.length). It is a linear time complexity which is quite fast.
I can not provide you with any code as I do not code in C a lot. I hope I have helped you. If you face any trouble in understanding my answer, please do comment. I will be happy to update my answer.

For starters always use English words for identifiers. In this case your code will be readable for a larger auditorium. Otherwise it is difficult to read it.
This statement in your program
if (((niz1[i] == niz2[j]) && (niz2[j] == niz3[k]) && (niz1[i] == niz3[k])))
1;
does not make a sense.
If you need to output common elements that are present exactly in two of three arrays then there is no great sense to create a forth array with the size equal to the sum of sizes of the three arrays.
If the arrays can be unsorted and you may not sort the arrays then a straightforward approach can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
void f( const int a1[], size_t n1, const int a2[], size_t n2, const int a3[], size_t n3 )
{
size_t total = 0;
for ( size_t i1 = 0; i1 < n1; i1++ )
{
size_t count = 1;
size_t i2 = 0;
while ( i2 < n2 && a2[i2] != a1[i1] ) i2++;
count += i2 != n2;
size_t i3 = 0;
while ( i3 < n3 && a3[i3] != a1[i1] ) i3++;
count += i3 != n3;
if ( count == 2 )
{
++total;
printf( "%d ", a1[i1] );
}
}
for ( size_t i2 = 0; i2 < n2; i2++ )
{
size_t i1 = 0;
while ( i1 < n1 && a1[i1] != a2[i2] ) i1++;
if ( i1 == n1 )
{
size_t i3 = 0;
while ( i3 < n3 && a3[i3] != a2[i2] ) i3++;
if ( i3 != n3 )
{
++total;
printf( "%d ", a2[i2] );
}
}
}
if ( total != 0 ) putchar( '\n' );
printf( "%zu\n", total );
}
int main(void)
{
int a[] = { 1, 2, 3, 5 };
int b[] = { 1, 2, 4, 6, 7 };
int c[] = { 1, 3, 4, 8, 9, 10 };
size_t n1 = sizeof( a ) / sizeof( *a );
size_t n2 = sizeof( b ) / sizeof( *b );
size_t n3 = sizeof( c ) / sizeof( *c );
f( a, n1, b, n2, c, n3 );
return 0;
}
The program output is
2 3 4
3

Related

Printing Prime numbers in a range

My code is not running the loop. I've tried changing it from for to while loop, tried changing the condition for prime number but still the same response. I've attached my output in this program output image.
#include<stdio.h>
int main(void) {
int a, b, flag = 0;
int i, j;
printf("Enter lower limit of range\n");
scanf("%d", &a);
printf("Enter upper limit of range\n");
scanf("%d", &b);
printf("The prime numbers between %d and %d are\n", a, b);
i = a;
j = 2;
while (i <= b) {
while ( j < i/2 )
{
if (i % j == 0)
{
flag = 1;
}
j++;
}
if (flag == 0)
{
printf("%d\n", i);
}
i++;
}
return 0;
}
You need at least to reset the variable flag to 0 and j to 2 in each iteration of the outer loop. Also the condition j < i /2 should be changed to j <= i / 2 (for example when i is equal to 4).
while (i <= b) {
flag = 0;
j = 2;
while ( flag == 0 && j <= i/2 )
{
if (i % j == 0)
{
flag = 1;
}
j++;
}
if (flag == 0)
{
printf("%d\n", i);
}
i++;
}
Pay attention to that the program can incorrectly consider 2 as a non-prime number and 1 as a prime number.
I would write the loops the following way
for ( ; i <= b; i++ )
{
int prime = i % 2 == 0 ? i == 2 : ( i == 3 ) || ( i != 1 && i % 3 != 0 );
for ( int j = 5; prime && j <= i / j; j += 6 )
{
prime = i % j != 0 && i % ( j + 2 ) != 0;
}
if ( prime )
{
printf("%d\n", i);
}
}
Or a more simple variant
for ( ; i <= b; i++ )
{
int prime = i % 2 == 0 ? i == 2 : i != 1;
for ( int j = 3; prime && j <= i / j; j += 2 )
{
prime = i % j != 0;
}
if ( prime )
{
printf("%d\n", i);
}
}
You should declare the variables a and b as having the type unsigned int instead of int to avoid using negative numbers.
Here is a demonstration program.
#include <stdio.h>
int main( void )
{
unsigned int a = 0, b = 0;
printf( "Enter lower limit of range " );
scanf( "%u", &a );
printf( "Enter upper limit of range " );
scanf( "%u", &b );
printf( "The prime numbers between %u and %u are\n", a, b );
for ( unsigned int i = a; i <= b; i++ )
{
int prime = i % 2 == 0 ? i == 2 : i != 1;
for ( unsigned int j = 3; prime && j <= i / j; j += 2 )
{
prime = i % j != 0;
}
if (prime)
{
printf( "%u ", i );
}
}
putchar( '\n' );
}
The program output might look like
Enter lower limit of range 0
Enter upper limit of range 100
The prime numbers between 0 and 100 are
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

reverse array in range in C

I have to solve it in C language. I have arrays with n integers. L and U are lower and upper bound. I have to reverse numbers in array which is in [L,U]. I tried it by this way, but in some cases the answer is wrong. What mist be changed in the code? Or is there any other logic to complete the task?
#include <stdio.h>
int main() {
int x, arr[100], n, l, u, a, temp, temp1;
scanf("%d%d%d", &n, &l, &u);
for (int i = 0; i < n; i++) {
scanf("%d", &x); // read elements of an array
arr[i] = x;
}
a = n / 2;
for (int i = 0; i < a; i++) {
for (int j = a; j < n; j++) {
if (arr[i] >= l && arr[i] <= u) {
if (arr[j] >=l && arr[j] < u) {
temp = arr[j];
temp1 = arr[i];
arr[i] = temp;
arr[j] = temp1;
}
}
}
}
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}
sample input:
10(number of integers) -7(lower bound) 5(upper bound)
-10 -9 5 -2 -3 7 10 6 -8 -5
sample output:
-10 -9 -5 -3 -2 7 10 6 -8 5
my output:
-10 -9 -5 -2 -3 7 10 6 -8 5
There is an O(N) solution that does not require nesting of loops.
First, with the code as you as you have it, declare an additional array and some other helper variables that keeps track of what indices need to be swapped.
int left, right;
int swaplist[100] = {0};
int swapcount = 0;
Your can keep your initial intake loop exactly as you have it, but amended to append the index of the newly scanned value to the swaplist array if the value is between the lower and upper bounds.
for (int i = 0; i < n; i++) {
scanf("%d", &x); // read elements of an array
arr[i] = x;
if ((x >= l) && (x <= u)) {
swaplist[swapcount++] = i;
}
}
Then a single loop to iterate over "swaplist" and do the swaps against the original array.
left = 0;
right = swapcount-1;
while (left < right) {
int leftindex = table[left];
int rightindex = table[right];
int tmp = arr[leftindex];
arr[leftindex] = arr[rightindex];
arr[rightindex] = tmp;
left++; right--;
}
You made a valiant attempt. Your nested for() loops are appropriate for some kinds of sorting algorithms, but not for what seems to be the purpose of this task.
From the sample input and desired output, you really want to establish a 'bracket' at either end of the array, then shift both toward the centre, swapping elements whose value happens to satisfy low <= n <= high value. (In this case, -7 <= n <= 5).
Here's a solution:
#include <stdio.h>
int swap( int arr[], size_t l, size_t r ) { // conventional swap algorithm
int t = arr[l];
arr[l] = arr[r];
arr[r] = t;
return 1;
}
int main() {
int arr[] = { -10, -9, 5, -2, -3, 7, 10, 6, -8, -5, }; // your data
size_t i, sz = sizeof arr/sizeof arr[0];
for( i = 0; i < sz; i++ ) // showing original version
printf( "%d ", arr[i] );
putchar( '\n' );
#define inRange( x ) ( -7 <= arr[x] && arr[x] <= 5 ) // a good time for a macro
size_t L = 0, R = sz - 1; // 'L'eft and 'R'ight "brackets"
do {
while( L < R && !inRange( L ) ) L++; // scan from left to find a target
while( L < R && !inRange( R ) ) R--; // scan from right to find a target
} while( L < R && swap( arr, L, R ) && (L+=1) > 0 && (R-=1) > 0 );
for( i = 0; i < sz; i++ ) // showing results
printf( "%d ", arr[i] );
putchar( '\n' );
return 0;
}
-10 -9 5 -2 -3 7 10 6 -8 -5
-10 -9 -5 -3 -2 7 10 6 -8 5
If I have understood the assignment correctly you need to reverse elements of an array that satisfy some condition.
If so then these nested for loops
for (int i = 0; i < a; i++) {
for (int j = a; j < n; j++) {
if (arr[i] >= l && arr[i] <= u) {
if (arr[j] >=l && arr[j] < u) {
temp = arr[j];
temp1 = arr[i];
arr[i] = temp;
arr[j] = temp1;
}
}
}
}
do not make sense.
It is enough to use only one for loop as shown in the demonstration program below.
#include <stdio.h>
int main( void )
{
int a[] = { 1, 10, 2, 3, 20, 4, 30, 5, 40, 6, 7, 50, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
int l = 10, u = 50;
for (size_t i = 0, j = N; i < j; i++ )
{
while (i < j && !( l <= a[i] && a[i] <= u )) ++i;
if (i < j)
{
while (i < --j && !( l <= a[j] && a[j] <= u ));
if (i < j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
The program output is
1 10 2 3 20 4 30 5 40 6 7 50 9
1 50 2 3 40 4 30 5 20 6 7 10 9
You could write a separate function as for example
#include <stdio.h>
void reverse_in_range( int a[], size_t n, int low, int upper )
{
for (size_t i = 0, j = n; i < j; )
{
while (i < j && !( low <= a[i] && a[i] <= upper )) ++i;
if (i < j)
{
while (i < --j && !( low <= a[j] && a[j] <= upper ));
if (i < j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
++i;
}
}
}
}
int main( void )
{
int a[] = { 1, 10, 2, 3, 20, 4, 30, 5, 40, 6, 7, 50, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
reverse_in_range( a, N, 10,50 );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
Thanks for everyone help. I read all of them, but I found another way to solve this problem. I will write it just in case. (some variable names are random, so in case of questions, comment).
#include <stdio.h>
int main() {
int x, main[100], n, l, u, a = 0, arr[100], temp, m = 0,f=0,c,d;
scanf("%d%d%d", &n, &l, &u);
for (int i = 0; i < n; i++) {
scanf("%d", &x); // read elements of an array
main[i] = x;
if (x >= l && x <= u) {
a++; //check if element is in range [l,u] and increasing a. later "a" will be used a length of the array "arr". this array cootains elements, which in in [u,l].
}
}
//add [u,l] elements in new array "arr"
for (int i = 0; i < n; i++) {
if (main[i] >= l && main[i] <= u) {
arr[m] = main[i];
m++; //index counter of "arr",
}
}
d=0;
for(int i=0;i<n;i++){
if(main[i]==arr[d]){
c=arr[a-d-1];
main[i]=c;
d++;
}
}
for(int i=0;i<n;i++){
printf("%d ",main[i]);
}
}
My best guess is that scanf is very annoying, on top of that, your format is ambiguous.
How will %d%d%d read 1234? Will it give you 12 3 and 4? 1 23 and 4? ...
try to do
scanf("%d %d %d" ...); // or
scanf("%d, %d, %d" ...);
something like that. Note that scanf is not recommended to be used, getc is a neat alternative, though also annoying when you want to read numbers with more than one digit, but you could create a function read_number, which, based on getc, will read a number as a string and return the int value with stoi.

Shortest path with Bellman & Ford algorithm

I want to implement Shortest path with Bellman & Ford algorithm. my idea is I use adjacent matrix
to save the information of digraph. If I want to find the shorest path of vertex i ,then I observe in-
degree of vertex i by the ith column of adjacent matrix ,and I save the shortest value of ith column
to a variable "min".if I want to find the shorest path from source vertex v to vertex i.
I only compare distance[i] with (distance[j]+ min ), because "min" is equal to adjmatrix[j][i].
In addition, I make the traverse(source, k) function to comfirm which vertex we can reach it in k
steps and use the data structure stack to save information of vertex i. I assume to that i'll get all the
shortest path from source vertex v to every vertex o graph except v itself. But the consequence after
compiling isn't that I expected. I finally got distance[i], 0 <= i < MAX_VERTEX, 1000,-1, 5, 5, 0 ,1000,
1000, respectively. What is my problem? Thanks for answer.
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX 7
#define FALSE 0
#define TRUE 1
#define MAX_DISTANCE_LIMIT 1000
#define MAX_STACK_LENGTH 100
#define MIN(x, y) ((x) < (y) ? x : y)
int stack[MAX_STACK_LENGTH];
int top = -1; //pointer to top of stack.
int adjmatrix[MAX_VERTEX][MAX_VERTEX];
short found[MAX_VERTEX]; //traverse(v ,k) : reach the vertex i By taking the k steps at most
int distance[MAX_VERTEX]; //save the shortest path that source v to every vertex i
int init_matrix(void);
void BellmanFord(int v); //v is source
void traverse(int v,int times);
void push(int vertex);
int pop(void);
int main(void){
int i,j;
init_matrix(); //initial matrix and found[] array
for(i = 0; i < MAX_VERTEX; i++){
for(j = 0; j < MAX_VERTEX; j++)
printf("%2d ", adjmatrix[i][j]);
printf("\n");
}
printf("--------------------------------------------------\n");
BellmanFord(0);
for(i = 0; i < MAX_VERTEX; i++)
printf("%4d ", i);
printf("\n");
for(i = 0; i < MAX_VERTEX; i++)
printf("%4d ", distance[i]);
return 0;
}
int init_matrix(void){
int num_edge = 0, i, j, w;
for(i = 0; i < MAX_VERTEX; i++){
found[i] = FALSE;
for(j = 0; j < MAX_VERTEX; j++)
adjmatrix[i][j] = MAX_DISTANCE_LIMIT; //set a large value to the entry of the vertice which aren't adjacent
}
while(1){
printf("enter the vertices and weight of edge connected between them(w,tail,head): ");
scanf("%d%d%d", &w, &i, &j);
if((i >= MAX_VERTEX) || (j >= MAX_VERTEX)){
fprintf(stderr, "index if the matrix should be less than %d");
exit(EXIT_FAILURE);
}
if(w == 0) break;
adjmatrix[i][j] = w;
num_edge++;
}
return num_edge;
}
void BellmanFord(int v){//compute all shortest path from v to every vertex ,and allow edge is negative
int i, k, min = MAX_DISTANCE_LIMIT, j, minpos;
for(int i = 0; i < MAX_VERTEX; i++)
distance[i] = adjmatrix[v][i]; //value of dist"1"
for(k = 2; k <= MAX_VERTEX - 1; k++){
traverse(v,k); //traverse(v ,k)will set found[i] that we can reach in k steps TRUE.
for(i = 0; i < MAX_VERTEX; i++ ){
if( found[i] == FALSE)
continue;
for(j = 0; j < MAX_VERTEX; j++)
if(adjmatrix[j][i]+distance[j] < min) {
min = adjmatrix[j][i]+distance[j];
minpos = j;
}
distance[i] = MIN(distance[i],adjmatrix[minpos][i]+distance[j]);
}
for(i = 0; i < MAX_VERTEX; i++ ) //initial found array to FALSE
found[i] = FALSE;
}
}
void traverse(int v,int times){
int i, next_order ,count = 0;
if (times == 0) return ;
for(i = 0; i < MAX_VERTEX; i++){
if((adjmatrix[v][i] != MAX_DISTANCE_LIMIT) && (!found[i])){
found[i] = TRUE;
if(times == 1)
return;
push(i);
count++;
}
}
for(i = 0; i < count; i++){
next_order = pop();
traverse(next_order,times-1);
}
return;
}
void push(int vertex){
if(top >= MAX_STACK_LENGTH){
fprintf(stderr, "The stack is full.");
exit(EXIT_FAILURE);
}
stack[++top] = vertex;
}
int pop(void){
if(top == -1){
fprintf(stderr, "The stack is empty.\n");
exit(EXIT_FAILURE);
}
else
return stack[top--];
}
/************************************
*graph information (w,tail,head)
input
6 0 1
5 0 2
5 0 3
-1 1 4
1 2 4
-2 2 1
-2 3 2
-1 3 5
3 5 6
3 4 6
0 0 0 //end the input
************************************
adjmatrix:
0 6 5 5 0 0 0
0 0 0 0 -1 0 0
0 -2 0 0 1 0 0
0 0 -2 0 0 -1 0
0 0 0 0 0 0 3
0 0 0 0 0 0 3
0 0 0 0 0 0 0
**************************************/

How to count Up and Down using For Loop

I want to get output like this using nested for loops:
0 0
0 1
0 2
0 3
1 3
1 2
1 1
1 0
2 0
2 1
2 2
2 3
3 3
3 2
3 1
3 0
So I came up with this solution:
for(i=0;i<4;i++) {
if(i == 1){
for(j=3;j>=0;--j) {
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}else if(i == 3){
for(j=3;j>=0;--j) {
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}else{
for(j=0;j<4;j++) {
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}
}
This works but is there way to do this without if conditions inside the loops?
Here you are.
#include <stdio.h>
int main(void)
{
const int N = 3;
for ( int i = 0; i <= N; i++ )
{
for ( int j = 0; j <= N; j++ )
{
printf( "%d %d\n", i , i % 2 == 0 ? j : N - j );
}
}
return 0;
}
The program output is
0 0
0 1
0 2
0 3
1 3
1 2
1 1
1 0
2 0
2 1
2 2
2 3
3 3
3 2
3 1
3 0
Or the loops can be written like
const int N = 4;
for ( int i = 0; i < N; i++ )
{
for ( int j = 0; j < N; j++ )
{
printf( "%d %d\n", i , i % 2 == 0 ? j : N - j - 1 );
}
}
I am not the Arduino guy, but as its similar to C and this question is more about the algorithm let me sketch an approach in C:
#define LEFT_START (0)
#define LEFT_END (3)
#define RIGHT_START (0)
#define RIGHT_END (3)
enum DIRECTION {
DOWN = -1,
UP = 1
};
int main(void)
{
for (int direction = UP, i = LEFT_START, j = RIGHT_START - sign;
i <= LEFT_END;
++i, direction *= -1)
{
for (j += direction;
j >= RIGHT_START && j <= RIGHT_END;
j += direction)
{
printf("%d %d\n", i, j);
}
}
}
No if/then, not explicitly, nor implicitly via ternary-operator, BTW. ;)
I don't know what your purpose was, but you need to use if statement. This code will do the thing you want
int n =3;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
for (int i=0; i<=n; i++){
if(i%2 == 0){
for (int j=0; j<=n; j++){
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}
else{
for (int j=n; j>=0; j--){
Serial.print(i);
Serial.print(" ");
Serial.println(j);
}
}
}
}
The output looks like this,
Defining variables/constant n, i, j is entirely up to you based on your project. This code is just a simple demonstration.

Using for loop to print out output

My for loops seems not working properly. First number which tells me how many task do I want my program to do is n. When I input 1 or 2, it works, but when I input 3 and more, it starts to struggle. Every row has 3 numbers separated by a space as you can see in the code. I am not getting all outputs. Algorithm in this program works perfect so no problem there.
Please ignore comments in the code. And sorry for my english.
#include <stdio.h>
int n;
int i;
int s;
int d;
int p;
int k;
int A;
int x;
int r[];
int koniec;
main()
{
scanf("%d", &n);
while( !(n >= 1 && n <=1000) )
{
//printf ( "max 1000 uloh min 1 \n");
return 1;//scanf("%d", &n);
}
for( i=1; i < n; i++)
{
scanf("%d %d %d", &s, &p, &d);
while((s < 1) || (s > 15000) || (p < 1) || (p > 4000) || (d < 1) || (d > 15000)) {
//printf ("prekroceny limit \n");
return 1; // scanf("%d %d %d", &s, &p, &d);
}
k = s / d;
A = s - ( k * d );
if ( A == 0 )
{
r[i] == 0;
}
else
{
//s = k * d + A ;
x = ( A * p ) / d ;
r[i] = p - x ;
}
}
for ( koniec = 0 ; koniec < i+1 ; koniec++ )
{
printf ( "%d", r[koniec] ) ;
printf ( "\n");
}
system("pause");
}
Example input so you can understand better:
4
5 4 4
6 100 3
500 5 1000
314 159 26
and output:
3
0
3
147
EDIT>
5
3434 234 2345
14455 345 12
134 145 1345
9242 2455 13455
83 34 133
output:
126
144
141
769
13
or something shorter>
input:
2
15000 1 1
1 4000 1
output:
0
0
Im getting return value 1 in both examples
My final code edit:
#include <stdio.h>
#include <stdlib.h>
int n;
int i;
int s;
int d;
int p;
int k;
int A;
int x;
int *r;
int koniec;
main()
{
scanf("%d", &n);
while( !(n >= 1 && n <=1000) )
{
return 0;//printf ( "max 1000 uloh min 1 \n");
//scanf("%d", &n);
}
r = (int *)malloc(n*sizeof(int));
for(i=0; i < n; i++)
{
scanf("%d %d %d", &s, &p, &d);
while((s < 1) || (s > 15000) || (p < 1) || (p > 4000) || (d < 1) || (d > 15000))
{
//printf ("prekroceny limit \n");
return 0; //scanf("%d %d %d", &s, &p, &d);
}
k = s / d;
A = s - ( k * d );
if ( A == 0 )
{
r[i] = 0;
}
else
{
//s = k * d + A ;
x = ( A * p ) / d ;
r[i] = p - x ;
}
}
for ( koniec = 0 ; koniec < n ; koniec++ )
{
printf ( "%d", r[koniec] ) ;
printf ( "\n");
}
free(r);
return 0;
}
You need to use malloc() to allocate memory dynamically. (Also #include stdlib.h)
For instance, add the following line after the first while loop :
//Note - at the top, change int r[] to the below:
int *r; //Instead of int r[]
//End note
while( !(n >= 1 && n <=1000) )
{
printf ( "max 1000 uloh min 1 \n");
scanf("%d", &n);
}
r = (int *) malloc(n*sizeof(int)); //Allocate "n" integers to your 'array r'
It should also be noted that once you are done using the array r, you must free() this memory like so:
free(r);
In addition, there are some other coding problems:
Be sure for( i=1; i < n; i++) is what you want. You use "i" to index your array, but arrays in C start from 0. So it (likely) should read for( i=0; i < n; i++).
r[i] == 0; is used falsely as an assignment. Use a single = to assign a value to a variable. Use the double equals == to compare two values.
for ( koniec = 0 ; koniec < i+1 ; koniec++ ) will likely through an error. Your i will be one less than n from the for-loop above it. So trying to iterate to i+1 or n will result in an array out of bounds problem -- aka a Segmentation Fault.
Edit - This should do what you want:
#include <stdio.h>
#include <stdlib.h>
int n;
int i;
int s;
int d;
int p;
int k;
int A;
int x;
int *r;
int koniec;
main()
{
scanf("%d", &n);
while( !(n >= 1 && n <=1000) )
{
//printf ( "max 1000 uloh min 1 \n");
//scanf("%d", &n);
return 1;
}
r = (int *)malloc(n*sizeof(int));
for(i=0; i < n; i++)
{
scanf("%d %d %d", &s, &p, &d);
while((s < 1) || (s > 15000) || (p < 1) || (p > 4000) || (d < 1) || (d > 15000))
{
//printf ("prekroceny limit \n");
//scanf("%d %d %d", &s, &p, &d);
return 1;
}
k = s / d;
A = s - ( k * d );
if ( A == 0 )
{
r[i] = 0;
}
else
{
s = k * d + A ; //This line does nothing... Just so you know
x = ( A * p ) / d ;
r[i] = p - x ;
}
}
for ( koniec = 0 ; koniec < n ; koniec++ )
{
printf ( "%d", r[koniec] ) ;
printf ( "\n");
}
free(r);
system("pause");
return 0;
}
Input:
4
5 4 4
6 100 3
500 5 1000
314 159 26
Output:
3
0
3
147
Allocate space for r[].
Change assignment.
Change for loop range.
//int r[];
main() {
scanf("%d", &n);
// while( !(n >= 1 && n <=1000) )
if (!(n >= 1 && n <=1000) ) {
return 1;//scanf("%d", &n);
}
int r[n]; // allocate
// for( i=1; i < n; i++)
for( i=0; i < n; i++) // Change range (#MrHappyAsthma)
...
// r[i] == 0;
r[i] = 0; // change
r[i] = p - x ;
// for ( koniec = 0 ; koniec < i+1 ; koniec++ )
for ( koniec = 0 ; koniec < n ; koniec++ )

Resources