How to stop the loop after printing one? - c

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;
}

Related

Function prints infinitely when in loop, although it's not called repeatedly

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!

Count how many 1 in integer's binary

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;
}

Trying to print 10 lines of 100 array values in C

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");
}
}

Negative numbers are printed

This is a program on sorting integers.
#include <stdio.h>
int main(void) {
int n, i, j, k;
int nmbr[100];
printf("\n How many numbers ? ");
scanf("%d", &n);
printf("\n");
for (i = 0; i < n; ++i) {
printf(" Number %d : ", i + 1);
scanf("%d", &nmbr[i]);
}
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
if (nmbr[j] > nmbr[j + 1]) {
k = nmbr[j];
nmbr[j] = nmbr[j + 1];
nmbr[j + 1] = k;
}
}
}
printf("\n Numbers after sorting : \n");
for (i = 0; i < n; ++i) {
printf (" %d", nmbr[i]);
}
return 0;
}
It works fine, but when I enter some number that contains more than 2 digits, the first number that is printed is negative and really big. I don't also get the last integer too. I enter N as 4, then the numbers I entered were 25, 762, 588, and 34. The result I get is:
-1217260830 25 34 588
What seems to be the problem?
You are running the loop as for (j = 0; j < n; ++j) which means j will have values from 0 to n-1 which are valid array indices (or array elements with relevant values).
But, inside that loop you are accessing an element beyond the last. For instance, in
if (nmbr[j] > nmbr[j + 1])
you are accessing nmbr[j + 1]. If the current value of j in n-1, then you are accessing nmbr[n-1 + 1] i.e. nmbr[n] which will be a value outside the array and may contain a garbage value (which might as well be negative!).
If you are trying something like Bubblesort, you might want to run the inner loop like for (j = 0; j < n - 1; ++j).
There are multiple problems in your code:
You do not check the return values of scanf(). If any of these input operations fail, the destination values remain uninitialized, invoking undefined behavior and potentially producing garbage output.
You do not verify that the number of values provided by the user is at most 100. The reading loop will cause a buffer overflow if n is too large.
Your sorting logic is flawed: in the nested loop, you refer to nmbr[j + 1] which is beyond the values read from the user. This invokes undefined behavior: potentially causing a garbage value to appear in the output.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int n, i, j, k;
int nmbr[100];
printf("\n How many numbers ? ");
if (scanf("%d", &n) != 1 || n > 100) {
printf("input error\n");
return 1;
}
printf("\n");
for (i = 0; i < n; ++i) {
printf(" Number %d : ", i + 1);
if (scanf("%d", &nmbr[i]) != 1) {{
printf("input error\n");
return 1;
}
}
for (i = 0; i < n; ++i) {
for (j = 0; j < n - 1; ++j) {
if (nmbr[j] > nmbr[j + 1]) {
k = nmbr[j];
nmbr[j] = nmbr[j + 1];
nmbr[j + 1] = k;
}
}
}
printf("\n Numbers after sorting :\n");
for (i = 0; i < n; ++i) {
printf (" %d", nmbr[i]);
}
printf("\n");
return 0;
}
Your Sorting Logic is wrong. It should be:
for (i = 0; i < n; ++i){
for (j = 0; j < (n-1); ++j){
if (nmbr[j] > nmbr[j + 1]){
k = nmbr[j];
nmbr[j] = nmbr[j + 1];
nmbr[j + 1] = k;
}
}
You are trying to access out of bounds of array, when you iterate in your second loop using j. This is causing the garbage value.
As per your example involving 4 elements, when you try to access j+1, it will try to access nmbr[3+1] in the last iteration of second loop which leads to out of bounds access.
Problem is with the sorting logic as suggested by fellow coders. But It is always good coding habit to initialize the variables. Also use the qualifier if are dealing with positive numbers only.
unsigned int n = 0 , i = 0, j = 0, k = 0;
unsigned int nmbr[100] = {0};
If you would have initialized them, out put of your program would be following, which might help you tracing the problem by yourself.
0 25 34 588

c programming - printing sequence of sum of squared digits (as an array) for a potential happy number

I have this assignment for my intro to C programming class and part of my code has to find the sequence of the sum of square digits of a number in order to determine after if the given number is a happy number (sum of square digits = 1)
Here's part of my code:
#include <stdio.h>
#include <math.h>
// The sum of square digits function
int sqd (int x) {
int sum = 0;
while (x > 0) {
sum = sum + pow(x%10, 2);
x = x/10;
}
return sum;
}
// The search function
int search (int a[], int val, int size) {
int i;
for (i = 0; i < size; i++) {
if (a[i] == val) {
return 1;
}
}
return 0;
}
// The main program
void main () {
int a [1000] = {0};
int N;
int count = 1;
int j;
printf("Please enter the potential happy number:\n", N);
scanf ("%d", &N);
a[0] = N;
a[count] = sqd (N);
do {
a[count] = sqd (a[count-1]);
count++;
} while (search (a, a[count], count));
for ( j = 0; j <= count; j++) {
printf("%d\n", a[j]);
}
}
It only prints the first three sums in the sequence. I really don't know how to make it work.
Thank you in advance
This line
while (search (a, a[count], count));
makes sure that you break out of the loop after one round since a[1] is not equal toa[0]. You can change that line to be:
while (a[count-1] != 1);
You also need to add a clause to make sure that you stop when the limit of the array is reached. Update that line to be:
while (a[count-1] != 1 && count < 1000 );
And then, change the printing loop to use i < count, not i <= count. Using <= will result in accessing the array out of bounds when the user enters a sad number.
for ( j = 0; j < count; j++){
printf("%d\n", a[j]);
}
Update
After a bit of reading on happy numbers at Wikipedia, I understand why you had call to search in the conditional of the while. The following also works.
} while ( ! (a[count-1] == 1 || search(a, a[count-1], count-1)) );
That will search for the last number in the array but only up to the previous index.

Resources