• 0

for loops, counting by 3's, and using /t in the print statement to prin


Question

I am seriously stuck.  I'm supposed to write a program that counts by 3's using a for loop with the increment clause either being 1 = i + 3 or i + = 3.  So far this is what i have, but it's not even close to working.  While it does not tell me that I have errors until the execution, once it runs i get a runtime error and must abort the program.  Am I over thinking this?  And how do you get the table (\t) function to work with the column headings and contents?  This is so confusing!  I've reread my book Deitel's C How to Program and looked up as much as I can on the web to find out more information on how to use it, but the book is vague with no examples, and the explanations that I found on the internet were very convoluted .

#include "stdio.h"

void main()
{
	int i;

	for(i = i + 3; i < 18; i++)
		{
			if (i % 3 == 0)
		printf("\t 'A'","%d",  &i);
			if (i % 3 != 0)
	continue;
			printf("\n");
	}

	for(i = i + 3; i < 20; i++)
	{ if (i % 3 == 0)
	printf("\t 'A+2", "%d", i);
	if (i % 3 != 0)
		continue;
	printf("\n");
	}
}

it should print out a table that looks like this :

 

post-505691-0-18091700-1379873055.png

15 answers to this question

Recommended Posts

  • 0

Your program is far more complicated than it needs to be. You already have the answer to the problem in your description. The iterator in your for loop should be i += 3 rather than i++ to use the loop to count by threes. Not only does that obviate your use of modulus, but it also eliminates the need for more than one for loop (assuming you actually needed more than one using the method you first attempted, which looks completely wrong).

 

I also get the impression that you don't completely understand the basic escape sequences in C. For example, '\t' is the escape sequence for horizontal tab, not table like you seem to suppose. Furthermore judging by your code I'm not entirely sure how you expected '\t' to generate a table anyway. Take a look at this page for a list of common escape sequences in C and C++. You can get a more complete picture by looking at the ASCII chart if you wish.

 

Despite its relatively short length I spotted a few more serious flaws in your code which I did not address above. I recommend that you completely throw it out, and start again based on your hopefully-more-thorough understanding of the problem.

  • 0
  On 22/09/2013 at 18:10, Terabojin said:

I'm supposed to write a program that counts by 3's using a for loop with the increment clause either being 1 = i + 3 or i + = 3.  So far this is what i hav

The increment clause is the third and last clause of the for loop statement. You have mistaken it for the first clause. You initialize i to itself + 3, which means you use i before you initialize it. In C, this is undefined behavior, i.e. the value of i will be random garbage. No wonder your program is not behaving the way you wish.

 

You increment i by 1 instead of 3, but then you filter out the non-multiple of 3 values with if statements. This shows you misundertood the question. Increment i by 3 and remove the if (i % 3) statements.

 

I suggest you start by writing a program that prints the following with only a single for loop and a single printf (no if statements):

6
9
12
15
18

This will provide the correct basis for the rest of the program. Once you have that, figure out how to print the 3 other columns (hint: use an inner for loop). Once you have that, print the column labels (A - A+3).

 

Finally, how do you run your program? Simply running the compiled .exe from a command prompt will make it hard to understand your errors. It would very helpful for you to use an IDE and launch your program in the debugger (F5 in most IDEs). When an run-time error is detected, it'll show you exactly where and what the state of the program is at that point.

  • 0
#include "stdio.h"

void main()
{
	int i;

	for(i = i + 3; i < 18; i++)
		{
			if (i % 3 == 0)
		printf("\t 'A'", "%d");
			if (i % 3 != 0)
	continue;
			printf("\n");
	}
}
  On 22/09/2013 at 19:46, xorangekiller said:

Your program is far more complicated than it needs to be. You already have the answer to the problem in your description. The iterator in your for loop should be i += 3 rather than i++ to use the loop to count by threes. Not only does that obviate your use of modulus, but it also eliminates the need for more than one for loop (assuming you actually needed more than one using the method you first attempted, which looks completely wrong).

 

