I have an array with 100 numbers in it, and I am trying to print it out with only 10 ints on each line, and a tab between each number. It is only printing the first 10 integers and then stopping, which makes sense because of my for loop. I am clearly missing part of it to allow for it to continue through the array. I was going to try to add the line
for(int line_num = 0; line_num < 10; line_num+=10)
before the for statement after the while loop
int array_value;
int length_of_array = 100;
while (length_of_array <= 100){
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
I was also thinking of including a line like
if (array_value % 10 == 0)
printf("\n");
I figured it out! Posted the answer below.
This might be what you're looking for:
/* test.c */
#include <stdio.h>
#define ELEMENTS 100
int main (void)
{
int array [ELEMENTS];
for ( int i = 0; i < ELEMENTS; ++i )
array [i] = i;
for ( int i = 0; i < ELEMENTS; ++i ) {
printf ("%i", array[i]);
if ( (i + 1) % 10 != 0 )
printf ("\t");
else
printf ("\n");
}
return 0;
}
edit: Because of the way the tab can extend to the next line at the end of the line you have to be careful with the tab and new line character.
For clarity, rename length_of_array to offset_in_array and then set it to zero at the start. I renamed array_value and corrected your length check. I also added a check to the inner loop in case the array length gets changed and doesn't divide by 10.
Something like:
int i;
#define ARRAY_LENGTH 100
int offset_in_array = 0;
while (offset_in_array < ARRAY_LENGTH){
for(i = 0; i < 10 && offset_in_array < ARRAY_LENGTH; ++i){
printf("%d ", A[offset_in_array]);
++offset_in_array;
}
}
I haven't tried running this but it should be closer.
Just print a newline every tenth number... If it's not a tenth number, then print a tab.
for (size_t i = 0; i < array_length; ++i) {
printf("%d%c", A[i], i % 10 != 9 ? '\t' : '\n');
}
Live code available at onlinedbg.
Just change the value of length_of_array to 0 and print \n after a for loop.
int array_value;
int length_of_array = 0;
while (length_of_array <= 100) {
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
printf("\n");
}
You can use the following solution to print 10 lines of 100 array values in C:
for (int i = 0; i < 100; ++i){
printf("%i\t", A[i]);
if ((i+1)%10 == 0){
printf("\n");
}
}
Related
Im a beginner programmer and i needed some help with making the result of the following exercise look a bit better.
As i said in the title i want to make the exercise look nicer by removing the 0-s from the array and leaving just the numbers.
The exercise goes like this:
We enter an array of integers and we copy into the 2nd array the integers that are positive and negative and multiples of 3 and in the 3rd array the negative elements that are odd and not multiples of 3. This is the code that I did:
#include <stdio.h>
#include <stdlib.h>
#define N 5
int main()
{
int v[N];
int v2[N] = {0, };
int v3[N] = {0, };
int i;
printf("Please enter the elements of the 1st array: ");
for (i = 0; i < N; i++)
{
scanf("%d", &v[i]);
}
printf("\nThe elements of the 2nd array are: ");
for (i = 0; i < N; i++)
{
if ((v[i] >= 0 || v[i] <= 0) && v[i] % 3 == 0)
{
v2[i] = v[i];
}
}
for (i = 0; i < N; i++)
{
printf("%d ", v2[i]);
}
printf("\nThe value of the 3rd array are : ");
for (i = 0; i < N; i++)
{
if (v[i] <= 0 && v[i] % 2 != 0 && v[i] % 3 != 0)
{
v3[i] = v[i];
}
}
for (i = 0; i < N; i++)
{
printf("%d ", v3[i]);
}
return 0;
}
For future use if possible how to do I post a code copied for code blocks directly into here without using space 4 times on every line?
Thanks in advance
Another option is to insert a condition in the output loop:
for (i = 0; i < N; i++)
{
if (v2[i] != 0)
{
printf("%d ",v2[i]);
}
}
So here is the problem: Write a program that accept an integer n, print out the largest number but smaller or equal n that is the product of two consecutive even number. Example: Input: 12, Output: 8 ( 2x4 )
Here is my code :
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
for (int i = n; i >= 0; i--)
{
for (int j = 0; j <= n; j = j + 2)
{
if ( i == j * (j+2) )
{
printf("%d ", i);
break;
}
}
}
return 0;
}
So if i input 20, it will print out 8 and 0 instead of 8, if i input 30, it will print out 24,8 and 0 instead of just 24. How do i make it stop after printing out the first number that appropriate ?
You need to stop an outer loop from processing, for example by using a boolean flag (meaning "solution found, we finish work") or a goto statement.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int solutionFound = 0;
for (int i = n; i >= 0; i--) {
// this could also be put into for's condition i.e. "i >= 0 && !solutionFound"
if (solutionFound) {
break;
}
for (int j = 0; j <= n; j = j + 2) {
if ( i == j * (j+2) ) {
printf("%d ", i);
solutionFound = 1;
break;
}
}
}
return 0;
}
EDIT: immediate return as noted in the comments is also a nice idea, if you don't need to do anything later.
Your problem is that you are nested - in a for loop which is inside another for loop - when you want to stop processing.
Some languages would let you code break 2; to indicate that you want to break out of 2 loops. Alas, C i snot such a language.
I would recommend that you code a function. That would serve a few porpoises: 1) your main should be "lean & mean" 2) as your programs get larger, you will learn the benefits of putting individual coding tasks into functions 3) you can use return; instead of break; and it will exit the function immediately.
Something like this:
#include <stdio.h>
void FindNeighbouringDivisors(int n)
{
for (int i = n; i >= 0; i--)
{
for (int j = 0; j <= n; j = j + 2)
{
if ( i == j * (j+2) )
{
printf("%d times %d = %d", j, j + 2, i);
return;
}
}
}
printf("There are no two adjacent even numbers which can be multiplied to give %d", n);
}
int main()
{
int n;
scanf("%d", &n); /* could get from comamnd line */
FindNeighbouringDivisors(n);
return 0; /* should be EXIT_SUCCESS */
}
Btw, when you have a problem with your code, ask a question here. When you have it working, consider posting it at our code review site where more experienced programmers can give you advice on how to improve it. It's a great way to learn
Break only breaks you out of immediate loop, so either use flags or just use return to terminate the execution. Or you can even use following code:
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
for (int j = 0; j <= n; j = j + 2)
{
if ( n < j * (j+2) )
{
printf("%d ", j*(j-2));
break;
}
}
return 0;
}
Sample Input
2
2
5
Sample Output
0 1 1
0 1 1 2 1 2
I already knew how to transfer an integer to its binary and count how many 1 in its binary.
But my code only can input one integer each time. I want it to input many numbers, like the sample input and sample output. To make question more easy to understand, so I drew a picture. Thank you!!
Thanks all of you!! But I need some time to understand those code and my English is pretty basic, so I couldn't reply you guys soon. But I will understand and reply you as soon as possible!!thank you :D
#include <stdio.h>
int main()
{
int n,cnt=0,m;
scanf("%d",&n);
while(n>0){
m=n%2;
if(m==1){
cnt++;
}
n/=2;
}
printf("%d",cnt);
return 0;
}
In practice, the process can be simplified and accelerated by noticing that if we know the result for i < 2^p, then, for all values in [2^p, 2^(p+1)-1], we have
count(j) = 1 + count(j-2^p)
This method is useful here as we have to provide the result for all values less or equal to n.
Moreover, in order to avoid performing the same calculation at different times, we first calculate the maximum n value, and perform the calculation for this maximum value.
#include <stdio.h>
int main() {
int t;
int check = scanf("%d", &t);
if (check != 1) return 1;
int nn[t];
for (int i = 0; i < t; ++i) {
int check = scanf("%d", &nn[i]);
if (check != 1) return 1;
}
int nmax = 0;
for (int i = 0; i < t; ++i) {
if (nn[i] > nmax) nmax = nn[i];
}
int count[nmax+1];
count[0] = 0;
count[1] = 1;
int pow2 = 1;
do {
pow2 *= 2;
for (int j = pow2; (j < 2*pow2) && (j <= nmax); j++) {
count[j] = 1 + count[j-pow2];
}
} while (pow2 <= nmax+1);
for (int i = 0; i < t; ++i) {
for (int j = 0; j <= nn[i]; ++j) {
printf ("%d ", count[j]);
}
printf ("\n");
}
return 0;
}
Let the number of measured values be t. Now if you want to take t number of integers as input, you have to run a loop t times and perform necessary tasks (like taking value of n, calculating cnt etc) inside that loop. Check the following code snippet:
int main()
{
int n,cnt=0,m;
int numberOfMeasuredValues;
scanf("%d", &numberOfMeasuredValues);
while(numberOfMeasuredValues > 0){
cnt = 0;
scanf("%d",&n);
// perform necessary calculations
printf("%d\n",cnt);
numberOfMeasuredValues--;
}
return 0;
}
In the code numberOfMeasuredValues is the t I've used in the explanation.
You can pre-allocate number of cases and work on them with outer and inner loops. I've added the code with comments below.
#include <stdio.h>
int main(void)
{
int cases; // Number of cases
scanf("%d", &cases);
int* nums = malloc(cases * sizeof *nums); // Allocate enough space.
/* Take the inputs. */
for (int i = 0; i < cases; i++)
{
scanf("%d", (nums + i));
}
int cnt = 0; // Counter for number of 1s.
// Outer loop for going through cases.
for (int i = 0; i < cases; i++)
{
// Inner loop for couting towards inputted number.
for (int j = 0; j < *(nums + i) + 1; j++)
{
/*
* You can Implement this part by yourself if you wish.
*/
for (int k = 0; k < 32; k++)
{
if ((j >> (31 - k)) & 0x01) cnt++; // Increment counter if digit is 1.
}
printf("%d ", cnt);
cnt = 0;
}
printf("\n");
}
return 0;
}
Here's the following code to your problem
#include<iostream>
using namespace std;
int main()
{
int tcs;
cin >> tcs;
while (tcs--) {
int n;
cin >> n;
for (int i = 0 ; i <= n ; i++) {
cout << __builtin_popcount(i) << " ";
}
cout << "\n";
}
return 0;
}
I am trying to assign user input into an array; however, the program below only picks up on the first element in each line of input. The ultimate goal of this program is to find the diagonal sums of integers and return the absolute value of their difference.
Example input (note that the first number gives the number of rows and columns (square array):
Input:
3
11 2 4
4 5 6
10 8 -12
Output:
Expected = 15
Actual = 10
I realize that the issue lies in the way that the array is setup. If I print the array out I get: 111555999
Any hints/help would be very appreciated.
int main() {
int n, i, c, multi_array[200][200], sum1 = 0, sum2 = 0;
scanf("%i", &n); //N = number of rows and number of columns (square 2D array)
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d ", &multi_array[c][i]); //enter integers to store in array
}
}
for (i = 0; i != n; i++) {
sum1 += multi_array[i][i]; //add up top left to bottom right diagonal
}
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n-i]; //add up top right to bottom left diagonal
}
printf("%i", abs(sum1 - sum2)); //print absolute value of the difference between diagonals
return 0;
}
Your major problem is here, where you go out of bounds:
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n - i]; // when i is 0, th
}
When i = 0, you are accessing multi_array[0][3], which is out of bounds when N = 3.
So change it to this:
multi_array[i][n - i - 1]
You should read your array like this:
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf(" %d ", &multi_array[i][c]);
}
}
since C stored its arrays in row-major order. What you have stores the array in column-major order. It's not wrong, but it's something you do only if you really have to.
Finally, change again the input part of your code to this:
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d", &multi_array[i][c]);
}
}
so that you have to input exactly what you need to. With your initial code I have to type an extra random number when I had completed the input process.
Last but not least, I am posting the whole code, where I have wrote some extra printf()'s, which are actually for the programmer, so that he can see step-by-step if his code is acting as expected or not.
#include <stdio.h>
#include <stdlib.h> /* abs */
int main() {
int n, i, c, multi_array[200][200], sum1 = 0, sum2 = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d", &multi_array[i][c]);
}
}
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
printf("|%d|", multi_array[i][c]);
}
printf("\n");
}
for (i = 0; i != n; i++) {
sum1 += multi_array[i][i];
}
printf("sum1 is %d\n", sum1);
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n - i - 1];
}
printf("sum2 is %d\n", sum2);
printf("%i", abs(sum1 - sum2));
return 0;
}
Output:
3
11 2 4
4 5 6
10 8 -12
|11||2||4|
|4||5||6|
|10||8||-12|
sum1 is 4
sum2 is 19
15
You are clearly going out of bounds here:
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n-i]; //add up top right to bottom left diagonal
}
When i is equal to 0 the expression n-i will be equal to n, but the range of the array is from 0 to n-1. The code will read uninitialized values and cause undefined behavior.
The second array index should be 1 less.
Need to figure out a code that counts all the repeating symbols in a string. As you can see below, so far so good.
And here starts the tricky part, at the end of the code I want to output symbols in an order they were typed which had for example 2 occurences in a string, and I got problems figuring that out.
int counts[256] = { 0 };
int i;
size = strlen(text);
for (i = 0; i < size; i++) {
counts[(int)(text[i])]++;
}
for (i = 0; i < 256; i++) {
printf("The %d. character has %d occurrences.\n", i, counts[i]);
}
Just iterate through the source string again and for each character look into your counts array.
If you don't want to print the same statistics for every occurence of repeating character, you can reset the corresponding counts value to zero just after you print the statistics, and have an additional check before printing.
for(i = 0; i < size; i++) {
if(counts[(int)(text[i])] == 2)
printf("%d", (int)(text[i]));
The first line loops through your source string for the order of occurences.
The second line checks if it was captured in the counts array as occuring only twice.
If it was we print the char code on the third line.
To only print the character once:
for(i = 0; i < size; i++) {
if(counts[(int)(text[i])] == 2) {
printf("%d", (int)(text[i]));
counts[(int)(text[i])] = 0;
}
}
Here is an implementation of Inspired's answer:
int counts[256] = { 0 };
char text[] = "Hello, world!";
int i, size = strlen(text);
for (i = 0; i < size; i++)
{
counts[(unsigned int)(text[i])]++;
}
for (i = 0; i < size; i++)
{
if (counts[(unsigned int)text[i]] > 1)
{
printf("%c", text[i]);
counts[(unsigned int)text[i]] = 0; // Remove to print repeats.
}
}
Make a key,count pair, like:
#include <string.h>
#include <stdio.h>
int main()
{
char* text = "count this text";
char *keys = new char[strlen(text)];
int* count = new int[strlen(text)];
int last = 0; int j=0;
for(int i=0; i<strlen(text); i++){
for(j=0; j<last; j++){
if(keys[j]==text[i]) break;
}
if(keys[j]==text[i]){
count[j]++;
} else {
keys[last]=text[i];
count[last]=1;
last++;
}
}
for(int i=0; i<last; i++){
printf("%c %d\n", keys[i], count[i]);
}
}
so you keep the order in the text and get the count.
On execution the output is:
c 1
o 1
u 1
n 1
t 4
2
h 1
i 1
s 1
e 1
x 1