Code returning different outputs using goto - c

I'm writing a function that takes an input n and creates a 1D array of size (2n-1)^2 to simulate a square. I.e. for an input of n = 1, there is just one point, for an input of n = 2, it would look like
0 1 2
3 4 5
6 7 8
and for n = 3 it would look like
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
where each number is a point.
The function terminates when the current location is detected at being on an edge and the point attempts to move off of the square's grid.
The purpose of this is to simulate how many points are visited for squares of different sizes, from n=2^0 up to n=2^8 and to return the fraction of how many points are visited over the total amount of points in the square.
The function generates a random number and checks the modulus of it against 4, and if it returns 0, the location is moved up 1, if it returns 1, the location is moved right, 2 goes down, and 3 goes left.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double two_d_random (int n) {
int tot_points = (2 * n - 1)*(2 * n - 1);
int value = (n*n)+((n-1)*(n-1))-1; //center
int length = 2 * n - 1; //length of side
int *array = (int *)malloc (sizeof (int) * tot_points);
int count = 0;
array[value] = 1;
while (1 == 1) {
int r = rand () % 4;
array[value] = 1;
if (r == 0) {//UP
if ((value >= 0) && (value < length)) {
goto a;
}
else {
array[value] = 1;
value -= length;
}
}
else if (r == 1) {//RIGHT
if ((value % length) == (2*n-2)){
goto a;
}
else {
array[value] = 1;
value += 1;
}
}
else if (r == 2) {//DOWN
if ((value < tot_points) && (value >= (tot_points - length))) {
goto a;
}
else {
array[value] = 1;
value += length;
}
}
else if (r == 3) {//LEFT
if (value % length == 0) {
goto a;
}
else {
array[value] = 1;
value -= 1;
}
}
}
a:
for (int i = 0; i < tot_points; i++) {
if (array[i] == 1) {
count += 1;
}
}
free (array);
return 1.0 * count / tot_points;
}
int main ()
{
int trials = 1000;
srand (12345);
for (int n = 1; n <= 256; n *= 2)
{
double sum = 0.;
for (int i = 0; i < trials; i++)
{
double p = two_d_random(n);
sum += p;
}
printf ("%d %.3lf\n", n, sum / trials);
}
return 0;
}
My current problem is that while I run it on my machine, I get a range of values I'm not expecting:
However, when a colleague runs it on their machine, they get the following which is what I expected:
I realize this is a large amount to ask at one point. I also realize that I should not use goto. I've put a lot of time into this however and I've no idea how to fix this. Any help is greatly appreciated.

