I'm starting into C programming and my english is not the best, so I'll try to explain myself the best i can...
I was trying to do a program that generates random numbers, pairs and odd numbers, and saves those numbers into two different vectors...
So it looks like this
#include <stdio.h>
#include <stdlib.h>
#define ARRAYSIZE 6
void main()
{
int randomNumber, position, pairVector[ARRAYSIZE], oddVector[ARRAYSIZE];
srand(time(NULL));
for (position = 0; position < ARRAYSIZE; position++)
{
randomNumber = rand() % 49 + 0;
if (randomNumber % 2 == 0)
pairVector[position] = randomNumber;
else
oddVector[position] = randomNumber;
}
// Loop to print all the pair random numbers
for (position = 0; position < ARRAYSIZE; position++)
{
if(pairVector[position] >= 0)
printf("%d ", pairVector[position]);
}
// Separation of the pair and odd numbers
printf("\n\n\n");
// Loop to print all the odd random numbers
for (position = 0; position < ARRAYSIZE; position++)
{
if (oddVector[position] >= 0)
printf("%d ", oddVector[position]);
}
}
As u can see, I have 2 loops to print pairs and odd numbers, this numbers are printed with 2 loops, so here goes my question...
Without the condition >= 0 in the vector inside the loop, I got printed some memory directions (because if I have a size of 6 ints but only 3 numbers (pair or odd), the other 3 directions are printed too)... What can I do to remove those directions from the printed vector without the condition? Maybe pointers?
Thanks in advice and sorry for my bad english.
You can set the both arrays elements at 0
for(position = 0; position < ARRAYSIZE; position++)
pairVector[position] = 0;
do it for the both arrays and your arrays will be filled with 0 (zeroes), next fill up your arrays with rand numbers, so you will have something like
example: 24, 22, 58, 0, 0, 0
when you want to printout array, just go something like
for(position = 0; position < ARRAYSIZE; position++)
{
if(pairVector[position] != 0)
printf("%d ", pairVector[position]);
}
Due to the fact that you don't know when the arrays are gonna be filled completely, I suggest you to do a while loop until the both arrays are filled.
void main()
{
int randomNumber, position, pairVector[ARRAYSIZE], oddVector[ARRAYSIZE];
srand(time(NULL));
int pairIndex, oddIndex;
pairIndex = oddIndex = 0; // you will increment them once you find a number for regarding array
while ((pairIndex < ARRAYSIZE) || (oddIndex < ARRAYSIZE) )
{
randomNumber = rand() % 49 + 0;
if (randomNumber % 2 == 0){
if (pairIndex<ARRAYSIZE)
pairVector[pairIndex++] = randomNumber;
}
else{
if (oddIndex<ARRAYSIZE)
oddVector[oddIndex++] = randomNumber;
}
}
// Loop to print all the pair random numbers
for (position = 0; position < ARRAYSIZE; position++)
{
if(pairVector[position] >= 0)
printf("%d ", pairVector[position]);
}
// Separation of the pair and odd numbers
printf("\n\n\n");
// Loop to print all the odd random numbers
for (position = 0; position < ARRAYSIZE; position++)
{
if (oddVector[position] >= 0)
printf("%d ", oddVector[position]);
}
}
In your approach the loop went through only 6 times and for sure one or both arrays could be incomplete. In the solution above you will fill both arrays and then you print them.
Related
Taking a sequence of (non-empty) integers the program should first request the number of integers to read and dynamically allocate an array large enough to hold the number of values you read. You should then loop in the elements of the array. Then, your program must use malloc() to dynamically allocate two arrays, one to hold all the even numbers in the array you just read, and one to hold the odd numbers in the array. You must allocate just enough space for each array to hold odd and even numbers.
That is my test case
Please enter the number of times you want to enter the temperature:
4
Please enter the numbers:
21
40
31
50
odds are: 21
odds are: 0
evens are: 0
evens are: 40
This is my code:
#include <stdio.h>
#include<stdlib.h> // for malloc
int main(void) {
int counts = 0; // set a variable named counts recored how many of the times
printf("Please enter the number of times you want to enter the temperature: \n");
scanf("%d",&counts);
int *odd_evens;
odd_evens = malloc(sizeof(int)*(counts));
printf("Please enter the numberss: \n");
for (int i = 0; i < counts; i++) { // use for loop to read temperature
scanf("%d",&odd_evens[i]); // record the temperature
}
int odds_number = 0; // calcuate how many numbers are odds
int evens_number = 0; // calcuate how many numbers are evens
for (int i = 0; i < counts; i++) {
if (odd_evens[i] %2 == 0) {
odds_number++; // odds add one
}
else if (odd_evens[i] %2 != 0) {
evens_number++; // evens add one
}
}
int *odds;
odds = malloc(sizeof(int)*(odds_number)); // create dunamic array for odds
int *evens;
evens = malloc(sizeof(int)*(evens_number)); // create dunamic array for evens
for (int j = 0; j < counts; j++) {
if (odd_evens[j] % 2 == 0) {
evens[j] = odd_evens[j];
}
else if (odd_evens[j] % 2 != 0) {
odds[j] = odd_evens[j];
}
}
for(int m = 0; m < odds_number; m++) {
printf("odds are: %d\n",odds[m]);
}
for (int n = 0; n < odds_number; n++) {
printf("evens are: %d\n",evens[n]);
}
free(odd_evens);
free(odds);
free(evens);
return 0;
}
In my limited coding experience, this usually happens with invalid subscripts, but in my test code, the odd numbers are of length 2 and the even numbers are of length 2. The array range should be correct. Why does this happen?
One major problem is this loop:
for (int j = 0; j < counts; j++) {
if (odd_evens[j] % 2 == 0) {
evens[j] = odd_evens[j];
}
else if (odd_evens[j] % 2 != 0) {
odds[j] = odd_evens[j];
}
}
Here you will go out of bounds of both evens and odds (leading to undefined behavior) since you use the index for odd_evens which most likely will be larger (unless all input is only odd, or only even).
You need to keep separate indexes for evens and odds:
unsigned evens_index = 0;
unsigned odds_index = 0;
for (int j = 0; j < counts; j++) {
if (odd_evens[j] % 2 == 0) {
evens[evens_index++] = odd_evens[j];
}
else if (odd_evens[j] % 2 != 0) {
odds[odds_index++] = odd_evens[j];
}
}
Another problem is the printing of the even numbers:
for (int n = 0; n < odds_number; n++) {
printf("evens are: %d\n",evens[n]);
}
Here you use the odds_number size instead of evens_number.
I'm a bit stuck on one of my problems not because I don't know, but because I can't use more complex operations.(functions and multiple arrays)
So I need to make a program in C that ask for an input of an array(max 100 elements) and then program needs to sort that matrix by numbers with same digits.
So I made everything that I know, I tested my program with sorting algorithm from minimum to maximum values and it works, only thing that I can't understand is how should I test if the number have same digits inside the loop? (I can't use functions.)
So I know the method of finding if the number have the same digits but I don't know how to compare them. Here is an example of what I need.
This is what I have for now this sorts numbers from min to max.
#include <stdio.h>
int main() {
int matrix[100];
int i,j;
int temp,min;
int elements_number=0;
printf("Enter the values of matrix-max 100 elements-type -1 to end: ");
for(i=0;i<100;i++){
scanf("%d",&matrix[i]);
elements_number++;
if(matrix[i]==-1){
elements_number--;
break;
}
}
for (i=0; i<elements_number; i++) {
min=i;
for (j=i+1; j<elements_number; j++) {
if (matrix[j] < matrix[min])
min = j;
}
temp = matrix[i];
matrix[i] = matrix[min];
matrix[min] = temp;
}
for(i=0;i<elements_number;i++){
if(i!=elements_number-1){
printf("%d,",matrix[i]); }
else printf("%d.",matrix[i]);
}
return 0;
}
I need this output for these numbers:
INPUT :
1 22 43 444 51 16 7 8888 90 11 -1
OUTPUT:
1,22,444,7,8888,11,43,51,16,90.
Integers with 1 digit count as "numbers with same number of digits" like 7 and 1 in this example.
Hope that you can help.
After processing the array, the single-digit numbers should all be in the left part of the array, the other numbers in the right part. Within each part, the original order of the elements should be preserved. This is called a stable partition. It is different from sorting, because the elements are only classified into two groups. Sorting means that there is a clear relationship between any two elements in the array.
This can be done by "filtering" the array for single-digit numbers and storing the other numbers that were filtered out in a temporary second array. Then append the contents of that second array to the (now shorter) first array.
Here's how that could work:
#include <stdlib.h>
#include <stdio.h>
void print(const int *arr, int n)
{
for (int i = 0; i < 10; i++) {
if (i) printf(", ");
printf("%d", arr[i]);
}
puts(".");
}
int is_rep_digit(int n)
{
int q = n % 10;
n /= 10;
while (n) {
if (n % 10 != q) return 0;
n /= 10;
}
return 1;
}
int main()
{
int arr[10] = {1, 22, 43, 444, 51, 16, 7, 8888, 90, 11};
int aux[10]; // auxliary array for numbers with several digits
int i, j, k;
print(arr, 10);
j = 0; // number of single-digit numbers
k = 0; // number of other numbers
for (i = 0; i < 10; i++) {
if (is_rep_digit(arr[i])) {
arr[j++] = arr[i]; // pick single-digit number
} else {
aux[k++] = arr[i]; // copy other numbers to aux
}
}
k = 0;
while (j < 10) { // copy aux to end of array
arr[j++] = aux[k++];
}
print(arr, 10);
return 0;
}
Edit: I've just seen your requirement that you can't use functions. You could use Barmar's suggestion to test divisibility by 1, 11, 111 and so on. The tricky part is to find the correct divisor, however.
Anyway, the point I wanted to make here is that you don't need a full sorting algorithm here.
try to input 20 numbers with array and to output
the numbers in the double location only but somehow it's print
also the 0 location... please help.
#include<stdio.h>
#define n 20
int main()
{
int num[n]={0},i=0,order=1,double_locaion=0;
for(i=0;i<n;i++)
{
printf("please enter %d number\n",order);
scanf("%d",&num[i]);
order++;
}
for(i=0;i<n;i++)
{
if (i%2==0 && i!=1 && i!=0)
{
printf("%d\n",num[i]);
}
}
}
Try this, start with 2 and increase by 2 every time, the you don't have to deal with 0th element and odd element.
for (i = 2; i < n; i += 2)
{
printf("%d\n",num[i]);
}
First of all there is no way that your code is printing the 0-th location of the array. That's impossible given the condition of the if statement.
Secondly n- you don;t need to use macro expansion for that name.
/* This program takes 20 integer number from input.
* Prints the numbers entered in odd positions.(First,Third,..etc).
*/
#include<stdio.h>
#include<stdlib.h>
#define NUM 20
int main(void)
{
int numArr[NUM];
for(size_t i = 0; i < NUM; i++) {
printf("please enter %zu number\n",i+1);
if( scanf("%d",&numArr[i]) != 1){
fprintf(stderr, "%s\n","Error in input" );
exit(1);
}
}
for(size_t i = 0; i < n; i++)
{
if( i%2 == 0 )// if you want to omit the first number put the
// the condition (i%2 == 0 && i)
{
printf("%d\n",numArr[i]);
}
}
return 0;
}
What you did wrong that your code skipped 0th element?
if (i%2==0 && i!=1 && i!=0)
^^^^
i when 0 makes this condition false - and you never get to print it.
i!=1 ?
If i=1 then i%2 will be 1, so you will not even check the second conditions, the whole conditional expression will become false. So you can safely omit this logic.
Is there a better way?
Sure,
for(size_t i = 0; i < n; i += 2){
printf("%d\n",num[i]);
}
Explanation
If you consider that every time you check the modular arithmetic of 2 the elements which results to 0 remained are
0,2,4,6,8,10,...18
See the pattern? Starts with 0 and increments by 2 each time and when does it stop? Yes before reaching 20 coding it we get
for(size_t i = 0; i < n; i += 2){
/* Initialize with i=0 as first number is 0 (i=0)
* Increments by 2 (i+=2)
* Runs when less than 20 (i<n)
*/
printf("%d\n",num[i]);
}
If you want to omit the 0-th index do initialize properly
for(size_t i = 2; i < n; i += 2){
If you mean you want the numbers from array that are present at even position than you can do like this:
for (i = 2; i < n; i=i + 2) //Initialize i = 0 if 0 is consider as even
{
printf("%d\n",arr[i]);
}
I above code i is initialized to 2 and the increment in each iteration is 2 so it will access elements only at even position (2,4,6...).
My objective for this program is to let the user determine the size of the array and dynamically allocate memory for whatever size they choose. Once the user defines the size of the array, random numbers that do no exceed the size of the array are placed into all of the allotted positions. Where I am having issues is removing duplicates from the array and replacing them with a value that is not being used,
Example:
Please enter the size of the array:
User Input: 5
Output of code: 5, 3, 3, 1, 2
I would need it to be something like this:
Please enter the size of the array:
User Input: 3
Output of program: 3, 1, 2
Currently reading "C Programming - A Modern Approach" by K.N. King (Second Edition).
if someone could point me in the right direction on how to approach this, it would be much appreciated.Here is my code thus far.
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
typedef int bool;
int main() {
int *UserData;
int TempPost;
int replace;
int UserInput;
int i;
int result;
bool digit_seen[UserInput];
int digit;
srand ((unsigned) time(NULL));
printf("Please enter the size of the array using a whole number: \n");
scanf("%d", &UserInput);
UserData = malloc(sizeof(int) * (UserInput ) +1);
for(i=0; i < UserInput; i ++) {
result = (( rand() % UserInput) + 1);
}
// check for duplicate values while putting values in array
while(UserInput>0){
digit = UserInput % UserInput;
if(digit_seen[digit])
break;
digit_seen[digit] = true;
UserInput /= UserInput;
if(UserInput > 0)
printf("Repeated digit \n");
else
printf("No repeated digit \n");
}
// Sorting the array using a Bubble sort
while(1){
replace = 0;
for (i=0; i<(UserInput - 1); i++){
if(UserData[i]>UserData[i+1]){
TempPost = UserData[i];
UserData[i] = UserData[i+1];
UserData[i+1] = TempPost;
replace = 1;
}
}
if(replace==0){
break;
}
}
printf("%d \n", result);
return 0;
}
It's not the most efficient way, but you can do it as you're generating the random numbers. When you pick a random number, go through all the previous elements of the array and see if it's already been used. Keep looping until you pick an unused number.
for (i = 0; i < UserInput; i++) {
do {
result = ( rand() % UserInput) + 1;
} while (in_array(result, UserData, i-1));
UserData[i] = result;
}
int in_array(int val, int* array, int array_size) {
for (int i = 0; i < array_size; i++) {
if (array[i] == val) {
return 1;
}
}
return 0;
}
A slightly more efficient way to do it is to initialize the array to 0. Then instead of picking random numbers, pick a random index to fill in, and repeat this until you pick an index that contains 0.
UserData = calloc(UserInput, sizeof(int));
for (i = 1; i <= UserInput; i++) {
int index;
do {
index = rand() % UserInput;
} while (UserData[index] != 0)
UserData[index] = i;
}
What you can do is shuffle the array instead. Just fill the array with all the numbers in order using a simple for loop, then shuffle it with something like this:
//read user input
//create array and fill with all the numbers in order
//[0,1,2,3,4,5 .. ... ]
int index, temp;
// size is the size of the array
for(int i = 0; i < size; i++)
{
index = rand()%size;//random place to pick from
temp = array[i];
array[i] = array[index];
array[index] = temp;
}
This is a lot more effecient -and less error prone- than your current approach.
I'm trying to populate a 20x20 matrix where each entry is of structure type. My goal is to randomly assign 100 ants and 5 doodlebugs on this 2D array. Even though I got it to work, I don't always get the amount of ants or doodlebugs I need in the matrix. I added a counting function to always verify how many of them I have each time I run the program, but I'm always slightly short. I'm trying to force those number to work (100 ants and 5 doodlebugs) by using a do/while loop in my populating function, although it's not working. Can someone spot where is my logic is failing me?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#define N 20
struct cellState {
int emptyInt;
int antInt;
int dBInt;
char emptyChar;
char antChar;
char dBChar;
};
struct cellState gridState[N][N];
// function to populate world
void pop_mtx(struct cellState gridState[N][N], int antsNeeded, int dBNeeded) {
int i, j;
do {
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if ((gridState[i][j].emptyInt = rand() % 3) == 0) {
gridState[i][j].emptyChar = '.';
} else
if (((gridState[i][j].antInt = rand() % 3 == 1) && antsNeeded != 0)) {
gridState[i][j].antChar = 'a';
antsNeeded--;
} else
if (((gridState[i][j].dBInt = rand() % 3 == 2) && dBNeeded != 0)) {
gridState[i][j].dBChar = 'D';
dBNeeded--;
}
}
}
} while (dBNeeded != 0 && antsNeeded != 0);
}
//function to display current state of the world
void display_mtx(struct cellState gridState[N][N]) {
int i, j;
char charToDisplay;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (gridState[i][j].antChar == 'a')
charToDisplay = 'a';
else
if (gridState[i][j].dBChar == 'D')
charToDisplay = 'D';
else
charToDisplay = '.';
printf("%c ", charToDisplay);
}
printf("\n");
}
printf("\n\n");
}
//function to count ants and doodlebugs
void count_mtx(struct cellState gridState[N][N]) {
int i, j, antCount = 0, dBcount = 0;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (gridState[i][j].antChar == 'a')
antCount++;
else
if (gridState[i][j].dBChar == 'D')
dBcount++;
}
}
printf("ant count: %i, doodlebug count: %i\n", antCount, dBcount);
}
int main(void) {
srand((unsigned int)time(NULL));
//populate grid state with 5 doodlebugs and 100 ants
int antsNeeded = 100, dBNeeded = 5;
pop_mtx(gridState, antsNeeded, dBNeeded);
count_mtx(gridState);
display_mtx(gridState);
}
There are several problems. First, each time you call rand() you obtain a different value, so it is possible that none of the three tests pass. You should call rand () once and save the value.
Second, there is nothing that guarantees that over NxN calls of rand() you will get as many ones and twos as you need. The outer loop is therefore necessary. You should also preserve already populated squares from one iteration to the next because it might take a long time before you reach an iteration that produces enough ones and twos.
Third, this method is biased toward the squares at the beginning of the grid. It will not give you one out of all possible distributions of 100 ants and 5 doodlebugs over 400 squares with equal probability.
Here is the proper way to do it:
Consider the grid as a uni-dimensional array. First fill it, in order, with 100 ants, 5 doodlebugs, and empty spaces. Then perform a random shuffle of the array.
This procedure will return each possible distribution of the ants and doodlebugs on the grid with equal probability.