Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

C#-Ask user to input how many odd numbers to be printed(using array)

array odd numbers user input

This topic has been archived. This means that you cannot reply to this topic.
10 replies to this topic

#1 somethingaboutK

somethingaboutK

    CC Lurker

  • New Member
  • Pip
  • 3 posts

Posted 27 May 2014 - 07:36 PM

I need to create a code that will ask the user to input how many odd numbers to sum up, and will then allocate an array, and fill it with that many odd numbers. This is what I have so far. I'm not sure what I'm doing wrong. Can someone please help me?

 

            Console.WriteLine("How many odd numbers do you want to print out?");

            int n;

            Int32.TryParse(Console.ReadLine(), out n);

            int sum = 0;

            int[] numbers = new int[n];

            for (int i = 0; i < n; i++)

            {

                if (n % 2 != 0)

                {

                    sum += numbers[i];

                }

            }

            Console.WriteLine(sum);



#2 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts

Posted 28 May 2014 - 04:08 AM

You haven't allocated your array with anything.


Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#3 lespauled

lespauled

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1360 posts

Posted 28 May 2014 - 06:47 AM

WP is correct, but I can't help but wonder what the logic is behind this program.

 

Correct me if I'm wrong:

 

You ask the user for the input of how many odd numbers they want printed out.  That is stored in n

 

You initialize an array of the length n, but don't populate it with anything.

 

You then iterate through from 0 to the number of odd numbers requested, and sum up the odd numbers in the array.  But since the array isn't populated, all values are initialized to 0.

 

Thus it's returning 0 as a sum, correct?

 

The reason I'm have a problem wrapping my head around it, is that the number array would need to handle any number of odd numbers requested, so storing them in memory could be troublesome.

 

The solution that I see is either:

 

1. Multiply the items requested by 2, then iterate 1 through the multiplied number and add the odd values.

2. Asking the user for the beginning number and ending number to sum up the negative values.  

2. Using another method that "yield returns" the next odd number.

 

In any case there is no need for the array.  The first two methods are better for beginner programmers.

 