I also get the impression that you don't completely understand the basic escape sequences in C. For example, '\t' is the escape sequence for horizontal tab, not table like you seem to suppose. Furthermore judging by your code I'm not entirely sure how you expected '\t' to generate a table anyway. Take a look at this page for a list of common escape sequences in C and C++. You can get a more complete picture by looking at the ASCII chart if you wish.

 

Despite its relatively short length I spotted a few more serious flaws in your code which I did not address above. I recommend that you completely throw it out, and start again based on your hopefully-more-thorough understanding of the problem.

 +xorangekiller,

 

You are right, I do not really understand C, or rather programming in general....this is a learning experience for me and unfortunately it is coming at me faster than I am understanding it.  I understand that \t is a horizontal tab, I get that, but I'm not quite sure how to do this one.  I now am getting run time errors, so I'm closer to solving this puzzle than I was before, and for your insight I thank you.  Code is hard for me to understand, and honestly it has been a lot of trial and error, including completely restarting from scratch.  So far this is what I have, but I'm not understanding how to do the printf statement.

#include "stdio.h"

void main()
{
	int i;

	for(i = i + 3; i < 18; i+=3)
		{
			if (i % 3 == 0)
		printf("\t 'A'", "%d");
			if (i % 3 != 0)
	continue;
			printf("\n");
	}
}

And I tried to adjust the for statement with the i+=3, but it is still producing a run time error, which I assume is because of something later on in the code? 

  • 0

Okay,

 

Now I have no run time errors but this is my output and here is what I have.  I'm still not sure how to use the \t function....

#include "stdio.h"

void main()
{
	int i;

	for(i = 0; i < 18; i+=3)
		{
			if (i % 3 == 0)
		printf("\t 'A %d","\t 'A+2' %d", "\t 'A+3' %d", "\t 'A+4' %d", i,i,i,i);
			if (i % 3 != 0)
	continue;
			printf("\n");
	}
}

But at least now I'm getting some sort of a print out.  Do I need to use multiple printf statements to get the output in the correct format? 

post-505691-0-50087300-1379885002.png

  • 0
  On 22/09/2013 at 21:36, notchinese said:

Also, since when does 18 + 3 = 22? (your table in the first post)

LOL!  I'm not sure what my professor was thinking when he made this assignment question to be honest.  I'm not following his logic very well let alone the logic of C.  I'm sorry to keep posting but I'm trying to work though this as much as possible.  So...with that being said this is what I have:


	int i;

	for(i = 0; i < 18; i+=3)
		{
			if (i % 3 == 0)
				printf("\t 'A' \t 'A+2' \t 'A+3' \t 'A+4'", i);
			printf("\n");
			continue;
			if (i % 3 != 0)
				printf("%d");
	
			printf("\n");
	}
}

And this is what it's doing:

 

At least now I'm getting somewhat of the formatting that is required.  I'm obviously not getting this at all unfortunately.  Just pretend that you're explaining this to a child, then maybe I'll understand this because I'm completely lost. 

 

Do I need to first initialize a printf statement before the first if statement to get the headers when I'm using the \t? 

post-505691-0-99653400-1379886042.png

  • 0

You are getting closer, but still missing some important concepts. Taking into account the advice in the posts above, you should be able to surmise the following algorithm:

PRINT_HEADER

FOR_LOOP
        PRINT A
        PRINT_TAB
        
        PRINT A + 2
        PRINT_TAB
        
        PRINT A + 3
        PRINT_TAB
        
        PRINT A + 4
        PRINT_NEWLINE

The proper algorithm will get you half way there. Your current issue seems to be evenly split between misunderstood syntax and faulty logic. I recommend that you read the printf() documentation in particular.

  • 0

OkIi used

printf("\t A \t A+2 \t A+3 \t A+4");
	printf("\n");

and it gave me the headers for the columns and I put it before the for loop.  Now I'm trying to get the printouts under those headers.  And now that I noticed the math is completely wrong, 6 + 4 != 12....hmmm.  Or am I reading the problem wrong?  Is each A+# the original number in A + whatever number is associated by A?

  • 0
  On 22/09/2013 at 21:56, Terabojin said:

