Tips on transitioning from solving problems in JavaScript to C# programming

Currently, I am working on a coding exercise that involves finding the sum of multiples of 3 and 5 below a given number.

The task is to create a function called ThreeFiveMultiples(num) that will calculate this sum. For instance, if the input num is 10, the multiples of 3 and 5 below 10 are 3, 5, 6, and 9, totaling 23. Therefore, the program should return 23. The input integer will always be between 1 and 100.

I am struggling with my C# solution as it keeps throwing an error: System.IndexOutOfRangeException: Index was outside the bounds of the array.

using System;
using System.Linq;

class MainClass {

  public static int ThreeFiveMultiples(int num) {
  
    int[] array = new int[] {};

    for(var i = num-1; i > 1; i--)
    {
      if(i % 5 == 0 || i % 3 == 0)
      {
        array[i] = i;
      }
    }

    return array.Sum();
  }

Here is a different approach using JavaScript:

function ThreeFiveMultiples(num) { 
    var arr = [];
    var tot=0;
   for(var i=num-1; i>1; i--){
        if(i % 5 === 0 || i % 3 === 0){
            arr.push(i);
        }
    }
    for(var i=0; i < arr.length; i++){
        tot = tot + arr[i];
    }
    return tot;
}

Answer №1

When working with javascript, the array.push method is used to expand the size of the array and insert new elements.

In contrast, C# does not support this. Instead, utilize List which can be easily converted to an array if necessary.

public static int GenerateThreeFiveMultiples(int number) {

    List<int> multiples = new List<int>();

    for(var i = number-1; i > 1; i--)
    {
        if(i % 5 == 0 || i % 3 == 0)
        {
            multiples.Add(i);
        }
   }
    
    // Converting to an array just because.
    int[] array = multiples.ToArray();

    return multiples.Sum(num => num);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to changing CSS style dynamically using AngularJS

<div style="width: 50px !important"> I am looking for a way to dynamically set the pixel number using angularjs. The final width should be calculated based on a base pixel width as well. How can I make this happen? <div ng-style="{{width: (model ...

How can we convert multiple arrays into a single JSON object?

I have multiple arrays like the ones shown below: var a=[1,2,3,4,5,6,7,8,9]; var b=["a","b","c","d","e","f","g","h","i","j"]; However, I need to convert these arrays into an array object structured like this: ab=[ ["1","a"], ...

Steering clear of using relative paths for requiring modules in Node.js

When it comes to importing dependencies, I like to avoid using excessive relative filesystem navigation such as ../../../foo/bar. In my experience with front-end development, I have found that using RequireJS allows me to set a default base path for "abso ...

bootstrap 4 - logo in navbar brand stays the same even when scrolling

I integrated Bootstrap 4 and successfully created a navbar. However, I am encountering a conflict when trying to change the navbar logo upon scrolling down. Despite my efforts, it is not functioning as expected. Does anyone know how to resolve this issue? ...

Identifying the length of a division element following its addition

I'm facing difficulties in detecting the length and index of the dynamically appended div. I have researched extensively and found a solution involving MutationObservers, but I am unsure if it is necessary for this particular issue. Let's focus ...

What causes an asynchronous function to exhibit different behavior when utilized in conjunction with addEventListener versus when manually invoked?

I was delving into the concepts of async and await keywords and decided to create a basic demonstration using an HTML file and a corresponding JS file. In my example, I defined two promises - promise1 and promise2. The handlePromises function uses async/ ...

Sending a variable to a template in AngularJS

I am looking for a way to pass a variable or text to a template in order to display the value within my template. While browsing through resources, I found an example on jsFiddle that demonstrates this functionality using ng-repeat. However, I am curious ...

Utilizing JQuery's serialize method to transfer form data to an ASP.NET MVC controller without the need to actually submit the form

Currently developing an ASP.NET MVC application that includes a form with multiple buttons to submit the data. One specific button needs to send the current status of the form's controls to the controller without actually submitting the whole form. My ...

Tips for preventing the extraction of resolve from promises and initiating a process before a callback

There is a common pattern I frequently find myself using: const foo = () => { const _resolve; const promise = new Promise(resolve => _resolve = resolve); myAsyncCall(_resolve); return (dataWeDontHaveYet) => promise.then(cb => c ...

Tooltip Bootstrap timing

I am currently working on creating a navigation bar with icon-only buttons that display tooltips when touched or tapped. Here is the code I have implemented: $('a[rel="tooltip"]').tooltip({ animated: 'fade', placement: ' ...

The angular datepicker functionality seems to be malfunctioning

unique-example encountering this error message: error TS2307: Cannot find module 'mydatepicker' also encountering a compile time error at this line: import { MyDatePickerModule } from 'mydatepicker'; report.module.ts : import ...

Interactive canvas box in motion with directional arrows

I am attempting to create a basic canvas box that moves using arrow keys. Here is the code: Here's the code snippet: $(function() { var n = 3; var xD = 0; var yD = 0; var canvas = document.getElementById("canvas"); var ctx = canvas.getCon ...

Using jQuery, you can easily pass an array in an AJAX request

I am working on a form that has multiple identical fields: <input type="text" id="qte" value="" name="qte[]"> How can I pass the array to my file processing? I have observed that the array sent via ajax is converted into a string. $("#form_comman ...

Error: Invalid syntax detected: /blog

I am encountering an issue with jQuery while trying to add a blog section to my existing single-page site. The new blog will be located in a separate /blog directory, causing the menu item for it to differ from the other href="#" tags on the index.html pag ...

Using the axios response to assign data object in VueJS

When making an API call, I am receiving an expected error. While I am able to log the error message in the console, I am encountering issues trying to set a vuejs data variable with the response. Can anyone point out what I might be doing incorrectly? ...

Function executed prior to populating $scope array

I encountered an issue with AngularJS involving a function that is called before the data array is filled. When the function is invoked in ng-init, the $scope.bookings array is not yet populated, resulting in empty data. My objective is: Retrieve all book ...

Tips for preventing Uncaught SecurityError: Blocking a frame with origin in phonegap

I'm in the process of developing a phonegap application that serves as a miniature browser for a client's website. This app will allow the client's customers to access their favorite pages with ease. Once a user selects a favorite, it will b ...

A guide to showcasing data within PrimeNG's pie chart component using either JavaScript or Angular

I have utilized the pie chart feature from the PRIMENG CHART PLUGIN My goal is to showcase the values within a pie chart Below, you can find my code for reference **Within app.component.html** <div style="display: block"> <p-chart type="pi ...

Updating an embedded object in JavaScript

This is the initial dataset const data = { "field1": { "name": 'Anuv', "marks": { "eng": 43, "hindi": 23 }, "age": 21 }, ...

Angular template fails to reflect changes after manipulating objects

There is an object defined as: $scope.allSessions = { set: {}, pending: [] }; Subsequently, a method is used to populate the set property with multiple objects like this: "2014-06-07-11-30": { blah blah } This results in a list of dates bei ...