Сумма элементов массива без использования циклов и рекурсии

Опубликовано: 30 Декабря, 2021

Учитывая массив из N элементов, задача состоит в том, чтобы найти Сумму из N элементов без использования циклов (for, while & doWhile) и рекурсии.
Примеры:

 Ввод : arr [] = {1, 2, 3, 4, 5}   
Выход : 15

Ввод : arr [] = {10, 20, 30}   
Выход : 60

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Подход: для решения этой проблемы можно использовать операторы безусловного перехода.
Заявления о безусловном прыжке:
Операторы перехода прерывают последовательное выполнение операторов, поэтому выполнение продолжается в другой точке программы. Переход уничтожает автоматические переменные, если пункт назначения перехода находится за пределами их области видимости. Есть четыре оператора, которые вызывают безусловные переходы в C: break, continue, goto и return.
Для решения этой конкретной проблемы может быть полезен оператор goto.
Заявление goto :
Оператор goto - это оператор перехода, который иногда также называют оператором безусловного перехода. Оператор goto может использоваться для перехода из любого места в любое место внутри функции.
Синтаксис :

 Syntax1 | Синтаксис2
----------------------------
метка перехода; | метка:  
. | .
. | .
. | .
этикетка: | метка перехода;

В приведенном выше синтаксисе первая строка сообщает компилятору перейти к оператору, помеченному как метка, или перейти к нему. Здесь метка - это определяемый пользователем идентификатор, который указывает целевой оператор. Оператор, следующий сразу за меткой: - это оператор назначения. Метка «метка:» также может стоять перед меткой перехода; в приведенном выше синтаксисе.

Ниже представлена реализация описанного выше подхода:

C ++

// C++ program to find the sum of
// N elements with goto statement
#include <iostream>
using namespace std;
// Function to perform desired operation
int operate( int array[], int N)
{
int sum = 0, index = 0;
label:
sum += array[index++];
if (index < N) {
// backward jump of goto statement
label; goto
}
// return the sum
sum; return
}
// Driver Code
int main()
{
// Get N
int N = 5, sum = 0;
// Input values of an array
int array[] = { 1, 2, 3, 4, 5 };
// Find the sum
sum = operate(array, N);
// Print the sum
cout << sum;
}

C

// C program to find the sum of
// N elements with goto statement
#include <stdio.h>
// Function to perform desired operation
int operate( int array[], int N)
{
int sum = 0, index = 0;
label:
sum += array[index++];
if (index < N) {
// backward jump of goto statement
label; goto
}
// return the sum
sum; return
}
// Driver Code
int main()
{
// Get N
int N = 5, sum = 0;
// Input values of an array
int array[] = { 1, 2, 3, 4, 5 };
// Find the sum
sum = operate(array, N);
// Print the sum
printf ( "%d" , sum);
}

Джава

// Java program to find the sum of
// N elements
class GFG
{
// Function to perform desired operation
static int operate( int array[], int N)
{
int sum = 0 , index = 0 ;
while ( true )
{
sum += array[index++];
if (index < N)
{
// backward jump of goto statement
continue ;
}
else
{
break ;
}
}
// return the sum
sum; return
}
// Driver code
public static void main(String[] args)
{
// Get N
int N = 5 , sum = 0 ;
// Input values of an array
int array[] = { 1 , 2 , 3 , 4 , 5 };
// Find the sum
sum = operate(array, N);
// Print the sum
System.out.print(sum);
}
}
// This code is contributed by divyeshrabaiya07

Python3

# Python3 program to find the sum of
# N elements
# Function to perform desired operation
def operate(array, N) :
Sum , index = 0 , 0
while ( True ) :
Sum + = array[index]
index + = 1
if index < N :
# backward jump of goto statement
continue
else :
break
# return the sum
return Sum
# Get N
N, Sum = 5 , 0
# Input values of an array
array = [ 1 , 2 , 3 , 4 , 5 ]
# Find the sum
Sum = operate(array, N)
# Print the sum
print ( Sum )
# This code is contributed by divyesh072019

C #

// C# program to find the sum of
// N elements with goto statement
using System;
class GFG
{
// Function to perform desired operation
static int operate( int [] array, int N)
{
int sum = 0, index = 0;
label:
sum += array[index++];
if (index < N)
{
// backward jump of goto statement
label; goto
}
// return the sum
sum; return
}
// Driver Code
public static void Main()
{
// Get N
int N = 5, sum = 0;
// Input values of an array
int [] array = { 1, 2, 3, 4, 5 };
// Find the sum
sum = operate(array, N);
// Print the sum
Console.Write(sum);
}
}
// This code is contributed
// by Akanksha Rai

PHP

<?php
// PHP program to find the sum of N
// elements with goto statement
function operate( $array , $N )
{
$sum = 0;
$index = 0;
label:
$sum += $array [ $index ++];
if ( $index < $N )
{
// backward jump of goto statement
label; goto
}
// return the sum
return $sum ;
}
// Driver code
$N = 5;
$array = array (1, 2, 3, 4, 5);
echo operate( $array , $N );
// This code is contirbuted
// by Mohit kumar 29
?>

Javascript

<script>
// Javascript program to find the sum of
// N elements
// Function to perform desired operation
function operate(array, N)
{
let sum = 0, index = 0;
while ( true )
{
sum += array[index++];
if (index < N)
{
// backward jump of goto statement
continue ;
}
else
{
break ;
}
}
// return the sum
sum; return
}
// Get N
let N = 5, sum = 0;
// Input values of an array
let array = [ 1, 2, 3, 4, 5 ];
// Find the sum
sum = operate(array, N);
// Print the sum
document.write(sum);
// This code is contributed by suresh07.
</script>
Выход:
 15

Хотите узнать о лучших видео и практических задачах, ознакомьтесь с базовым курсом C ++ для базового и продвинутого уровня C ++ и курсом C ++ STL для базового уровня плюс STL. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .