I need to input 20 numbers and to output only double location - c

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...).

Related

The wrong data is displayed in the output on c

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.

Finding substring, but not for all inputs?

I wrote a code to find the index of the largest substring in a larger string.
A substring is found when there is an equal amount of a's and b's.
For example, giving 12 and bbbbabaababb should give 2 9, since the first appearing substring starts at index 0 and ends at index 9. 3 10 is also an answer, but since this is not the first appearing substring, this will not be the answer.
The code I made is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
void substr(char str[], int n) {
int sum = 0;
int max = -1, start;
for (int i = 0; i < n; i++) {
if (str[i]=='a') {
str[i] = 0;
} else if(str[i]=='b') {
str[i] = 1;
}
}
// starting point i
for (int i = 0; i < n - 1; i++) {
sum = (str[i] == 0) ? -1 : 1;
// all subarrays from i
for (int j = i + 1; j < n; j++) {
(str[j] == 0) ? (sum += -1) : (sum += 1);
// sum == 0
if (sum == 0 && max < j - i + 1 && n%2==0) {
max = j - i + 1;
start = i-1;
} else if (sum == 0 && max < j - i + 1 && n%2!=0) {
max = j - i + 1;
start = i;
}
}
}
// no subarray
if (max == -1) {
printf("No such subarray\n");
} else {
printf("%d %d\n", start, (start + max - 1));
}
}
/* driver code */
int main(int argc, char* v[]) {
int n; // stores the length of the input
int i = 0; // used as counter
scanf("%d", &n);
n += 1; // deals with the /0 at the end of a str
char str[n]; // stores the total
/* adding new numbers */
while(i < n) {
char new;
scanf("%c", &new);
str[i] = new;
++i;
}
substr(str, n);
return 0;
}
It works for a lot of values, but not for the second example (given below). It should output 2 9 but gives 3 10. This is a valid substring, but not the first one...
Example inputs and outputs should be:
Input Input Input
5 12 5
baababb bbbbabaababb bbbbb
Output Output Output
0 5 2 9 No such subarray
You have several problems, many of them to do with arrays sizes and indices.
When you read in the array, you want n characters. You then increase n in oder to accomodate the null terminator. It is a good idea to null-terminate the string, but the '\0' at the end is really not part of the string data. Instead, adjust the array size when you create the array and place the null terminator explicitly:
char str[n + 1];
// scan n characters
str[n] = '\0';
In C (and other languages), ranges are defined by an inclusive lower bound, but by an exclusive upper bound: [lo, hi). The upper bound hi is not part of the range and there are hi - lo elements in the range. (Arrays with n elements are a special case, where the valid range is [0, n).) You should embrace rather than fight this convention. If your output should be different, amend the output, not the representation in your program.
(And notw how your first example, where you are supposed to have a string of five characters actually reads and considers the b in the 6th position. That's a clear error.)
The position of the maximum valid substring does not depend on whether the overall string length is odd or even!
The first pass, where you convert all "a"s and "b"s to 0's and 1's is unnecessary and it destroys the original string. That's not a big problem here, but keep that in mind.
The actual problem is how you try to find the substrings. Your idea to add 1 for an "a" and subtract one for a "b" is good, but you don't keep your sums correctly. For each possible starting point i, you scan the rest of the string and look for a zero sum. That will only work, if you reset the sum to zero for each i.
void substr(char str[], int n)
{
int max = 0;
int start = -1;
for (int i = 0; i + max < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += (str[j] == 'a') ? -1 : 1;
if (sum == 0 && max < j - i) {
max = j - i;
start = i;
}
}
}
if (max == 0) {
printf("No such subarray\n");
} else {
printf("%d %d\n", start, start + max);
}
}
Why initialize max = 0 instead of -1? Because you add +1/−1 as first thing, your check can never find a substring of max == 0, but there's a possibility of optimization: If you have already found a long substring, there's no need to look at the "tail" of your string: The loop condition i + max < n will cut the search short.
(There's another reason: Usually, sizes and indices are represented by unsigned types, e.g. size_t. If you use 0 as initial value, your code will work for unsigned types.)
The algorithm isn't the most efficient for large arrays, but it should work.

How to remove memory directions from an empty vector

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.

Custom iteration through array in C printing every nth value

I'm currently working on a homework assignment and what I have to do is ask for the size of the array and what I would like to loop through it (how many things I should skip through). Example (I bolded what would be the users response)
How large is the array?
10
How would you like to iterate through it?
3
Conditions:
Then it should loop through every third item and then start over looping through the items that haven't been picked until the last one. I must also start on the first item (0) which you can see in my code that I provided.
This is what I thought I could do...
int amount=0, often=0, counter=0, x;
printf("Size of Array? ");
scanf("%d", &amount);
printf("iteration size? ");
scanf("%d", &often);
// sets the array (1 means it exists)
int[] array[amount];
for(x=0; x<amount; x++)
array[x] = 1;
// the part that I'm confused on
// supposed to iterate through everything
for(x=0; x<amount; x++){
if(array[0] == 1){
printf("#0\n");
array[0]=0;
}
if(array[x]==1)
counter++;
if(counter == often){
printf("#%d\n", x);
array[x]=0;
counter=0;
}
return 0;
}
However, I need to continuously loop through until the entire array is done except for the last one. Mine stops after I loop through the array once. This is the output I have verse the output I want.
My output:
0
3
6
9
Wanted output:
0
3
6
9
4
8
5
2
7
Notice how the the wanted output loops through it again picking the third number that hasn't been picked yet. That is where I'm confused and how to fix this problem. Any guidance or information would be great, thanks.
You need to keep looping until all numbers have been printed,
for instance like this:
int total = amount;
counter = often - 1;
while (total > 0) {
for(x=0; x<amount; x++){
if(array[x]==1)
counter++;
if(counter == often){
printf("#%d\n", x);
array[x]=0;
counter=0;
total--;
}
}
}
Edit: The entire program:
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int amount=0, often=0, counter=0, x;
printf("Size of Array? ");
scanf("%d", &amount);
printf("iteration size? ");
scanf("%d", &often);
// sets the array (1 means it exists)
int array[amount]; // Fixed typo in declaration
for(x=0; x<amount; x++)
array[x] = 1;
// the part that I'm confused on
// supposed to iterate through everything
int total = amount;
counter = often - 1;
while (total > 0) {
for(x=0; x<amount; x++){
if(array[x]==1)
counter++;
if(counter == often){
printf("#%d\n", x);
array[x]=0;
counter=0;
total--;
}
}
}
return 0;
}
Compilation:
gcc -std=c99 -Wall a.c -o a
Running the program:
Size of Array? 10
iteration size? 3
#0
#3
#6
#9
#4
#8
#5
#2
#7
#1
Let's start out with a loop which skips every three numbers:
for(int i = 0; i < amount; i += 3)
{
print(i);
array[i] = 0;
}
Now, this only seems to work for 0, 3, 6, 9.
We want to be able to start at the first existing value, and repeat this process until nothing remains.
So let's put another loop on the outside, to count how many items remain:
int total = amount;
while(total > 0)
{
for(int i = 0; i < amount; i += 3)
{
print(i);
array[i] = 0;
total--;
}
}
Good so far, but we still start at 0 every time. We want to start at a particular value, and skip until the 3rd number is reached.
int total = amount;
while(total > 0)
{
for(int i = getStartingIndex(array, 3); i < amount; i += 3)
{
while(array[i] == 0 && i < amount)
i++;
print(i);
array[i] = 0;
total--;
}
}
Let's define our getStartingIndex function:
int getStartingIndex(int array[], int skipCount)
{
int index = 0;
for(int i = 0; i < skipCount; i++)
{
while(array[index] == 0)
index++;
index++;
}
return index - 1;
}
Now, we start at the value specified, and print numbers until we reach amount. And then we go back to the beginning, but we start at the third unused number.
We need to keep the current step size, it will run from zero to the desired step size and each time we visit an index and mark it as visited we will reset that counter to zero. Our main loop will iterate over the array one by one, until there are no unvisited indices left. We make sure the index does not run out of bounds of the array, so when index hits the length of the array, we reset it to zero.
If you don't want the last element to be printed, just change the while loop's conditional to while (visited_count < total_length - 1)
int main() {
int array[10] = { 0 };
int total_length = 10;
int visited_count = 0;
int index = 0;
int step_size = 3;
int current_step = 3;
while (visited_count != total_length) /* while there are unvisited elements */
{
if (!array[index] && current_step == step_size) /* array[index] has value zero, and we are at the desired step count, so print that element and mark it as visited */
{
array[index] = 1;
visited_count++;
printf("%d\n", index);
current_step = 0; /* resetting the step counter */
}
index++; /* this is how we iterate over the array, incrementing it at each iteration */
if (index == total_length) /* checking for out-of-bounds of the array, if we hit the total length, the index should be reset. */
{
index = 0;
}
if (!array[index]) /* now that we have stepped through the array, we increment the step counter if that element is not visited. */
{
current_step++;
}
}
return 0;
}