You need to initialise your array. When calling malloc() it just returns a chunk of un-initialised memory. Either initialise it, or use calloc() instead, to get pre-zeroed memory.
double two_d_random( int n )
{
int tot_points = ( 2 * n - 1 ) * ( 2 * n - 1 );
int value = ( n * n ) + ( ( n - 1 ) * ( n - 1 ) ) - 1; //center
int length = 2 * n - 1; //length of side
int *array = (int *) malloc( sizeof( int ) * tot_points );
int count = 0;
// Initialise the array to zero
for ( int i=0; i<tot_points; i++ )
{
array[i] = 0;
}
array[value] = 1;
while ( 1 == 1 )
{
int r = rand() % 4;
array[value] = 1;
if ( r == 0 )
With this modification, I get results similar to what you reported as desired:
1 1.000
2 0.367
4 0.221
8 0.154
16 0.122
32 0.101
64 0.085
128 0.077
256 0.071

Related

dealing with dups in end of the array

This is the task I have got:
I need to write a function (not recursive) which has two parameters.
An array of integers.
An integer representing the size of the array.
The function will move the duplicates to an end of the array.
And will give the size of the different digits.
Example:
5 , 2 , 4 , 5 , 6 , 7 , 2, n = 7
we will get back 5 , 2 , 4 , 6 , 7 , 5 , 2 and 5
We must keep the original sort as it is (which means like in example 5 must)
It does not matter how we sort the duplicates ones but just keep the sort for the original array as it is)
The function has to print the number of different digits (like in example 5)
The the input range of numbers in array [-n,n]
I can only use 1 additional array for help.
It has to be O(n)
I tried it so many times and feel like am missing something. Would appreciate any advice/suggestions.
int moveDup(int* arr, int n)
{
int* C = (int*)calloc(n * 2 + 1, sizeof(int));
assert(C);
/*int* count = C + n;*/
int *D = arr[0];
int value = 0, count = 0;
for (int i = 0; i < n; i++)
{
value = arr[i];
if (C[value + n] == 0)
{
*D = arr[i];
D++;
count++;
}
C[value + n] = C[value + n] + 1;
}
while (1 < C[value + n])
{
*D = i;
D++;
C[value + n]--;
}
free(C);
return count;
}
This algorithm will produce the required results in O(n) arithmetic complexity:
Input is an array A with n elements indexed from A0 to An−1 inclusive. For each Ai, −n ≤ Ai ≤ n.
Create an array C that can be indexed from C−n to C+n, inclusive. Initialize C to all zeros.
Define a pointer D. Initialize D to point to A0.
For 0 ≤ i < n:
If CAi=0, copy Ai to where D points and advance D one element.
Increment CAi.
Set r to the number of elements D has been advanced from A0.
For −n ≤ i ≤ +n:
While 1 < CAi:
Copy i to where D points and advance D one element.
Decrement CAi.
Release C.
Return r. A contains the required values.
A sample implementation is:
#include <stdio.h>
#include <stdlib.h>
#define NumberOf(a) (sizeof (a) / sizeof *(a))
int moveDuplicates(int Array[], int n)
{
int *memory = calloc(2*n+1, sizeof *Array);
if (!memory)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
int *count = memory + n;
int *destination = Array;
for (int i = 0; i < n; ++i)
// Count each element. If it is unique, move it to the front.
if (!count[Array[i]]++)
*destination++ = Array[i];
// Record how many unique elements were found.
int result = destination - Array;
// Append duplicates to back.
for (int i = -n; i <= n; ++i)
while (0 < --count[i])
*destination++ = i;
free(memory);
return result;
}
int main(void)
{
int Array[] = { 5, 2, 4, 5, 6, 7, 2 };
printf("There are %d different numbers.\n",
moveDuplicates(Array, NumberOf(Array)));
for (int i = 0; i < NumberOf(Array); ++i)
printf(" %d", Array[i]);
printf("\n");
}
here is the right answer, figured it out by myself.
int moveDup(int* arr, int n)
{
int* seen_before = (int*)calloc(n * 2 + 1, sizeof(int));
assert(seen_before);
int val = 0, count = 0, flag = 1;
int j = 0;
for (int i = 0; i < n; i++)
{
val = arr[i];
if (seen_before[arr[i] + n] == 0)
{
seen_before[arr[i] + n]++;
count++;
continue;
}
else if (flag)
{
j = i + 1;
flag = 0;
}
while (j < n)
{
if (seen_before[arr[j] + n] == 0)
{
count++;
seen_before[arr[j] + n]++;
swap(&arr[i], &arr[j]);
j++;
if (j == n)
{
free(seen_before);
return count;
}
break;
}
/*break;*/
j++;
if (j == n)
{
free(seen_before);
return count;
}
}
}
}
second right answer
int* mem = (int*)calloc(2 * n + 1, sizeof * arr);
assert(mem);
int* count = mem + n;
int* dest = arr;
for (i = 0; i < n; ++i)
{
if (count[arr[i]]++ == 0)
{
*dest = arr[i];
*dest++;
}
}
res = dest - arr;
for (i = -n; i <= n; ++i)
{
while (0 < --count[i])
{
*dest++ = i;
}
}
free(mem);
return res;

How optimize below code to determine the total number of prime numbers below 1,000,000,000 have the sum of their digits equal to 14 in C?

/Write a program to determine the total number of prime numbers below 1000,000,000 have the sum of their digits equal to 14? Make sure the execution time is few seconds./
#include<stdio.h>
#include<math.h>
int main() {
int i, j, count = 0, temp = 0, n, ans = 0, tot = 0;
for (i = 1; i <= 1000000000; i++) {
for (j = 2; j <= i / 2; j++) {
if (i % j == 0) {
count++;
}
}
if (count == 0) {
n = i;
while (n != 0) {
temp = n % 10;
n = n / 10;
ans = ans + temp;
}
if (ans == 14) {
tot++;
printf("%d,", i);
}
ans = 0;
temp = 0;
}
count = 0;
}
// printf("%d:\n",tot);
return 0;
}
Two simply improvements (amongst other):
1: Rather than iterate to i/2, iterate to the square root of i - that is j*j <= i.** This is a huge speed-up.
2: Quit loop once a factor found.
// for(j=2;j<=i/2;j++) {
// if(i%j==0) {
// count++;
// }
//}
for(j=2;j<=i/j;j++) { // _much_ lower limit
if(i%j==0) {
count++;
break; // No need to find more factors: `i` is not a prime.
}
}
Functionality: Inside if(count==0), I'd expect ans == 0 before while(n!=0).
** Use j<=i/j to prevent overflow. A good compiler will see a nearby i%j and often perform both i/j, i%j for the time cost of one.
The digit-sum function could also use a early return like:
int dsum14(int n) {
int sum = 0;
for (; n; n /= 10)
if ((sum += n % 10) > 14)
return 0;
return sum == 14 ? 1 : 0;
}
But how to combine the (efficient) prime search and this sum condition?
int n, cnt = 0;
for (n = 3; n < 1000*1000*1000; n += 2)
if (n%3 && n%5 && dsum14(n) && n%7 && n%11 && n%13)
cnt++;
This gives 77469 in 1.5 seconds. With dsum() at either end of the logical chain it is almost double.
The && n%7 && n%11 && n%13 part would be replaced by a function using a list of primes up to about 32000 (square root of max).
...or you can optimize it to 0.1 seconds, by tweaking the digsum function.
There are "only" 575 three-digit numbers 000-999 with sum 14 or less. So I prepare them and combine three of them to get a 9-digit number. Generating them instead of filtering them.
The tail looks like:
920000021
920000201
920001011
920010011
920100011
920100101
920101001
921001001
931000001
total count: 22588
real 0m0.098s
user 0m0.100s
sys 0m0.002s
And the start:
59
149
167
239
257
293
347
383
419
Not 100% sure if it's correct, but the total count also seems reasonable.
It all relies on the given max of 1000 Mio. digsum_prime() uses it to build the candidate number from three (almost) equal parts.
Code:
#include <stdio.h>
#include <stdlib.h>
int parr[5000] = {3};
struct {
int tri, sum;
} ts[999];
void primarr(void) {
int maxn = 32000;
int i = 1;
for (int n = 5; n < maxn; n += 2)
for (int div = 3;; div += 2) {
if (!(n % div))
break;
if (div*div > n) {
parr[i++] = n;
break;
}
}
}
int isprime(int n) {
for(int i = 0;; i++) {
if (!(n % parr[i]))
return 0;
if (parr[i]*parr[i] > n)
return 1;
}
}
int dsum(int n) {
int sum = 0;
for (; n; n /= 10)
sum += n % 10;
return sum;
}
int tsarr(void) {
int i = 0;
for (int n = 0; n < 1000; n++) {
int digsum = dsum(n);
if (digsum <= 14) {
ts[i].tri = n;
ts[i].sum = digsum;
i++;
}
}
return i;
}
int digsum_prime() {
int cnt = 0;
int tslen = tsarr();
printf("tslen: %d\n", tslen);
int high, mid, low;
int sum, num;
for (high = 0; high < tslen; high++) {
if(ts[high].sum > 13)
continue;
for (mid = 0; mid < tslen; mid++) {
if(ts[mid].sum + ts[high].sum > 13)
continue;
sum = ts[mid].sum + ts[high].sum;
for (low = 0; low < tslen; low++)
if (ts[low].tri % 2)
if(ts[low].sum + sum == 14) {
num = ts[high].tri * 1000*1000
+ ts[mid] .tri * 1000
+ ts[low] .tri;
if (isprime(num)) {
cnt++;
printf("%d\n", num);
}
}
}
}
return cnt;
}
int main(void) {
primarr();
printf("total count: %d\n", digsum_prime());
}
Changing 13-13-14 to 3-3-4 (but same preparation part) gives an overview - in 0.005 s!
tslen: 575
13
31
103
211
1021
1201
2011
3001
10111
20011
20101
21001
100003
102001
1000003
1011001
1020001
1100101
2100001
10010101
10100011
20001001
30000001
101001001
200001001
total count: 25
real 0m0.005s
user 0m0.005s
sys 0m0.000s
Make sure the execution time is few seconds.
oops
But the limits of OP are well chosen: a naive approach takes several seconds.

Brute Force in C for 3Sum - But how do I detect duplicate triplets?

I am aware this is a brute force and non optimal approach to solving the 3Sum problem. It does the job of detecting the triplets which sum up to zero. But I am looking for ways to detect duplicate triplets. I am not able to come up with the logic to look for similar triplet combinations which have already been considered. Thanks!
int** threeSum(int* nums, int numsSize, int *returnSize)
{
int count = 0;
int **res = NULL;
for (int i=0; i<(numsSize-2) ; i++)
{
for (int j=i+1; j<(numsSize-1) ; j++)
{
for(int k=j+1; k<numsSize ; k++)
{
if (0==(nums[i]+nums[j]+nums[k]))
{
if (count > 0)
{
res = (int **)realloc(res,sizeof(int *)*(count+1));
res[count] = (int *) malloc(sizeof(int)*3);
res[count][0] = nums[i];
res[count][1] = nums[j];
res[count][2] = nums[k];
count++;
}
else if (0==count)
{
res = (int **) malloc(sizeof(int *)*1);
res[0] = (int *) malloc(sizeof(int)*3);
res[0][0] = nums[i];
res[0][1] = nums[j];
res[0][2] = nums[k];
count++;
}
}
}
}
}
*returnSize=count;
if (count > 0)
return res;
else
return NULL;``
}
You can simplify your code as there are redundant blocks:
realloc can be called with NULL and acts like malloc.
returning res is OK when count is 0 as it was initialized to NULL.
You can check for duplicates, you can sort the triplet and search it in the list of matches before insertion, with brute force too:
int **threeSum(int *nums, int numsSize, int *returnSize) {
int count = 0;
int **res = NULL;
for (int i = 0; i < numsSize - 2; i++) {
for (int j = i + 1; j < numsSize - 1; j++) {
for (int k = j + 1; k < numsSize; k++) {
if (nums[i] + nums[j] + nums[k] == 0) {
int a = nums[i], b = nums[j], c = nums[k], n;
if (a > b) { int t = a; a = b; b = t; }
if (b > c) { int t = b; b = c; c = t; }
if (a > b) { int t = a; a = b; b = t; }
for (n = 0; n < count; n++) {
if (a == res[n][0] && b == res[n][1])
break;
}
if (n == count) {
int **p = realloc(res, sizeof(*p) * (count + 1));
int *p1 = malloc(sizeof(*p1) * 3);
if (p == NULL || p1 == NULL) {
for (n = 0; n < count; n++)
free(res[n]);
free(res);
free(p);
free(p1);
*returnSize = -1;
return NULL;
}
res = p;
p1[0] = a;
p1[1] = b;
p1[2] = c;
res[count] = p1;
count++;
}
break; // any other match would be a duplicate.
}
}
}
}
*returnSize = count;
return res;
}
Notes:
no need to test if c == res[n][2] because res only contains matches
no need to test further elements for the same i and j after a match is found.
Edit I deleted this incorrect answer, but now enabled it (although not updated from various comments, because it is still wrong).
For what it's worth I changed the duplicate removal to this:
int terms = 2;
// . . .
// remove duplicates
for(int i = 2; i < TERMS; i++) {
if(nums[i] != nums[terms - 1] || nums[i] != nums[terms - 2]) {
nums[terms++] = nums[i];
}
}
First I sort the array, and then remove duplicates.
Optionally, I make early loop terminations when the 0 sum is impossible.
I have not created an array of solutions, only printed – I leave that to you.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define TERMS 30 // length of array
#define MAXVAL 9 // value range + - MAXVAL
#define CHECK // compiler option quit when 0 sum is impossible
int cmp(const void *a, const void *b) {
return (*(int*)a) - (*(int*)b);
}
void show(char *legend, int *nums, int size)
{
printf("%s\n", legend);
for(int i = 0; i < size; i++) {
printf("%d ", nums[i]);
}
printf("\n\n");
}
int main(void) {
int nums[TERMS];
int terms = 1;
int sum;
int results = 0;
// build array
//srand((unsigned)time(NULL)); // comment out for repeatable values
for(int i = 0; i < TERMS; i++) {
nums[i] = rand() % (MAXVAL * 2 + 1) - MAXVAL;
}
show("input", nums, TERMS);
// sort array
qsort(nums, TERMS, sizeof nums[0], cmp);
show("sorted", nums, TERMS);
// remove duplicates
for(int i = 1; i < TERMS; i++) {
if(nums[i] != nums[terms - 1]) {
nums[terms++] = nums[i];
}
}
show("removed dups", nums, terms);
// find triplets with 0 sum
printf("zero sum triplets\n");
for(int i = 0; i < terms; i++) {
#ifdef CHECK
if(nums[i] > 0) {
// early termination if impossible
break;
}
#endif
for(int j = i + 1; j < terms; j++) {
for(int k = terms-1; k > j; k--) {
#ifdef CHECK
if(nums[k] < 0) {
// early termination if impossible
break;
}
#endif
sum = nums[i] + nums[j] + nums[k];
if(sum == 0) {
printf("%4d %4d %4d\n", nums[i], nums[j], nums[k]);
results++;
}
}
}
}
printf("\n%d results\n", results);
return 0;
}
Program output
input
-6 9 -2 5 8 2 -7 -6 -8 2 -4 -3 -3 3 -4 7 3 1 -8 -7 6 3 -2 -8 -2 4 8 -8 6 -7
sorted
-8 -8 -8 -8 -7 -7 -7 -6 -6 -4 -4 -3 -3 -2 -2 -2 1 2 2 3 3 3 4 5 6 6 7 8 8 9
removed dups
-8 -7 -6 -4 -3 -2 1 2 3 4 5 6 7 8 9
zero sum triplets
-8 1 7
-8 2 6
-8 3 5
-7 -2 9
-7 1 6
-7 2 5
-7 3 4
-6 -3 9
-6 -2 8
-6 1 5
-6 2 4
-4 -3 7
-4 -2 6
-4 1 3
-3 -2 5
-3 1 2
16 results
Since you want to stay with brute force, I am responding with that context. You can do an increasing sort your detected triplet into a temp array of 3 ints, before storing it in the res. When a new triplet is detected, sort it and insert that into the temp array, compare the temp array with the arrays stored in your res array to detect a duplicate set and if duplicate continue.
ie. compare res[0][0], res[0][1], res[0][2] with the temp[0], temp[1], temp[2]and detect the duplicates for every triplet that exists in res. And since every res row is sorted, it should be easy to detect duplicates by comparing position to position.
let us say res after a few rounds looks as follows:
-2 1 1
-3 1 2
-7 3 4
and if a new triplet detected is say [4, 3, -7], in temp it will be [-7, 3, 4] and when we loop through res and compare, duplicate will be detected.
To sort num[i], num[j], num[k] you could do the following (again staying in your brute force context):
if ((num[i] > num[j]))
{
/* Compare the first two numbers in num triplet */
temp[0] = num[j];
temp[1] = num[i];
}
else
{
temp[0] = num[i];
temp[1] = num[j];
}
//now compare the third number num[k]
if (num[k] < temp[0])
{
/* num[k] is the smallest number, shift the temp array to the right */
temp[2] = temp[1];
temp[1] = temp[0];
temp[0] = num[k]; /* Add the third number in the beginning of temp array */
}
else
if (num[k] >= temp[1])
{
/* num[k] is the shortest number, no shifting needed */
temp[2] = num[k]; /* Add the number num[k] to the end of temp array */
}
else
{
/* num[k] is in the middle, shift temp[1] to the right and insert num[k] */
temp[2] = temp [1]; /* Shift the last number in temp[k] */
temp[1] = num[k]; /* Overwrite temp[1] with the new number in num[k] which will put num[k] in the middle */
}
I haven't tested this code yet.

Binary search function can't find specified numbers if they are at the end or beginning of a sorted array

As the title says above, a binary search function I wrote for some reason can't find the number it was given if it is at the end or beginning of an array. I have tried looking for the issue in the debugger, but nothing strange ever shows up.
For instance if you put in the input 24 25 26 27 28 and the number it was trying to find was 28, it would return false.
But if the numbers were 24 25 28 26 30 it would return true
(assuming these numbers were already sorted beforehand)
bool search(int value, int values[], int n)
{
// check if only 1 item exists in values and if it is the item which is being looked for
if (n == 1)
{
if (value == values[0]) return true;
else return false;
}
int middle = n / 2;
// if the value is greater than middle, search the right half of the array
if (value > values[middle])
{
// initialize rightHalf since it is a variable length array
int rightHalf[n];
for(int x = 0; x <= n; x++) rightHalf[x] = 0;
int rightHalfSize = n - middle;
if (value > values[middle])
{
int rightHalfSize = n - middle - 1;
for (int i = 0, m = middle + 1; i < rightHalfSize; i++, m++)
{
rightHalf[i] = values[m];
}
}
return search(value, rightHalf, rightHalfSize);
} // if the value is less than middle, search the left half of the array
else if (value < values[middle])
{
// initialize leftHalf since it is a variable length array
int leftHalf[n];
for(int y = 0; y <= n; y++) leftHalf[y] = 0;
int leftHalfSize = n - middle;
for (int i = 0, m = 0; i < middle; i++, m++)
{
leftHalf[i] = values[m];
}
return search(value, leftHalf, leftHalfSize);
}
else if (value == values[middle]) return true;
return false;
}
It is unclear the purpose of creating within the function a variable length array that results in undefined behavior at least due to the loop
int rightHalf[n];
for(int x = 0; x <= n; x++) rightHalf[x] = 0;
because there is an attempt to change the memory beyond the array for x equal to n.
The function that determines whether the target value is present can be written much simpler.
For example
#include <stdio.h>
#include <stdbool.h>
bool search( const int a[], size_t n, int value )
{
if ( !n )
{
return false;
}
else
{
size_t middle = n / 2;
if ( a[middle] < value )
{
return search( a + middle + 1, n - middle - 1, value );
}
else if ( value < a[middle] )
{
return search( a, middle, value );
}
else
{
return true;
}
}
}
int main(void)
{
int a[] = { 24, 25, 26, 27, 28 };
const size_t N = sizeof( a ) / sizeof( *a );
printf( "a[0] - 1 is found - %d\n", search( a, N, a[0] - 1 ) );
for ( size_t i = 0; i < N; i++ )
{
printf( "a[%zu] is found - %d\n", i, search( a, N, a[i] ) );
}
printf( "a[%zu] + 1 is found - %d\n", N - 1, search( a, N, a[N-1] + 1 ) );
return 0;
}
The program output is
a[0] - 1 is found - 0
a[0] is found - 1
a[1] is found - 1
a[2] is found - 1
a[3] is found - 1
a[4] is found - 1
a[4] + 1 is found - 0

Copying values from one array to another

It should be simple,two arrays,one with 5 other with 6 elements.
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i=0;
int k=0;
int v[5] = {2,3,4,5,6};
int g[6];
for( i = 1; i <= 6; i++ ){
k= i + 1;
if ( 1 == i && 2 == i)
{
g[k]=v[i];
}
else
{
g[k]=(v[i]+10);
}
printf("%d\n",g[k]);
}
return 0;
}
I got this
13
14
15
16
32776
10
I really wanted
2 3 13 14 15 16
Where is my mistake?Should I create function or what?
Problem 1
Array indexes are 0-based, meaning v[0] and g[0] are the first element of the arrays. All your i and k are off by one 1.
Problem 2
1 == i && 2 == i is never true. If 1 == i, then 2 != i. If 2 == i, then 1 != i.
1 == i && 2 == i
should be
1 == i || 2 == i
Problem 3
Your loop has 5 passes, but it requires 6!
1) g[0] = v[0];
2) g[1] = v[1];
3) g[2] = v[1]+10;
4) g[3] = v[2]+10;
5) g[4] = v[3]+10;
6) g[5] = v[4]+10;
Solution
#include <stdlib.h>
#include <stdio.h>
int main() {
int v[5] = {2,3,4,5,6};
int g[6];
for( int i = 0; i < sizeof(g)/sizeof(*g); ++i ) {
if ( 0 == i || 1 == i )
g[i] = v[i];
else
g[i] = v[i-1]+10;
printf("%d\n", g[i]);
}
return 0;
}
Note that
if ( 0 == i || 1 == i )
can be simplified to
if ( 2 < i )
Your code has a few problems:
if ( 1 == i && 2 == i) will always return false as a variable cannot be both 1 and 2 at the same time.
Your loop iterator takes values larger than they should; when i becomes 5 and 6, v[i] and g[i] triggers reads to memory locations beyond the respective arrays' memory ranges, which explains the random values in your output.
I think this is what you want:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i = 0;
int v[5] = {2, 3, 4, 5, 6};
int g[6];
for ( i = 0; i < 6; i++ )
{
if ( i < 2 )
{
g[i] = v[i];
}
else
{
g[i] = ( v[i - 1] + 10 );
}
printf ( "%d\n", g[i] );
}
return 0;
}
Output:
2 3 13 14 15 16
It never enter in the if conditional block because i cannot be 1 and 2 at the same time..
So your code will enter just in else...
and it wil start from index 1;
so in this expresion from else : g[k]=(v[i]+10); --- v[i]=> 3 and when you arrive at index 5 or 6 it is outside of your v array....
for( i = 1; i <= 6; i++ ){
k= i + 1;
if ( 1 == i && 2 == i) //never enter here...
{
g[k]=v[i];
}
else
{
g[k]=(v[i]+10); //index get outside the vector length
}
printf("%d\n",g[k]);
}

Resources