By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,148 Members | 1,250 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,148 IT Pros & Developers. It's quick & easy.

c code

P: 5
i have a test in a couple hours and I need help with a short code for c language.
Mar 7 '07 #1
Share this Question
Share on Google+
6 Replies


P: 5
can i show shome one the code? its only 6 lines long and my test is in 3 hours and i need to know this
Mar 7 '07 #2

Ganon11
Expert 2.5K+
P: 3,652
We can help you understand if you will explain your situation more closely and tell us what you need. Saying "i need the code" is rather ambiguous. I could show you this code:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5.    cout << "Hello World!" << endl;
  6.    return 0;
  7. }
That's 6 lines, so I just answered your question - but somehow I think you wanted something a little more specific.
Mar 7 '07 #3

P: 5
thank you for your reply. this is the code:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.  int i, j;
  6.  int a=0;
  7.   for (i=0;i<3;i++)
  8.    for (j=0;j<2;j++)
  9.        a+=2*i+j-1;
  10.  printf("%d\n", a);
  11.  return 0;
  12. }
me and my partner have been sitting here for damn near 2 hours trying to figure

out how the program gets 9 as an answer. We are thinking your supposed to

do it as a matrices perhaps?
Mar 7 '07 #4

P: 5
nevermind we have it. thanx
Mar 7 '07 #5

Ganon11
Expert 2.5K+
P: 3,652
Well, let's break this down, line by line:

3 int variables are declared: i, j, and a. a is set to 0.

a FOR loop is entered: i = 0; i < 3; i++
a FOR loop is entered: j = 0; j < 2; j++
And in each execution of the inner loop, 2 * i + j - 1 is added to a.

The outer loop executes three times, and for each execution of the outer loop, the inner loop executes twice. SO the total number of operations are 2 * 3 or 6. These operations happen at the (i, j) pairs:

(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)

That is, the previous 6 combinations are the values of i and j, respectively, in each addition. So, with a = 0 at the start,

a = a + (2 * i + j - 1)
a = 0 + (2 * 0 + 0 - 1)
a = 0 + (0 - 1)
a = -1

After the first execution, a is -1. Then the next addition comes:

a = a + (2 * i + j - 1)
a = -1 + (2 * 0 + 1 - 1)
a = -1 + (0 + 0)
a = -1

After the second execution, a is still -1.

Continue doing this step by step for the last 4 (i, j) pairs to see what a ends up as.
Mar 7 '07 #6

P: 5
thats a real good xplanation, thanx gannon
Mar 7 '07 #7

Post your reply

Sign in to post your reply or Sign up for a free account.