assigning and printing from 2d arrays C

/*
Program to calculate trip and plan flights
*/
#define TRIP 6
#define DEST 1
#include <stdio.h>
int main(void)
{
int type_num, cont_num, index, i, dest_code, trip_num, row, col;
int travelint[TRIP][DEST]= {{0}};
printf("Please enter the number of trips:");
scanf("%d", &trip_num);
for (i=0; i < trip_num ; i++)
{
printf("Please enter destination code:");
scanf("%d", &dest_code);
cont_num = dest_code / 10000;
type_num = dest_code/1000 - cont_num*10;
if ( (cont_num <= 7) && (cont_num > 0) && (type_num <= 5) && (type_num >=0) )
dest_code = travelint[i][0];
else
printf("Invalid code\n");
}
printf("%2d", travelint[0][0]);
return 0;
}
I'm having trouble printing from the array I'm not sure if I'm either printing it wrong or that the number isn't actually being assign in the array. I'm still having trouble with the concept of assign values from input into the array..
An array dimension with only one element in the row is a trifle pointless. You normally only use dimensions with more than one element in each row.
Additionally, you are never assigning to the travelint array - only reading from it. So, since it is initialized to all zeroes, all you will ever see when you print it are zeroes.
You probably simply need to change this:
if ( (cont_num <= 7) && (cont_num > 0) && (type_num <= 5) && (type_num >=0) )
dest_code = travelint[i][0];
to:
if ( (cont_num <= 7) && (cont_num > 0) && (type_num <= 5) && (type_num >=0) )
travelint[i][0] = dest_code;
This assigns to travelint.
To print out a full 2D array, you would normally use:
for (int j = 0; j < TRIP; j++)
{
for (int k = 0; k < DEST; k++)
printf("Trip[%d][%d] = %d\n", j, k, travelint[j][k]);
}
Given that the inner loop will be executed just once per iteration of the outer loop (in your example, where DEST is 1), you could simplify that to:
for (int j = 0; j < TRIP; j++)
{
printf("Trip[%d][%d] = %d\n", j, 0, travelint[j][0]);
}
You should validate the trip_num after the user enters it. You should check that scanf() actually converted a value; if the user types 'A', then your program will go into a rapid loop printing out "Invalid code" every time. Always check that inputs succeed. In theory, you should also check that outputs succeed, but that rule is more often ignored than honoured. Also, if the user is nasty and types 200, then your program is not going to be happy after the user enters the sixth trip destination. It should be between 0 and TRIP (inclusive), of course. You should handle the degenerate (0) case properly, of course. And the printing loop becomes:
for (int j = 0; j < trip_num; j++)
{
printf("Trip[%d][%d] = %d\n", j, 0, travelint[j][0]);
}

Resources