And now that I noticed the math is completely wrong, 6 + 4 != 12....hmmm.  Or am I reading the problem wrong?  Is each A+# the original number in A + whatever number is associated by A?

Based on your initial description I think you are supposed to be computing the result of the three latter columns (A + 2, A + 3, and A + 4) based on the contents of the multiple-of-three-number in the first column (referred to as A in your header and assigned to i in your loop). For example, if i=3 then A=3, A+2=5, A+3=6, and A+4=7.

  • 0
  On 22/09/2013 at 22:05, xorangekiller said:

Based on your initial description I think you are supposed to be computing the result of the three latter columns (A + 2, A + 3, and A + 4) based on the contents of the multiple-of-three-number in the first column (referred to as A in your header and assigned to i in your loop). For example, if i=3 then A=3, A+2=5, A+3=6, and A+4=7.

 

 

Okay let me see if I'm understanding this correctly. 

 

Basically I should be doing:

 

if (A=i)

A+2=i, A+3=i, A+4=i;

correct?

 

  • 0
  On 22/09/2013 at 22:07, Terabojin said:

Okay let me see if I'm understanding this correctly. 

 

Basically I should be doing:

 

if (A=i)

A+2=i, A+3=i, A+4=i;

correct?

 

 

What?! Where did you get that from? Isn't there a math prerequisite for your programming class?

 

If (A=i)

A+2=i+2, A+3=i+3, A+4=i+4

  • 0
  On 22/09/2013 at 22:11, xorangekiller said:

What?! Where did you get that from? Isn't there some math prerequisite for your programming class?

 

If (A=i)

A+2=i+2, A+3=i+3, A+4=i+4

Okay I missed that, sorry for the airheaded math...just been at this problem for a long time and obviously not thinking clearly.  I do apologize for the mathematical errors.  And again,thank you for all of your help.

  • 0

Testing for i to be a multiple of 3 is useless since you start i at 0 and increment by 3. You can (and should) write this program without ifs, continues, or breaks.

 

printf only ever takes one format string. The additional arguments must correspond to the format specifiers contained in the string (characters preceded by %).

  • 0

It's probably worth breaking down your problem into smaller chunks. Try these, all as smaller programs.

1: Print the header.

So the first thing that you're required to do is print the header. Now, the header only needs to be printed once, therefore we don't need to print the header inside a loop! Just print it once before you create a loop!

My Recommendation: write a program that prints ONLY the header, and only do it once.

2: Create a loop.

Next, have a go at creating the loop. So your for loop should start at a specific number, and increment in multiples of three (e.g. 6, 9, 12, 15, 18). You don't just have to use the "++" operator to increment your variable, you can do this too:

 

// Create a loop that increments by 10 every time...
int index;
for (index = 0; index <= 50; index += 10) {
    printf("%d", index);
}

// Output:
// "0"
// "10"
// "20"
// "30"
// "40"
// "50"
Do you see how the output was created? The variable "index" was passed into the printf function as a parameter, and the printf function replaced the "%d" with the value of "index".

See if you can just do this with a loop incrementing by three every time. Don't worry about any table data at the minute.

3: Print some output that accepts more than one number

Next, try to create a program that, like #1 above, only prints one line, but prints multiple numbers worked out using some variables. Remember how the loop program above used "%d" instead of a number, and then we passed the number in? The same concept applies for as many numbers as you like. So you can create a printf statement that looks like this:

 

int i = 1;
int j = 2;
int k = 4;
printf("%d %d %d", i, j, k);

// Output:
// 1 2 4
4: Put it all together

So now what do you have? You've got three little programs that do three things:

  • Prints a static line of text.
  • Prints a set of numbers in a loop.
  • Prints a line containing multiple numbers.
How you can put all this code together to solve your problem I'll leave as an exercise to you. Hopefully by the end of the third program you'll already know what you have to do.