But if you want to learn about the workings of yield, you can see a simple example in my blog: ( http://forum.codecal...le-using-yield/ )


My Blog: http://forum.codecal...699-blog-77241/
"Women and Music: I'm always amazed by other people's choices." - David Lee Roth

#4 somethingaboutK

somethingaboutK

    CC Lurker

  • New Member
  • Pip
  • 3 posts

Posted 28 May 2014 - 11:40 AM

But how I'm going to allocate the array if I dont know the exact numbers to put in it?

 

You haven't allocated your array with anything.



#5 lespauled

lespauled

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1360 posts

Posted 28 May 2014 - 11:49 AM

Did you read my answer?


My Blog: http://forum.codecal...699-blog-77241/
"Women and Music: I'm always amazed by other people's choices." - David Lee Roth

#6 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts

Posted 28 May 2014 - 11:56 AM

But how I'm going to allocate the array if I dont know the exact numbers to put in it?

Unfortunately, I don't know what you're supposed to put in it, either.  All you've indicated is that you're supposed to fill it with odd numbers, but you never indicated which ones. It may be that you're supposed to get them from the user as additional inputs. It may be that you're supposed to make them up out of thin air using a random number generator. I don't know. But you have to get them from someplace.


Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#7 somethingaboutK

somethingaboutK

    CC Lurker

  • New Member
  • Pip
  • 3 posts

Posted 30 May 2014 - 11:34 PM

WP is correct, but I can't help but wonder what the logic is behind this program.

 

Correct me if I'm wrong:

 

You ask the user for the input of how many odd numbers they want printed out.  That is stored in n

 

You initialize an array of the length n, but don't populate it with anything.

 

You then iterate through from 0 to the number of odd numbers requested, and sum up the odd numbers in the array.  But since the array isn't populated, all values are initialized to 0.

 

Thus it's returning 0 as a sum, correct?

 

The reason I'm have a problem wrapping my head around it, is that the number array would need to handle any number of odd numbers requested, so storing them in memory could be troublesome.

 

The solution that I see is either:

 

1. Multiply the items requested by 2, then iterate 1 through the multiplied number and add the odd values.

2. Asking the user for the beginning number and ending number to sum up the negative values.  

2. Using another method that "yield returns" the next odd number.

 

In any case there is no need for the array.  The first two methods are better for beginner programmers.

 

But if you want to learn about the workings of yield, you can see a simple example in my blog: ( http://forum.codecal...le-using-yield/ )

I did actually but your explanation was a bit confusing. and YES it returns the value 0. Btw I do need to use an array. I tried to implement your solution #1 in the code but it didnt worked out. Now answering the question that " A spammer worst nightmare" asked "No the numbers are not random! If the user input the number 5 then it will allocate 1,3,5,7,9, inside the array and then add those numbers ". I'm not supposed to ask the users for this numbers it is supposed to be there in the code somewhere which I cant figure out.


Edited by somethingaboutK, 30 May 2014 - 11:36 PM.


#8 DeadLine

DeadLine

    CC Regular

  • Member
  • PipPipPip
  • 41 posts

Posted 31 May 2014 - 10:01 AM

This example uses a List instead of an array:


	static void Main()
	{
		Console.WriteLine("Count to:");
		int num;
		bool can = int.TryParse(Console.ReadLine(), out num);
		if (!can) return;
		List<int> nums = new List<int>();
		int sum = 0;
		for (int i = 1; i <= num; i += 2)
		{
			nums.Add(i);
			sum++;
		}
		Console.WriteLine("Total number of odd numbers: " + sum);
		foreach (int x in nums)
		{
			Console.WriteLine(x);
		}
		Console.ReadLine();
	}

The list is very simple because you don't need to define the length of the 'array'.

 

This example uses an array(int):

        static void Main()
        {
            Console.WriteLine("Count to:");
            int num;
            bool can = int.TryParse(Console.ReadLine(), out num);
            if (!can) return;
            int[] nums = new int[num/2];
            int sum = 0;
            for (int i = 1; i <= num; i += 2)
            {
                nums[i / 2] = i;
                sum++;
            }
            Console.WriteLine("Total number of odd numbers: " + sum);
            foreach (int x in nums)
            {
                Console.WriteLine(x);
            }
            Console.ReadLine();
        }

Since half of the total numbers will be odd, you can just define your array with the length of only half of what the users writes.

You also don't need to check the MOD because you can change your for-loop to increase with 2 and start with the number 1 which means less calculations and better performance !

 

Here's an example where the user can tell how many odd numbers the system needs to print:
 

static void SayHowMany()
        {
            Console.WriteLine("How many odd numbers:");
            int num;
            bool can = int.TryParse(Console.ReadLine(), out num);
            if (!can) return;
            int[] nums = new int[num];
            int sum = 0;
            for (int i = 1; i <= num * 2; i += 2)
            {
                nums[i / 2] = i;
                sum++;
            }
            Console.WriteLine("Total number of odd numbers: " + sum);
            foreach (int x in nums)
            {
                Console.WriteLine(x);
            }
            Console.ReadLine();
        }

Edited by DeadLine, 31 May 2014 - 10:11 AM.


#9 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts

Posted 31 May 2014 - 10:21 AM

So each space in the array nums[i] needs to contain 2i-1.


Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#10 DeadLine

DeadLine

    CC Regular

  • Member
  • PipPipPip
  • 41 posts

Posted 31 May 2014 - 10:35 AM

Since you're working with odd numbers you basically just need a loop that starts with 1, and adds 2 each time the loop has been completed.

You can do this because of all the numbers, half of them will be odd because the integer type is not infinite and because the user enters a max value. In the real world, if we're working with an infinite amount of numbers, an infinite amount of them will be odd. When the users says that he wants the system to display 5 odd numbers, you need to create a loop that starts with the numer 1 and ends with the number 10 (= input * 2) and i += 2.

 

When the user wants the system to display 10 odd integers, your loop will need to loop 10 times with i set to 1 the max number set to 20 (= input * 2) and i+=2.


Edited by DeadLine, 31 May 2014 - 10:42 AM.


#11 PBJ

PBJ

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 176 posts

Posted 11 June 2014 - 06:47 PM

something,

If you were to implement Python you could do something like this:

#!/usr/bin/python3
def main():
    s = sum(range(1, int(input(("enter N to sum to: "))) + 1, 2))
    print("{}".format(s))
if __name__ == "__main__": main()

Which would output

 

enter N to sum to: 23

144

Now, that I understand the logic, I can now try to implement this in ANSI C, as follows: 

#include <stdio.h>
#include <conio.h>
int main(){
	int n = 0, s = 0, i;
	
	fputs("enter N: ", stdout);
	scanf("%d", &n);

	for (i = 0; i <= n; i++){
		if(i % 2 == 0) { continue; }
		else { s = s + i; }
	}

	printf("sum: %d", s);
	
	getch();
	return 0;
}

and receive the same results:

 

enter N: 23

sum: 144
Now, seeming how C# is like C's grand daughter, this should transfer fairly easy into C# and the previous suggestions should provide more than plenty of explanation as to why I implemented this code.I hope that seeing a more code-specific example(s) will assist you in your studies.

Edited by PBJ, 11 June 2014 - 06:49 PM.





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download