I'm new to C and I'm trying to practice my knowledge by doing programs by my own without the use of the internet. I'm stuck with a small and probably dumb mistake but i can't seem to understand what it is. I'm trying to build an hour glass but before i do so i need to understand printing triangles. I'm really going step by step with this and I have tried to understand my mistake for very long with this.
I have my code below and I'm trying to print j where i need j to print normally 12345 then 1234, 123 etc.. but when I use temp-- it skips by printing 123,1,1 and closes the program.
Can somebody have a look at it and tell me what the problem with me second for loop?
#include <stdio.h>
int main()
{
int i,j,k,num, temp=0;
printf("Enter a number: ");
scanf("%d", &num);
temp=num;
for (i=1; i<=num; i++) // Step1: Take care of the rows --> check
{
for (j=1; j<=temp; j++)
{
printf("%d", j);
temp-=1;
}
printf("\n");
}
}
You both increment j and decrement temp which leads to odd effects. You probably don't want to decrement temp. Or you need to reset temp before the inner loop, rather than before the outer loop.
Or, indeed, you do not really need temp at all. Here are two variants of the code, one creating a triangle growing, and one creating a triangle shrinking. Neither needs temp (though t-dn.c could use a variable in place of the expression num - i + 1, but the compiler will probably handle that anyway — it is a basic optimization).
t-up.c
#include <stdio.h>
int main(void)
{
int i,j,num;
printf("Enter a number: ");
scanf("%d", &num);
for (i=1; i<=num; i++)
{
for (j=1; j<=i; j++)
printf("%d", j);
printf("\n");
}
}
t-dn.c
#include <stdio.h>
int main(void)
{
int i,j,num;
printf("Enter a number: ");
scanf("%d", &num);
for (i=1; i<=num; i++)
{
for (j=1; j<=num-i+1; j++)
printf("%d", j);
printf("\n");
}
}
Example output
$ ./t-up
Enter a number: 5
1
12
123
1234
12345
$ ./t-dn
Enter a number: 5
12345
1234
123
12
1
$
t-ok.c
Another variant, keeping the temp variable around:
#include <stdio.h>
int main(void)
{
int i,j,num,temp;
printf("Enter a number: ");
scanf("%d", &num);
temp=num;
for (i=1; i<=num; i++)
{
for (j=1; j<=temp; j++)
printf("%d", j);
printf("\n");
temp--;
}
}
It produces the decreasing pyramid I believe you want. It places the decrement outside the inner loop.
You're decrementing your j-loop condition within the j-loop. This means that every time you print a number, you also decrease the size of your loop (not at all what you want). To fix this, you need to move your temp-=1 from
for (i=1; i<=num; i++) // Step1: Take care of the rows --> check
{
for (j=1; j<=temp; j++)
{
printf("%d", j);
temp-=1;
}
printf("\n");
}
to
for (i=1; i<=num; i++) // Step1: Take care of the rows --> check
{
for (j=1; j<=temp; j++)
{
printf("%d", j);
}
temp-=1;
printf("\n");
}
This decreases the size of your j-loop AFTER you've finished going through it, so you should wind up with the right amount of numbers.
You could even do away with your temporary variable by reversing the i-loop like such
for ( i = num ; i > 0 ; i-- ) {
for ( j = 1 ; j <= i ; j++ ) {
printf("%d", j);
}
printf("\n");
}
for a simpler code.
Related
I'm new to C and need some help to understand how this piece of code works. I know that it reads the values that the user writes, puts them into an array, and then prints them out.
But I don't understand why I need two "counters" (i and j) to do this. Can someone help me to figure it out?
#include<stdio.h>
int main ()
{
int A[5];
int i=0;
int j=0;
while (i < 5)
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}
while (j < 5)
{
j++;
printf ("\n%d\n", A[j]);
}
}
Technically, what you have aren't two counters, but two loops. If you wanted, to, you could just reuse i for the second loop as well, by doing something like this:
while (i < 5)
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}
i = 0;
while (i < 5)
{
i++;
printf ("\n%d\n", A[i]);
}
As for why you have two loops, the reason is simple. The first loop (using i in your code), reads the 5 integers into the array A. After the first loop concludes, your array A holds the 5 int values, which you could've used however you wanted. In your case, you want to print those values. So what you do is use a loop for looping over the array elements and printing the values to the screen, one by one.
You don't need it, you can simply reset the first and reuse it. However you must increment your index only after having using it otherwise you will overflow the limit of the array :
#include<stdio.h>
int main ()
{
int A[5];
int i=0;
while (i < 5) {
printf("Enter your %d number\n", i);
scanf("%d", &A[i]); // the last must be 4 not 5
i++; //<== increment here
}
i=0;
while (i < 5)
{
printf ("\n%d\n", A[i]); //idem
i++;
}
}
I hope someone can help me.
I want to create stars "*" instead of my numbers in the output of array, 10 numbers.
Example
Input
Number 1: 3
Number 2: 2
Number 10: 5
Output
Number 1: ***
Number 2: **
Number 10: *****
But i get always the same number of stars.
Thanks! Dear Harman
#include <stdio.h>
int main()
{
int tal[10], i, j, z;
printf("Mata in tio tal mellan 0 och 60:\n");
for(z=0;z<10;z++)
{
printf("Tal %d: ", z+1);
scanf("%d",&tal[i]);
}
printf("\nRita ut stapeldiagram:\n");
for(z=0;z<10;z++)
{
printf("Tal %d: ", z + 1);
for (j=0; j<i; j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Here's your bug. Your inner for-loop that prints a star is redefining the iteration index, i. Simple fix is to use a new variable, say j, in this line:
for (i=0; i<tal; i++)
To this:
for (int j=0; j<tal; j++)
First of all, when scanning user input you are storing the value at the same position of the array tal . Increment the value of i so that in every iteration the new value takes a new memory place .
for(z=0, i=0; z<10; z++, i++)
{
printf("Tal %d: ", z+1);
scanf("%d",&tal[i]);
}
Secondly when printing out the stars in the inner loop, you are iterating to a fixed number i . So , it is printing the fixed number of stars in every iteration of outer loop. Iterate the inner loop to tal[z] . I hope this will make you smile .
for(z=0;z<10;z++)
{
printf("Tal %d: ", z + 1);
for (j=0; j<tal[z]; j++)
{
printf("*");
}
printf("\n");
}
I'm a beginner to C, and am trying to sort user inputted numbers into odd and even arrays. I don't understand why my code isn't working.
Cheers.
This is my code, I don't understand my mistake.
int x[]= {};
int i=0;
int d=0;
int j=0;
int even[12]={};
int odd[12]={};
printf("Enter amount of numbers: "); // asking user for amount of numbers
scanf("%d", &d);
for (j=0; j<d; j++){
printf("Enter number %d: ", i+1); // scanning input into 'x' array
scanf("%d", x[i]);
}
printf("Even numbers: ");
for (i=0; i<d; i++) {
if (x[i] % 2 == 0) { // sorting into even array
even[i]=x[i];
printf("%d \n", even[i]);
}
}
printf("\n Odd numbers: ");
for (i=0; i<d;i++){
if (x[i] % 2 != 0) { // sorting into odd array
odd[i]=x[i];
printf("%d \n", odd[i]);
}
}
This error message keeps coming up:
$ ./main
Enter amount of numbers: 4
Enter number 1: 6
Segmentation fault (core dumped)
int x[]= {}; doesn't work because it would hold no elements. But initializing it with {} doesn't work in C anyway, do this instead:
int x[24] = {0}; // first element explicitely set to 0, the rest default-initialized to 0
You also need to put {0} for even and odd. If it's compiling for you with {} then it's possible that you're compiling it as a C++ program, or perhaps your compiler just tolerates it anyway (but it won't work on every C compiler).
scanf needs the address of the int, so instead of scanf("%d", x[i]); you need scanf("%d", &x[i]);. But i is the wrong iterator for this for (j = 0; j < d; j++) loop. Instead do this:
for (j = 0; j < d; j++) {
printf("Enter number %d: ", j + 1); // scanning input into 'x' array
scanf("%d", &x[j]);
}
Also note that the way you're doing this, half the array will be left at 0. So for instance if I imputted the values 1 through 6, then odd contains the values 1 0 3 0 5 0.
#include <stdio.h>
#include <conio.h>
void main()
{
int arr[5], new[5], i, j;
printf("ENTER ANY FIVE NUMBERS:");
scanf("%d%d%d%d%d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]);
for(i=0; i<5; i++)
{
for(j=5; j>=0 ;--j)
{
new[i] = arr[j];
printf("%d", new[i]);
printf(" ");
}
}
getch();
}
The above code is of a simple problem, which asks to take inputs of numbers in an array and show the inverse array of the input. I tried to solve it myself and wrote the above code. But the compiler is showing the result multiple times, I mean, the result should have only 5 numbers but the output shows series of numbers.
Here is one problem:
for(j=5;j>=0;--j){
new[i]=arr[j];
^ out of bounds access to arr[5]
Change it to
for(j=4;j>=0;--j){ // 4 instead of 5
new[i]=arr[j];
That said, if all you want is to print an array in reverse order, simply do:
for(j=4;j>=0;--j){
printf("%d", arr[j]);
printf(" ");
}
printf("\n");
No need for two loops and no need for the extra array new
If you really want a "reversed copy" do:
for(j=4;j>=0;--j){
new[4-j] = arr[j];
printf("%d", arr[j]); // or printf("%d", new[4-j]);
printf(" ");
}
printf("\n");
I'm trying to make a one-month calendar that prints the sum of the last row of days.
The output of this is correct for the calendar, but the sum keeps printing out that it's 0. For an input of 3=day_of_week and 30=days_in_month, the sum should be 26+27+28+29+30 = 140
Thanks.
int main() {
int day_of_week, days_in_month, i, row=1, array[31], sum=0, a;
printf("Enter the day of the week 1=sun, 2=mon, 3=tue, 4=wed, 5=thurs, 6=fri, 7=sat\n");
scanf("%d", &day_of_week);
printf("Enter the number of days in this month:\n");
scanf("%d", &days_in_month);
for (i=0; i<3*day_of_week; i++)
printf(" ");
for (i=1; i<=days_in_month; i++) {
printf("%3d", i);
array[i] = i;
day_of_week++;
if (day_of_week%7==0){
printf("\n");
}
}
printf("\n");
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
sum+=array[a];
printf("sum of last row is %d\n", sum);
return 0;
}
I don't understand why you are doing ++day_of_week,
something like this should work better:
int main()
{
int day_of_week, days_in_month, i, row=1, array[31], sum=0, a;
printf("Enter the day of the week 1=sun, 2=mon, 3=tue, 4=wed, 5=thurs, 6=fri, 7=sat\n");
scanf("%d", &day_of_week);
printf("Enter the number of days in this month:\n");
scanf("%d", &days_in_month);
for (i = 0; i < 3 * day_of_week; i++)
printf(" ");
for (i = 1; i <= days_in_month; i++)
{
printf("%3d", i);
array[i] = i;
if (i % 7 == 0)
printf("\n");
}
printf("\n");
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
sum+=array[a];
printf("sum of last row is %d\n", sum);
return 0;
}
You have
for (a=days_in_month; a>=(days_in_month-(7-day_of_week)); a--)
but day_of_week does not remain constant in your program and changes before with this statement:
day_of_week++;
Use a second variable to increment and do not modify day_of_week after scanf.
One problem is here:
for (i=1; i<=days_in_month; i++) {
printf("%3d", i);
array[i] = i;
day_of_week++;
if (day_of_week%7==0){
printf("\n");
}
}
You are allowing day_of_week to go out of range. Your code expects that value to be no more than 7. This loop will result in that variable being set to the value the user entered plus (days_in_month - 1). In your final for loop, the statement 7 - day_of_week will likely be negative, which will throw the rest of your code off.
You are sort of checking for overflow when you test the variable modulo 7 and print a newline. When you do that, set day_of_week = 0 as well.
Also, calculate (days_in_month-(7-day_of_week)) and store it in a temporary variable as soon as you get the input from the user. Since you're manipulating these variables inside your code, your final for loop probably isn't using the values that you think it's using. Alternatively, don't modify the variables that you use for user input and create other variables to use as temporaries.