If you're up for some constructive criticism, I've got a couple of pointers based on your initial code:

Tip #1: Indent your code correctly

I know it might seem a bit silly being strict on indenting your code, but it really helps you to read it later. Indenting code inside curly braces (i.e. { and }) allows you to see what block of code a function sits inside.

Check out how much easier it is to read your original code with better formatting:

 

#include "stdio.h"

void main()
{
    int i;

    for(i = i + 3; i < 18; i++)
    {
        if (i % 3 == 0)
            printf("\t 'A'","%d", &i);

        if (i % 3 != 0)
            continue;

        printf("\n");
    }

    for(i = i + 3; i < 20; i++)
    {
        if (i % 3 == 0)
            printf("\t 'A+2", "%d", i);

        if (i % 3 != 0)
            continue;

        printf("\n");
    }
}

Tip #2: Don't forget about 'else'

The else statement is your friend, don't forget to call him every now and then! You don't need to check if "i % 3 == 0" and then in the next line check if the opposite is true (i.e. "i % 3 != 0"), because you can just use an else...

// Do this if i is a multiple of three...
if (i % 3 == 0)
    printf("\t 'A+2", "%d", i);

// ... otherwise do this...
else
    continue;
Tip #3: Remember to initialize your variables!

In C, your numbers won't have a defined value by default, so there's no guarantee that your number will start at zero. Remember to set your variable to zero (or another appropriate value) before you start using it, otherwise, as Asik said, you'll run into undefined behaviour, and nobody wants that!

