print out all pairs of natural numbers whose sum isequal to the entered number n
Write an algorithm that prints out all pairs of natural numbers whose sum is
equal to the entered number n.
Example:
n = 7
Paris:
0 + 7
1 + 6
2 + 5
3 + 4
I have no clue how to introduce it into c# lang
20 Replies
Do you know how to get 'the entered number'?
yes i know that, like i know basics of c# but I dont have idea for this task
Well get started on it, then come back with where you're actually stuck
Are you sure you're stuck on the c#? Or perhaps it's actually the algorithm?
My issue is actually algorithm. I can't figure it out
i was able to print all pairs but they were not unique so for n = 7 i got
0 + 7
1 + 6
2 + 5
3 + 4
4 + 3
5 + 2
6 + 1
7+ 0
instead of
0 + 7
1 + 6
2 + 5
3 + 4
Aha
Well there's two relationships that can solve they problem for you
Compare one number in the pair to the other, which is bigger?
That's one way. Or count how many pairs you've made compared to the input
Note that numbers start repeating exactly in the middle of your output
okay i have something like that and i think its works well could you review it please?
That look overly complex
This seems a bit overkill. Unless there were more conditions for this problem?
You're still overcomplicating it. Also you can define tuples like
(int, int)
and you can create them like this: (1, 2)
You don't really need to store your values anywhere, you just need to output them. Try to compute the values you need to show right there in your for
loop.
what you think?
This can be accomplished with a single for loop. Try applying this suggestion from @R.
you can just put
i <= n / 2
in you for
loop conditionoh yeah
Also, I'd recommend
int.Parse
instead of Convert.ToInt32
or even int.TryParse
so you can handle invalid input
what is the difference betweene parse and convert
?
Convert.ToInt32
will return 0 if the input is null
, int.Parse
will throw an exception
int.Parse
also doesn't require using System
, but that's not much of an advantage
and if you use int.TryParse
you can display an error message when input isn't an integerTHANKS!