I'm currently trying to solve a problem on Hackerrank where I have to print a pattern. Everything works as it's intended right now, except for the call of my loop function repeat_number inside the loop (!). It prints numbers infinitely, although it should only print it a fixed number of times.
This does not happen, when I call the function before the loop starts. When I print an integer variable it also prints only once. The error only occurs when I call repeat_number inside the loop.
Why is that?
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void repeat_number(int number_to_repeat, int times_to_repeat) {
for (int e; e < times_to_repeat; e++) {
printf("%d ", number_to_repeat);
}
}
int main()
{
int n;
scanf("%d", &n);
// Complete the code to print the pattern.
// get number of rows
int rows = n * 2 - 1;
int starting_number = n;
// print row after row
for (int r; r < rows; r++) {
// count down
for (int i = rows; i > 0; i--) {
if (starting_number >= 1) {
printf("%d ", starting_number);
if (starting_number > 1) {
starting_number--;
}
else {
break;
}
}
}
// repeat number
repeat_number(5,1);
// test
//int test = 2;
//printf("%d", test);
// count up
for (int j = 1; j < rows; j++) {
if (starting_number >= 1) {
if (starting_number < n) {
starting_number++;
}
else {
break;
}
printf("%d ", starting_number);
}
}
printf("\n");
}
return 0;
}
This line looks very dangerous:
for (int e; e < times_to_repeat; e++)
I would replace it by:
for (int e = 0; e < times_to_repeat; e++)
Because: imagine that e get initialised as some very small number, then you can have an enormous loop: always initialise your variables!
Related
So, I'm doing an exercise, and I want to sort a list of float numbers. When I used for loop, it worked perfectly. When I changed to while loop, it shows nothing. I already tried to declare a different variable for each while loop, but remains the same. I'm getting this warning for the file ex005.c:
Please, input one non-integer values: 45.3
Please, input one non-integer values: 32.2
Please, input one non-integer values: 34.5
zsh: segmentation fault ./"ex005"
Here is my code:
#include <stdio.h>
int main(void)
{
float three_numbers[3];
char support_var;
int size_array;
int i;
int z;
size_array = 3;
z = size_array - 1;
i = 0;
while (i < size_array)
{
printf("Please, input one non-integer values: ");
scanf("%f", &three_numbers[i]);
i++;
}
i = 0;
while (i < size_array)
{
while (z != i)
{
if (three_numbers[i] < three_numbers[z])
{
support_var = three_numbers[i];
three_numbers[i] = three_numbers[z];
three_numbers[z] = support_var;
}
z--;
}
i++;
}
i = 0;
while (i < size_array)
{
printf("The %dth place is %.1f. \n", i + 1, three_numbers[i]);
i++;
}
return (0);
}
You probably want to set z in the inner loop otherwise it causes out of bound access of three_numbers[z]. Also, your support_var should be a float. Use the typeof operator if available (with gcc 10.2.1-6 it's still an extension so -std=gnu18):
#include <stdio.h>
#define ARRAY_SIZE 3
int main(void) {
float three_numbers[ARRAY_SIZE];
for(int i = 0; i < ARRAY_SIZE; i++) {
printf("Please, input one non-integer values: ");
scanf("%f", three_numbers + i);
}
for(int i = 0; i < ARRAY_SIZE; i++) {
for(int z = ARRAY_SIZE - 1; z != i; z--) {
if(three_numbers[i] < three_numbers[z]) {
// typeof (*three_numbers) support_var = three_numbers[i];
float support_var = three_numbers[i];
three_numbers[i] = three_numbers[z];
three_numbers[z] = support_var;
}
}
}
for(int i = 0; i < ARRAY_SIZE; i++) {
printf("The %dth place is %.1f. \n", i + 1, three_numbers[i]);
}
}
Not sure why you don't like for-loops but it makes your code easier to read. Also replaced int array_size with a constant ARRAY_SIZE. Minimizing scope of variables makes is usually a good idea.
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 new to C and I have been trying to print a pyramid of * using for loops and printf() in a RIGHT ALIGNMENT manner; like this;
*
**
***
I can only do this
*
**
***
#include<stdio.h>
int main()
{
int i,j,k;
for(i=1;i<=5;i++)
{
for(j=5;j>i;j--)
{
printf(" ");
}
for(k=1;k<=i;k++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Here the first for-loop creates rows which are 5. Second for loop does the spacing and the third for loop prints the stars.
When
i = 1; j goes from 5 to 2 and prints spaces. After this k=1 and it prints one star.
i = 1; j = 5,4,3,2; k = 1
i = 2; j = 5,4,3 ; k = 1,2
.
.
i = 5; j = 0; k = 1,2,3,4,5
Here "-" represents a blank space.
So it goes down like this:
----*
---**
--***
-****
*****
You can use printf format specifier tricks mentioned in the comments or you can do this using basic for loops. Break down the problem step by step. First a loop for given number of lines, then a loop for spaces in each line, then a loop for stars in each line. Here's the code:
#include <stdio.h>
int main(){
int max_stars = 3;
// for every line
for(int i=1; i<=max_stars; ++i){
// print max_stars - i spaces
for(int j=1; j<= max_stars-i; ++j){
printf(" ");
}
// print i stars
for(int j=1; j<=i; ++j){
printf("*");
}
//print a new line
printf("\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
void f(int n)
{
int x = 1 , y , var ;
while( n > 0 )
{
for( var = n-1 ; var > 0 ; var-- )
{
fputc(' ',stdout);
}
for( y = 0 ; y < x ; y++ )
{
fputc('*',stdout);
}
fputc('\n',stdout);
n--;
x++;
}
}
int main(void)
{
f(3);
return 0;
}
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