int i; // <-- BAD! i could be "0", but it could also be "12654151", because you haven't told it what to be!
int j = 0; // <-- GOOD! j will definitely be zero the first time you use it.
  • Like 2
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Back to School 2025 Nvidia gaming laptop deals list from Gigabyte, MSI and Acer by Sayan Sen The Back To School sales for 2025 are currently live with several laptops from MSI, Gigabyte, and Acer. These are gaming as well as studio laptops powered by Nvidia GPUs. A wide range of laptops ranging from $700 all the way up to $3000 are available. MSI has the most devices available while Gigabyte also has plenty in the list to choose from. Acer laptops and its trusty Predator machines are there too. Check the full list of discounts below: GIGABYTE - AORUS MASTER 16 Gaming Laptop - 240Hz 2560x1600 OLED - NVIDIA GeForce RTX 5090 - Intel Core Ultra 9 275HX - 2TB SSD with 32GB DDR5 RAM - Windows 11 Home AD (AORUS MASTER 16 BZHC6USE65SH) + Intel CPU Spring Bundle worth $159.99 for free: $3899.99 + $50 rebate => $3849.99 (Shipped and Sold by Newegg US) MSI - 18" GeForce RTX 5080 Laptop GPU - Intel Core Ultra 9 285HX - 64GB DDR5 6400MHz Memory - 4 TB SSD - Windows 11 Home - Gaming Laptop - 120 Hz Mini LED (Raider 18 HX AI A2XWIG-014US ) + Intel CPU Spring Bundle worth $159.99 for free: $3779.99 (Shipped and Sold by Newegg US) MSI Vector - 16" GeForce RTX 5080 Laptop GPU - Intel Core Ultra 9 275HX - 32GB Memory - 2 TB SSD - Windows 11 Pro - Gaming Laptop - 240 Hz (Vector 16 HX AI A2XWIG-058US ) + Intel CPU Spring Bundle worth $159.99 for free: $2799.99 (Shipped and Sold by Newegg US) MSI - 16" GeForce RTX 5070 Ti Laptop GPU - Intel Core Ultra 9 275HX - 32GB Memory - 2 TB SSD - Windows 11 Pro - Gaming Laptop - 240 Hz (Vector 16 HX AI A2XWHG-060US ) + Intel CPU Spring Bundle worth $159.99 for free: $2549.99 (Shipped and Sold by Newegg US) MSI Summit Pro 16 16" Touchscreen Laptop Intel Ultra 7 255H GeForce RTX 4050 32GB Memory 1 TB NVMe SSD Windows 11 Home Summit Pro 16 AI A2HVETG-074US: $1349.99 (Shipped and Sold by Newegg US) Aorus - 16" GeForce RTX 4060 Laptop GPU - Intel Core i7-13700HX - 16GB Memory - 1 TB PCIe SSD - Windows 11 Home 64-bit - Gaming Laptop - 240 Hz (16 BKF-73US654SH ): $1199.99 (Shipped and Sold by Newegg US) MSI Creator M14 14” 2.8K Display Creator Laptop: Intel Core i7-13620H, NVIDIA Geforce RTX 4050, 16GB DDR5, 1TB NVMe SSD, Cooler Boost, Win 11: Black A13VE-083US: $999.99 (Shipped and Sold by Amazon US) MSI Thin A15 B7V Thin A15 B7VE-214US 15.6" Gaming Notebook - Full HD - AMD Ryzen 7 7735HS - 16 GB - 512 GB SSD - Cosmos Gray - AMD Chip - 1920 x 1080 - Windows 11 - NVIDIA GeForce RTX 4050: $929.00 (Shipped and Sold by Newegg US) MSI Thin A15 B7U Thin A15 B7UC-473US 15.6" Gaming Notebook - Full HD - AMD Ryzen 5 7535HS - 16 GB - 512 GB SSD - Black - AMD Chip - 1920 x 1080 - Windows 11 Home - NVIDIA GeForce RTX 3050: $909.00 (Shipped and Sold by Newegg US) MSI Cyborg - 15.6" GeForce RTX 4050 Laptop GPU - Intel i7-13620H - 16GB Memory - 512 GB SSD - Windows 11 Home - Gaming Laptops - 144 Hz IPS (A13VE-218US ): $849.99 (Shipped and Sold by Newegg US) Acer Nitro V - 15.6" GeForce RTX 4050 Laptop GPU - Intel Core i7-13620H - 16GB Memory - 512 GB PCIe SSD - Windows 11 Home - 144 Hz IPS - Gaming Laptop with Acer Gaming Controller (ANV15-51-717H ): $839.99 (Shipped and Sold by Newegg US) Aorus - 15.6" GeForce RTX 4050 Laptop GPU - Intel Core i5-12500H - 8GB Memory - 512 GB PCIe SSD - Windows 11 Home 64-bit - Gaming Laptop - 360 Hz (15 9MF-E2US583SH ): $699.99 (Shipped and Sold by Newegg US) As an Amazon Associate and Newegg Affiliate Partner, we earn from qualifying purchases.
    • I'd say this is hardly news. A GUI wrapper is not exactly some grand accomplishment. Even ClamAV itself is of questionable use. I suppose it lets you check the box on an audit questionnaire that a server has virus protection. But Linux has always been a more difficult target for malware because of the wide variety of distros, library versions, etc. And also the fact that it has a much smaller user base consisting of users who are generally more knowledgeable.
    • Privacy nightmare... And, yes, I know, there's an On/Off toggle. But like Edward Snowden once said : "Where there's an On/Off toggle, there's always a way to turn it on." 😉 Microsoft is also working on letting Copilot tap into your history and credentials so that it can better understand context and perform actions on your behalf
    • Looks like "LoucheBear" should be renamed "DoucheBear". Ignorant ######.
    • The dev is a snowflake for deciding that a project he’s not getting paid to do isn’t worth the attacks? Interesting.
  • Recent Achievements

    • Week One Done
      NeoWeen earned a badge
      Week One Done
    • One Month Later
      BA the Curmudgeon earned a badge
      One Month Later
    • First Post
      Doreen768 earned a badge
      First Post
    • One Month Later
      James_kobe earned a badge
      One Month Later
    • Week One Done
      James_kobe earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      656
    2. 2
      ATLien_0
      253
    3. 3
      Xenon
      167
    4. 4
      neufuse
      146
    5. 5
      +FloatingFatMan
      121
  • Tell a friend

    Love Neowin? Tell a friend!