The program just breaks when I have two or more FOR loops one after another.
The program was supposed to generate 20 random numbers inside an ARRAY of 20 numbers and then separate the odd ones from the even ones into two different arrays, one for odd numbers, and one for even numbers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main(){
srand(time (NULL));
int vector[20];
int vectoreven[20];
int vectorodd[20];
int c = 0;
for(c = 0;c <= 19;c = c+1){
vector[c] = rand()%100;
}
c = 0;
for(c = 0;c <= 19; c = c+1){
printf("\nVector %d = %d", c, vector[c]);
}
c = 0;
for(int d = 0;d <= 19; d = d+1){
if(vector[d]%2 == 0){
vectoreven[d] = vector[d];
printf("\nVector even %d = {%d}", d,
vectoreven[d]);
}else if(vector[d]%2 != 0){
vectorodd[d] = vector[d];
printf("\nVector odd %d = I%dI", d, vectorodd[d]);
}
}
}
RESULT
You need to use separate index variables for the arrays you're writing to than the array you're iterating over. This way you'll fill each array sequentially. Your method leaves lots of unfilled elements in the middle of the arrays, with no way to tell which these are.
int even_index = 0;
int odd_index = 0;
for (int d = 0; d < 20; d++) {
if (vector[d] % 2 == 0) {
vectoreven[even_index++] = vector[d];
} else
vectorodd[odd_index++] = vector[d];
}
}
Related
I am successful in identifying prime and composite from an array. But my qsort function seem to not have any effect when I print the output. I need the primes to be ascending and composite to be descending. When I run the code, it does not sort the output, though it identifies primes and composites.
#include <stdio.h>
#include <stdlib.h>
int compare_Asc(const void *a_void, const void *b_void) {
int a = *(int *)a_void;
int b = *(int *)b_void;
return a - b;
}
int compare_Desc(const void *a_void, const void *b_void) {
int a = *(int *)a_void;
int b = *(int *)b_void;
return b - a;
}
int main() {
int i = 0, n, x, p, c, z, w, j = 0, k = 0, cmpst, null;
int prm;
int prime[50], composite[50], input[50];
printf("How many inputs are you be working with?\nNote: 50 Maximum Inputs\n");
scanf("%d", &n);
printf("Enter the numbers.\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &input[i]);;
}
for (i = 0; i < n; i++) {
if (input[i] % 2 != 0) {
prime[p++] = input[i];
prm = p;
} else
if (input[i] >= 2 && input[i] % 2 == 0) {
composite[c++] = input[i];
cmpst = c;
}
}
printf("Prime Numbers:");
qsort(prime, prm, sizeof(int), compare_Asc);
for (i = 0; i < p; i++) {
printf("%d", prime[p]);
}
printf("Composite Numbers:");
qsort(composite, cmpst, sizeof(int), compare_Desc);
for (i = 0; i < c; i++) {
printf("%d", composite[c]);
}
return 0;
}
There are some major issues, in the posted code, worth mentioning.
Variables
Declaring all the variables at the beginning of the scope, instead of just before where they are used, can hide bugs.
Uninitialized variables, are an even worse source of errors, because their values are indeterminated.
int i=0, n, x, p, c, z, w, j=0, k=0, cmpst, null;
// ^ ^ ^^^^ ?
// ... Later, in the code:
prime[p++] = input[i];
// ^^^ What value is incremented?
// Where is [p++]? Is it inside the prime array?
A correct initialization would prevent undefined behavior.
int p = 0, c = 0;
int composite[50], input[50];
for(int i = 0; i < n ; ++i) {
if ( is_prime(input[i]) ) { // <-- More on this, later.
prime[p++] = input[i];
}
else {
composite[c++] = input[i];
}
}
Loops
This happens a couple of times, just because the code itself is duplicated (another code smell):
for(i=0;i<p;i++){
// ^^^^^^^^^^^ We want to iterate over [0, p).
printf("%d",prime[p]);
// ^ But this always prints the element one past the end
}
Even if it's just a simple loop, it could be a good idea to write a (testable and reusable) function
void print_arr(size_t n, int arr[n])
{
for (size_t i = 0; i < n; ++i) {
printf("%d ", arr[i]);
} // ^
putchar('\n');
}
// ... Later, in main:
print_arr(p, prime);
print_arr(c, composite);
Primes or composite
I am successful in identifying prime and composite from an array
Well, no. Not with this code, I'm sorry.
if (input[i]%2 != 0) { // Those are ALL the ODD numbers!
prime[p++]=input[i];
}
else if(input[i]>=2 && input[i]%2==0){ // Those are the EVEN numbers greater than 0
composite[c++]=input[i];
}
// What about 0 and the even numbers less than 0?
Not all the odd numbers are prime number (it's a little more complicated than that) and 2 itself is a prime, not a composite.
It's unclear to me if this is a terminology issue or if the snippet is only a placeholder for a proper algorithm. In any case, there are multiple examples of primality test functions in SE sites (I'm quite confident some are posted almost every day).
Overflow risk
See chux - Reinstate Monica's comment:
return a-b; risks overflow when a, b are large int values.
Consider return (a > b) - (a < b); for a full range solution.
Single letter variables names are to be avoided... except for i, j and k used in for() loops only.
You're not updating the index of the arrays c and p as the numbers are being printed out. The arrays are being sorted fine.
In the code below I also remove redundant variables, and rename n to input_count, c to compo_count and p to prime_count.
#include <stdio.h>
#include <stdlib.h>
int compare_Asc(const void *a_void, const void *b_void)
{
int a = *(int *) a_void;
int b = *(int *) b_void;
return a - b;
}
int compare_Desc(const void *a_void, const void *b_void)
{
int a = *(int *) a_void;
int b = *(int *) b_void;
return b - a;
}
int main ()
{
int i = 0;
int input_count = 0;
int prime_count = 0;
int compo_count = 0;
int prime[50];
int composite[50];
int input[50];
printf("How many inputs are you be working with?\nNote: 50 Maximum Inputs\n");
scanf("%d", &input_count);
printf("Enter the %d numbers.\n", input_count);
for (i = 0; i < input_count; i++)
{
scanf("%d", &input[i]);
}
for (i = 0; i < input_count; i++)
{
if (input[i] % 2 != 0)
{
prime[prime_count] = input[i];
prime_count += 1;
}
else if (input[i] >= 2 && input[i] % 2 == 0)
{
composite[compo_count] = input[i];
compo_count += 1;
}
}
printf("Prime Numbers:");
qsort(prime, prime_count, sizeof(int), compare_Asc);
for (i = 0; i < prime_count; i++)
{
printf("%d ", prime[i]); // <<-- HERE, not [p]
}
printf( "\n" );
printf ("Composite Numbers:");
qsort(composite, compo_count, sizeof(int), compare_Desc);
for (i = 0; i < compo_count; i++)
{
printf("%d", composite[i]); // <<-- HERE, not [c]
}
printf( "\n" );
return 0;
}
I have to make an array containing 25 random numbers using a function to define the random numbers but keep getting it to either display only one number at a time (instead of all of them cell by cell) or simply displaying incorrectly i.e. 0. Here is what I have so far.
edit Code changed to correct stupid mistakes I missed rushing, however still unsure how to call funct as I am getting "too few arguments for funct 'get_value', apologies if this seems trivial but I am extremely new to coding thank you for your time.
int get_value (int t);
int main()
{
srand(time(NULL));
int temp[25], n;
for(n=0; n<25; n++)
{temp[n] = rand() %(40)+60;
printf("value of %d at cell %d \n", n, temp[n]);}
return 0;
}
//function get_value()
//needs to return rand # <-> 60 and 100 seed rand
//use rand %40+60 to ensure value is <-> 60 and 100
int get_value (int t)
{
return rand() %(40)+60;
}
You have some syntax errors
for loop should be like this
for(n=0; n<25; n++)
{
temp[n] = get_value(n); //in your prog u have written temp[t], t isnt defined
printf("value at cell %d is %d \n", n, temp[n]);
} // you also missed the braces
You are assigning value to temp[t], but you haven't declared t. In any case, it should be temp[n].
The scope of the variable t is only in your get_value function.
For more information about scopes
//I think here's what you want to do.
#include <stdio.h>
#include <time.h>
int main()
{
srand(time(NULL));
int temp, i, j, h;
int num_array[40];
int i_need_25[25];
//here's how im getting random numbers without repeating a number.
//first, fill the array with numbers between
for(i = 0; i < 41; i++)
{
num_array[i] = i + 60;
}
//then here's how we shuffle it
for(i = 0; i < 41; i++)
{
j = rand() % 41;
temp = num_array[j];
num_array[j] = num_array[i];
num_array[i] = temp;
}
//final process is to print the first 25 elements as you have said you need 25.
for(i = 0; i < 25; i++)
{
printf("%d ", num_array[i]);
}
printf("\n\n");
//or you can also store the first 25 elements on separate array variable.
for(i = 0; i < 25; i++)
{
i_need_25[i] = num_array[i];
printf("%d ", i_need_25[i]);
}
return 0;
}
I'm trying to create a simple application that takes a list of numbers from stdin and sorts them by casting all of the variables into 'semi' sorted lists by taking a simple average of the numbers and casting them into two arrays:
(a[] is <= avg)
(b[] is > avg)
My plan is then to sort my two lists, and then merge them. (I also understand that any optimization that I'm getting through this effort is most likely lost by not keeping it simple).
Here's my code and I'll follow up with two questions below:
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
bool compare(val1,val2)
{
if(val1 > val2){return false;}
else{return true;}
}
int average(char *array[],int count)
{
int total = 0;
for(int i=1;i<count;i++){
int temp = atoi(array[i]);
total = temp+total;
}
int avg = total/(count-1);
return avg;
}
int main(int argc, char *argv[])
{
//produce average for argv array excluding *argv[0]
int avg = average(argv,argc);
for(int i=1; i<argc; i++){
//print unsorted list for debugging
//TODO remove this
printf("%s\n",argv[i]);
}
//setup int arrays (-2 because argc = count +1 & because of average one number will always be > or < average.
int a[argc-2];
int b[argc-2];
//start counters for a=below avg b =above avg
int acount = 0;
int bcount = 0;
//cycle through argv[i] and cast values to new arrays a && b
for(int i=1; i<argc; i++){
//temp variable to avoid excessive atoi()
int temp = atoi(argv[i]);
if(temp <= avg){
a[acount] = temp;
acount++;
}
else{
b[bcount] = temp;
bcount++;
}
//print temp for debugging
//TODO remove this.
printf("%d\n",temp);
}
// sort a
for(int i = 1; i <acount; i++){
int temp;
if(compare(a[i],a[i+1])){}
else{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
printf("\n%d\n",a[i]);
}
return 0;
}
I'm having difficulty with gdb trying to debug my code. I'm trying
to break at printf("\n%d\n",a[i]); and run the following with
these results:
(gdb) b 69
(gdb) r 1 2 3
Breakpoint 1, main (argc=4, argv=0xbffff184) at work.c:69
69 printf("\n%d\n",a[i]);
(gdb) info locals
temp = 2
i = 1
avg = 2
acount = 2
bcount = 1
b = <optimized out>
(gdb) p a[i]
No symbol "a" in current context.
(gdb) p *argv[i]
$1 = 49 '1'
What am I doing wrong here that a[] and b[] aren't storing the values as I'd hoped?
I am new to C so this question may seem a bit stupid :P .
I have an array arr[] which stores numbers from 100 to 999.
Now, I have to take each element of the array and subtract the subsequent digits.
For example if I have a number in that array as 1234 then I need another array that stores 1,2,3,4 distinctly so that I can perform 1-2= -1, 2-3 =-1, 3-4= -1.
So if I change a data like 1234 to char through typecasting then how to store this char into an array and then break it into 1,2,3,4 so that I can call it in a for loop by arr[i].
#include <stdio.h>
#include<string.h>
int main()
{
int t,n,w;
int mod = 1000007;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&w);
int start = 1;
int end = 10;
int i,j,z;
for(i=0;i<=n-2;i++)
{
start = start*10;
end = end*100;
}
end--;
char arr[10000];
for(i= start;i<=end;i++)
{
scanf("%c",&arr[i]);
}
int len = strlen(arr);
int count = 0;
int Value=0;
for(i=0;i<len;i++)
{
char b[10000];
b[0] = arr[i] + '0';
char arr2[10000];
int g = strlen(b);
for(j=0;j<g;j++)
{
strncpy(arr2, b + j, j+1);
}
int k = strlen(arr2);
for(z=0;z<k;z++)
{
int u = arr2[z] - '0';
int V = arr2[z+1] - '0';
if(u>V)
{
Value = Value + (u-V);
}
else
{
Value = Value + (V-u);
}
}
if (Value == w)
{
count++;
}
}
int ans = count % mod;
printf("%d",ans);
}
return 0;
}
Actually its a question from codechef.com called weight of numbers in the easy section of the practice problems
you can split number by digits in this way
int num = 123;
int digits[3];
for (int i = 2; i >= 0; i--)
{
digits[i] = num % 10;
num /= 10;
}
Also if you'll cast num to char that wouldn't help you. You'll just get some character if you try to print it. Nothing more will change.
I'm looking to create a program that creates and stores N random complex numbers. However, it's necessary to use another array (of pointers) which points to every element on the complex array. Then, I have to present it sorted by its norm to the user.
To "sort" it, I just change to where the pointer array is pointing to. Then I just show the "sorted" array of pointers.
But I'm not getting it right. How can I achieve this?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define FORMATLOG "FORMATLOG: invalid parameters: ex3 <N>"
#define RANGE 18 - 6
enum { true, false };
typedef struct {
double real,
imag,
norm;
} Complex;
void generateComplex(int N) {
int i, test;
Complex vector[N];
for(i = 0; i < N; i++) {
vector[i].real = rand() % RANGE;
do { vector[i].imag = rand() % RANGE; } while(vector[i].imag == 0);
vector[i].norm = sqrt(pow(vector[i].real, 2) + pow(vector[i].imag, 2));
}
Complex *p_vect = &vector;
/* makes array point in order */
while(test == false) {
test == true;
for(i = 0; i < N - 1; i++)
if(vector[i].norm > vector[i + 1].norm) {
*p_vect[i] = &vector[i + 1];
*p_vect[i + 1] = &vector[i];
test = false;
}
}
for(i = 0; i < N; i++)
printf("\t%d -| %2g + %2gi | = %g\n", i, vector[i].real,
vector[i].imag,
vector[i].norm);
printf("********************************\n");
for(i = 0; i < N; i++)
printf("\t%d -| %2g + %2gi | = %g\n", i, p_vect[i].real,
p_vect[i].imag,
p_vect[i].norm);
}
int main(int argc, char **argv) {
if(argc != 2) {
puts(FORMATLOG);
return false;
}
srand(time(NULL));
int i, N = atoi(argv[1]);
generateComplex(N);
return true;
}
Complex *p_vect = &vector;
This creates a pointer to the existing array. The requirement is to create an array of pointers, not a pointer to an array.
Complex *p_vect[N];
for (i = 0; i < N; i++) {
p_vect[i] = &vector[i];
}
If you start with this, you can then sort p_vect without touching vector. Your sorting code, when written correctly, will make no mention of vector at all.