Beginner to Arrays - c

//This is the example
#include <stdio.h>
#define SIZE 10
int main() {
int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
int i, j;
printf("%s%13s%17s\n", "Element", "Value", "Histogram");//This part here is what is unlcear to me
for (i = 0; i < SIZE; ++i) {
printf( "%7d%13d ", i, n[ i ]);
for ( j = 1; j <= n[ i ]; j++ )
printf( "%c",'*' );
printf( "\n" );
}
return 0;
}
I am new to arrays and i've seen this example where it's suppoesd to create a histogram of stars and i've stumbled on that Printf and i have no clue why is it there and what are the numbers after the % do

Those numbers are there to create spacing. If you try printf("%s%s%s\n", "Element", "Value", "Histogram") instead, the output becomes `ElementValueHistogram. Basically the spacing just says that the second string should take up 13 characters worth of space, even if there aren't 13 characters. The way that C formats these strings, the empty space is at the beginning.

The numbers next to % determine the number of characters it can take.
So for example, printf("%s%s%s","Element","Value","Histogram") would output "ElementValueHistogram"
While, printf("%s%10s%10s","Element","Value","Histogram") would output "Element Value Histogram"
So Value has 5 letters, with %10s it would print "_____Value". Same with Histogram with 9 letters, with %10s it would print "_Histogram". Where the underscores represent the spaces.
Normally, C would print empty characters to fill in the spaces.

Related

Sorting out Array of several integers, numbers in array seems to have shifted by 1

I'm trying to solve a question to find the lowest and highest numbers in an array in C Language. I tried swapping the numbers that are close to each other to align the numbers from small(left) to big(right).
For example, if the array is 20, 10, 35, 30, 7, first compare 20 and 10, if 20 is larger than 10, swap the numbers to 10, 20. then compare 20 and 35, 20 is smaller than 35, so go on. then compare 35 and 30, 35 is bigger than 30, swap numbers to 30, 35. then compare 35 and 7, 35 is bigger than 7, swap numbers to 7, 35.
Did these 'swappings' again 3 more times to align the numbers perfectly.
After I've done the swappings, I just printed the first array number and the last array number, but the numbers aren't correct, and it looks like the numbers have shifted by 1. For example, if I align the above array, it is 7[0], 10[1], 20[2], 30[3], 35[4]. (marked the indices by []) So, when I print the indice[0], and indice[4], I expected the numbers to show 7 and 35.
But in fact I have to print indice[1], and indice[5] to get the numbers 7 and 35 to be printed. The numbers seem to have shifted by 1..
I really want to know why the numbers have shifted by 1 in the array.
Thank you for reviewing the question.
I'll also post the original question that I'm trying to solve.
"Q. Input the number N first to decide how much numbers to enter, then input the N-numbers. Print the lowest and highest number in the N-numbers you have input."
And here's my code:
#include<stdio.h>
#pragma warning(disable:4996)
int main(void)
{
int input, i, j, temp, k;
int value[100] = { 0 };
scanf("%d", &input);
for (i = 0; i < input; i++)
{
scanf("%d", &value[i]);
}
for (k = 0; k < input; k++)
{
for (j = 0; j < input; j++)
{
if (value[j] > value[j + 1])
{
temp = value[j + 1];
value[j + 1] = value[j];
value[j] = temp;
}
}
}
printf("%d %d\n", value[0], value[input-1]);
return 0;
}
Because you're iterating over the whole array, value[j+1] walks off the end of the user's input. Since value was initialized 0 to, temp = value[j + 1] will be 0. So 0 will always be your min (unless the user enters negatives).
Instead, iterate only up to j < input - 1.
I'm trying to solve a question to find the lowest and highest numbers in an array in C Language.
You don't need to sort the array, you can do this in a single pass.
// Initialize min and max to be the first value.
int min = value[0];
int max = value[0];
// Then loop through the rest of the array checking if each value is
// smaller than min and/or larger than max.
for (i = 1; i < input; i++) {
if( value[i] < min ) {
min = value[i];
}
if( value[i] > max ) {
max = value[i];
}
}
printf("min: %d, max: %d\n", min, max);
Note: It's not necessary to declare all your variables up front. You can declare them as you need them. And you don't need different iterators for each loop, you can reuse i as I have above.

How to make a series that adds up by 5 every 5 counts using for loop?

I'm kind of new in C programming and I'm trying to make a program that prints the nth term of a series and every 5 counts, it adds up by 5.
Example: 1, 2, 3, 4, 9, 10, 11, 12, 17, 18, 19, 20, 25......
Here is my code
int num,digit,count = 1;
printf("Enter n: ");
scanf("%d", &num);
for(int i=1; i<=num; i++){
count++;
if(count > 5){
count = 0;
i+=4;
}
printf("%d ",i);
}
My code doesn't get to the specific nth term that I'm asking for. For example, I've inputted 10 and it only shows up until the 6th term
The thing to do is get clear in your head what you want to do and how you are going to do it. Rather than tinkering with code, break things down into simple parts and make them clear.
#include <stdio.h>
int main(void)
{
int num = 10;
// Method 1: Spell everything out.
// i counts number of terms printed.
// j counts number of terms since last multiple of four terms.
// k is current term.
for (
int i = 0, j = 0, k = 1; // Initialize all counters.
i < num; // Continue until num terms are printed.
++i) // Update count.
{
printf("%d ", k); // Print current term.
++j; // Increment four-beat count.
if (4 <= j)
{
// Every fourth term, reset j and increment the term by 5.
j = 0;
k += 5;
}
else
// Otherwise, increment the term by 1.
k += 1;
}
printf("\n");
// Method 2: Use one counter and calculate term.
// Iterate i to print num terms.
for (int i = 0; i < num; ++i)
/* Break the loop count into two parts: the number of groups of 4
(i/4) and a subcount within each group (i%4). Looking at the
starts of each group (1, 9, 17, 25...), we see each is eight
greater than the previous one. So we multiply the group number by
8 to get the right offsets for them. Within each group, the term
increments by 1, so we use i%4 directly (effectively multiplied by
1). Then (i/4)*8 + i%4 would start us at 0 for i=0, but we want to
start at 1, so we add 1.
*/
printf("%d ", (i/4)*8 + i%4 + 1);
printf("\n");
}
You shall not change the variable i within the body of the for loop.
You need to introduce one more variable that will store the current outputted number.
Here is a demonstration program.
#include <stdio.h>
int main(void)
{
unsigned int n = 0;
printf( "Enter n: " );
scanf( "%u", &n );
for ( unsigned int i = 0, value = 0, count = 1; i < n; i++ )
{
if ( count == 5 )
{
value += 5;
count = 1;
}
else
{
++value;
}
printf( "%u ", value );
++count;
}
}
The program output is
Enter n: 13
1 2 3 4 9 10 11 12 17 18 19 20 25
Here's another take that I think is a bit less complicated, with explanations in the comments:
#include <stdio.h>
int main(void)
{
int num, count = 1;
num = 20;
// if you look closely, you actually have an initial condition before the
// main pattern starts. Once the pattern starts, its actually every _fourth_
// term that gets added by 5. You'll make things easier on yourself if you
// print out this initial condition, then handle the pattern in the loop.
// If you really want to be correct, you can wrap this in a if (num > 0) check
printf("%d ", count++);
// start at 1, because we already printed the first item
for(int i=1; i<num; i++, count++)
{
// now we can focus on every fourth term
if (i % 4 == 0)
{
// if it's the fourth one, add 5 to the previous value
// Of course this simplifies to count += 4
count = (count-1) + 5;
}
printf("%d ",count);
}
}
Demonstration

Initializing an array in c with same numbers leads to different values [duplicate]

This question already has answers here:
C++ int with preceding 0 changes entire value
(4 answers)
Closed 5 years ago.
#include <stdio.h>
int main () {
int n[ 10 ] = {002535}; /* n is an array of 10 integers */
int j;
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
The above code runs and returns the first element to be equal to 1373. Could you explain this? I am not able to understand the reason behind the number being changed due to padding in the integer provided.
Output comes out to be the following lines.
Element[0] = 1373
Element[1] = 0
...
Element[9] = 0
In your program, you are initializing the array n -
int n[ 10 ] = {002535};
The number 002535 is interpreted as a octal number because of leading zeros.
So, this will assign the octal value 002535 to n[0] i.e. 0th location in your array n and rest of array elements will be initialized with 0.
In for loop, you are printing it with format specifier %d.
The decimal equivalent of 002535 octal value is 1373. That's why you are getting Element [0] as 1373.
If you want to print octal number as output, use %o format specifier:
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %o\n", j, n[j] );
And if you want the decimal 2535 as first element of array n, remove leading zeros:
int n[ 10 ] = {2535};
An integer literal starting with 0 is interpreted as an octal number. And 02535 octal is equivalent to the decimal 1373

c array on a single line

I have to do a bubble sort with pointers for my class.
I am having trouble with the output
I want every array sort to be on a single line, not individual lines for each element.
Here is an array example that I would want to print.
I flipped the 1 and 9 to ensure that I was printing the proper value, not the location, when it was returning just one number.
[9, 2, 3, 4, 5, 6, 7, 8, 1]
Here is what it prints
[9]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[1]
How do I get this sample array onto just one line?
#include <stdio.h>
#define MAX 9
int val[] = {9, 2, 3, 4, 5, 6, 7, 8, 1};
int i;
int main(){
for (i = 0; i < MAX; i++
{ printf ("[%d]\n", val[i]);
}
return (0);
} //end main
Now I have read that you cant output to one line. I keep reading that you need each element to output individually. The prof has the sample output for the bubble pointer showing that all elements of the array remain on the same line. What am I missing?
FYI this is not the bubble sort with pointer. I am just needing help getting this sample array to output properly.
This must be in C, NOT C++, or C#.
I really don't see why you don't just remove the \n, which causes the newline. Then separate out the different parts of your output.
#include <stdio.h>
#define MAX 9
int val[] = {9, 2, 3, 4, 5, 6, 7, 8, 1};
int i;
int main(void){
putchar('[');
for (i = 0; i < MAX; i++) {
if (i == MAX - 1)
printf ("%d", val[i]);
else
printf ("%d, ", val[i]);
}
puts("]");
return (0);
} //end main
You cannot print the [ in the loop, or else it will print every time. Then, in the loop you want to print a comma unless you are at your last element where no elements should be printed next (if (i == MAX - 1). Finally you print the newline and the closing bracket at the end once the loop finishes. Make note that puts() automatically prints a newline.

Storing Odd and Even numbers in an Array

We were tasked to make a program that accepts ONLY ten inputs from the user and then sort it into an Even or Odd Array.
Accepts 10 inputs.
Segregates to an Even or Odd Array.
Print how many are in the Even/Odd Array.
Print the numbers in each Array.
This is the program I made:
#include<stdio.h>
int main(){
int even[10];
int odd[10];
int number;
int numOdd = 0;
int numEven = 0;
int sizeOdd = 0;
int sizeEven = 0;
int count;
printf("Input numbers:\n");
for(count = 0; count < 10; count++){
scanf("%d", &number);
if (number %2 == 0){
while (numEven < 10){
even[numEven++] = number;
sizeEven++;
}
}
else {
while (numOdd < 10){
odd[numOdd++] = number;
sizeOdd++;
}
}
}
printf("\n\nEven numbers(%d): ", sizeEven);
for(number = 0; number < numEven; number++){
printf("%d, ", even[number]);
}
printf("\n\nOdd numbers(%d): ", sizeOdd);
for(number = 0; number < numOdd; number++){
printf("%d, ", odd[number]);
}
system("pause");
return 0;
}
But my program just outputs the first numbers in the array and repeats it. Like, if I input 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, I get:
Even numbers (10): 2, 2, 2, 2, 2
Odd numbers (10): 1, 1, 1, 1, 1
Am I wrong with everything/my logic in the program? Am I on the right track and I just have to tweak it a bit? Hope for help!
This may help you:
Why do you add that while loop inside the if and else condition:
if (number %2 == 0){
even[numEven++] = number;
Also even[numEven++] itself increses the value of numEven variable no need to increment again in the next line.
You've used while twice, where you should have used if. As a result, your even array will be filled with the first even number entered, and your odd array will be filled with the first odd number.
Change each while to an if and you may be OK, though I haven't checked for other errors. For example...
if (number %2 == 0){
if (numEven < 10){
even[numEven++] = number;
sizeEven++;
}
}
The while keyword defines a complete loop of it's own - it's not a limit on some other kind of repetition such as (in this case) your addition of elements to each array.
BTW - you don't really need the if checks either. You only input 10 items, so at most you can add 10 items to the even array, or 10 items to the odd array. As the arrays are both large enough to take 10 items, you don't need bounds checks in this code.
The while keyword defines a complete loop of it's own - it's not a limit on some other kind of repetition such as (in this case) your addition of elements to each array.
BTW - you don't really need the if checks either. You only input 10 items, so at most you can add

Resources