The Wayback Machine - https://web.archive.org/web/20240909131536/https://www.geeksforgeeks.org/program-to-find-the-magnitude-of-a-vector/
Open In App

Program to find the Magnitude of a Vector

Last Updated : 11 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given three integers representing the X, Y, and Z coordinates of a 3-D vector, the task is to find the magnitude of that vector.

Example:

Input: X = 1, Y = 2, Z = 2
Output: 3
Explanation: Magnitude of the vector is equal to ?9 =3

Input: X = 0, Y = 4, Z = 3
Output: 5

Approach: The magnitude of a vector can be calculated by solving the equation ?(X2 + Y2 + Z2). Follow the steps below to solve the problem:

  • Stores the sum of the squares of the X, Y and Z coordinates in a variable, say sum.
  • Initialize a variable, say magnitude, to store the square root of sum.
  • Print the value of magnitude as the required result.

Below is the implementation of the above approach:

C++14




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate magnitude
// of a 3 dimensional vector
float vectorMagnitude(int x, int y, int z)
{
    // Stores the sum of squares
      // of coordinates of a vector
    int sum = x * x + y * y + z * z;
   
      // Return the magnitude
    return sqrt(sum);
}
 
// Driver Code
int main()
{
    int x = 1;
    int y = 2;
    int z = 3;
   
    cout << vectorMagnitude(x, y, z);
   
    return 0;
}


Java




// Java program for the above approach
class GFG{
     
// Function to calculate magnitude
// of a 3 dimensional vector
private static double vectorMagnitude(int x, int y,
                                      int z)
{
     
    // Stores the sum of squares
    // of coordinates of a vector
    int sum = x * x + y * y + z * z;
 
    // Return the magnitude
    return Math.sqrt(sum);
}
 
// Driver code
public static void main(String[] args)
{
    int x = 1;
    int y = 2;
    int z = 3;
     
    System.out.print(vectorMagnitude(x, y, z));
}
}
 
// This code is contributed by abhinavjain194


Python3




# Python3 program for the above approach
from math import sqrt
 
# Function to calculate magnitude
# of a 3 dimensional vector
def vectorMagnitude(x, y, z):
     
    # Stores the sum of squares
    # of coordinates of a vector
    sum = x * x + y * y + z * z
     
    # Return the magnitude
    return sqrt(sum)
         
# Driver code   
x = 1
y = 2
z = 3
 
print(vectorMagnitude(x, y, z))
 
# This code is contributed by abhinavjain194


C#




// C# program for the above approach
using System;
 
class GFG{
     
// Function to calculate magnitude
// of a 3 dimensional vector
private static double vectorMagnitude(int x, int y,
                                      int z)
{
     
    // Stores the sum of squares
    // of coordinates of a vector
    int sum = x * x + y * y + z * z;
 
    // Return the magnitude
    return Math.Sqrt(sum);
}
 
// Driver code
static void Main()
{
    int x = 1;
    int y = 2;
    int z = 3;
     
    Console.Write(vectorMagnitude(x, y, z));
}
}
 
// This code is contributed by abhinavjain194


Javascript




<script>
 
// Javascript program for the above approach 
 
// Function to calculate magnitude
// of a 3 dimensional vector
function vectorMagnitude(x, y, z)
{
     
    // Stores the sum of squares
    // of coordinates of a vector
    var sum = x * x + y * y + z * z;
 
    // Return the magnitude
    return Math.sqrt(sum);
}
 
// Driver Code
var x = 1;
var y = 2;
var z = 3;
 
document.write(vectorMagnitude(x, y, z));
 
// This code is contributed by Ankita saini
 
</script>


Output

3.74166







Time Complexity: O(1)
Auxiliary Space: O(1)

Using the mathematical formula for magnitude:

Approach:

We can find the magnitude of a vector using the mathematical formula:

|V| = sqrt(X^2 + Y^2 + Z^2)

where X, Y, and Z are the components of the vector.

Import the math module for using the sqrt() function.

Get the components of the vector from the user as input using the input() function and store them in the variables X, Y, and Z.

Calculate the magnitude of the vector using the formula |V| = sqrt(X^2 + Y^2 + Z^2) and store it in the variable magnitude.

Print the magnitude of the vector using the print() function.

C++




#include <iostream>
#include <cmath> // Include the math library for sqrt()
 
using namespace std;
 
int main() {
    double X = 0;
    double Y = 4;
    double Z = 3;
 
    // Calculate the magnitude using the formula: sqrt(X^2 + Y^2 + Z^2)
    double magnitude = sqrt(X * X + Y * Y + Z * Z);
 
    // Print the magnitude of the vector
    cout << "The magnitude of the vector is: " << magnitude << endl;
 
    return 0;
}


Java




import java.lang.Math;
 
public class VectorMagnitude {
 
    public static void main(String[] args) {
        double X = 0;
        double Y = 4;
        double Z = 3;
 
        double magnitude = Math.sqrt(X * X + Y * Y + Z * Z);
 
        System.out.println("The magnitude of the vector is: " + magnitude);
    }
}


Python3




import math
 
X = 0
Y = 4
Z = 3
 
magnitude = math.sqrt(X**2 + Y**2 + Z**2)
 
print("The magnitude of the vector is:", magnitude)


C#




using System;
 
public class VectorMagnitude
{
    public static void Main(string[] args)
    {
        double X = 0;
        double Y = 4;
        double Z = 3;
 
        double magnitude = Math.Sqrt(X * X + Y * Y + Z * Z);
 
        Console.WriteLine("The magnitude of the vector is: " + magnitude);
    }
}


Javascript




// Define the components of the vector
const X = 0;
const Y = 4;
const Z = 3;
 
// Calculate the magnitude using the formula: sqrt(X^2 + Y^2 + Z^2)
const magnitude = Math.sqrt(X * X + Y * Y + Z * Z);
 
// Print the magnitude of the vector
console.log("The magnitude of the vector is: " + magnitude);


Output

The magnitude of the vector is: 5.0







Time complexity: O(1)
Auxiliary Space: O(1)



Similar Reads

Check if it is possible to reach vector B by rotating vector A and adding vector C to it
Given three 2-Dimensional vector co-ordinates A, B and C. The task is to perform below operations any number of times on vector A to get vector B : Rotate the vector 90 degrees clockwise.Add vector C to it. Print "YES" B is obtained using the above operations, else Print "NO".Examples: Input: Vector A: 2 3, Vector B: 2 3, Vector C: 0 0 Output: YES
9 min read
How to flatten a Vector of Vectors or 2D Vector in C++
Given a Vector of Vectors (2D vector), the task is to flatten this 2d vector. Examples: Input: vector = [[1, 2, 3, 4], [5, 6], [7, 8]] Output: 1 2 3 4 5 6 7 8 Input: vector = [[1, 2], [3], [4, 5, 6, 8]] Output: 1 2 3 4 5 6 8 Algorithm: 2D Vector can be flattened using iterators.Store starting and ending iterator of every vector in two arrays, iStar
2 min read
Basic Vector Paths in Photoshop Vector Tools
Photoshop is a popular program that has a variety of tools. Some of the most common tools used for digital graphic design are Vector tools. Vector tools are used to create designs that can resize big and small without losing pixels. The most common vector tools are the Pen tool, Shape tool, Type tool, Brush tool, and Eraser tool. Pen Tool: A pen to
4 min read
Program to find frequency of each element in a vector using map in C++
Given a vector vec, the task is to find the frequency of each element of vec using a map. Examples: Input: vec = {1, 2, 2, 3, 1, 4, 4, 5} Output: 1 2 2 2 3 1 4 2 5 1 Explanation: 1 has occurred 2 times 2 has occurred 2 times 3 has occurred 1 times 4 has occurred 2 times 5 has occurred 1 times Input: v1 = {6, 7, 8, 6, 4, 1} Output: 1 1 4 1 6 2 7 1 8
3 min read
Find the mean vector of a Matrix
Given a matrix of size M x N, the task is to find the Mean Vector of the given matrix. Examples: Input : mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Output : Mean Vector is [4 5 6] Mean of column 1 is (1 + 4 + 7) / 3 = 4 Mean of column 2 is (2 + 5 + 8) / 3 = 5 Mean of column 3 is (3 + 6 + 9) / 3 = 6 Input : mat[][] = {{2, 4}, {6, 8}} Output : Mean
6 min read
Find Cumulative Sum Of a List, Vector or Array
Given a list of numbers, the task is to find and return a list with the cumulative sum of given list. Examples : Input: list = [10, 20, 30, 40, 50]Output : [10, 30, 60, 100, 150]Explanation:for cumulative sum, every index of the output list will be list[i] = list[i] + originallist[i], therefore the resultant list will be [10, 10+20, 10+20+30, 10+20
4 min read
Dope Vector
Dope Vectors is a data structure that is used by compilers to store some metadata about the array like its total size, the size of one unit also called stride of the array, etc. These are used to describe arrays and other similar structures that store multiple values of one datatype as a complete block of memory. It can also describe structures tha
2 min read
Advantages of vector over array in C++
We have already discussed arrays and vectors. In this post, we will discuss advantages of vector over normal array. Advantages of Vector over arrays : Vector is template class and is C++ only construct whereas arrays are built-in language construct and present in both C and C++.Vector are implemented as dynamic arrays with list interface whereas ar
6 min read
Keep track of previous indexes after sorting a vector in C++ STL
Prerequisite: vector, vector pair sorting Given a vector, keep track of the present indexes corresponding to each element and after sorting print element with its previous respective indexes. Examples: Input: Arr[] = {2, 5, 3, 7, 1} Output: {1, 4} {2, 0} {3, 2} {5, 1} {7, 3} Explanation: Before sorting [index(element)]: [0(2), 1(5), 2(3), 3(7), 4(1
2 min read
How to store a Sparse Vector efficiently?
A sparse vector is a vector that has a large number of zeros so it takes unwanted space to store these zeroes.The task is to store a given sparse vector efficiently without storing the zeros. Examples: Input: vector = { 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5 }
6 min read
Sort a 2D vector diagonally using Map Data Structure
Given a 2D vector mat[][] of integers. The task is to sort the elements of the vectors diagonally from top-left to bottom-right in increasing order.Examples: Input: mat[][] = {{9, 4, 2}, {7, 4, 6}, {2, 3, 3}} Output: 3 4 2 3 4 6 2 7 9 Explanation: There are 5 diagonals in this matrix: 1. {2} - No need to sort 2. {7, 3} - Sort - {3, 7} 3. {9, 4, 3}
8 min read
Problem solving on Boolean Model and Vector Space Model
Boolean Model: It is a simple retrieval model based on set theory and boolean algebra. Queries are designed as boolean expressions which have precise semantics. Retrieval strategy is based on binary decision criterion. Boolean model considers that index terms are present or absent in a document. Problem Solving: Consider 5 documents with a vocabula
4 min read
Sort vector of Numeric Strings in ascending order
Given a vector of numeric strings arr[], the task is to sort the given vector of numeric strings in ascending order. Examples: Input: arr[] = {"120000", "2", "33"}Output: {"2", "33", "120000"} Input: arr[] = {"120", "2", "3"}Output: {"2", "3", "120"} Approach: The sort() function in C++ STL is able to sort vector of strings if and only if it contai
5 min read
Sorting 2D Vector of Pairs in C++
A 2D vector also known as vector of vectors is a vector in which each element is a vector on its own. In other words, It is a matrix implemented with the help of vectors. What is a 2D vector of pairs? A 2D vector of pairs is a vector in which each element is a vector of pairs on its own. In other words, It is a matrix implemented with the help of v
15+ min read
Create a balanced BST using vector in C++ STL
Given an unsorted vector arr, the task is to create a balanced binary search tree using the elements of the array. Note: There can be more than one balanced BST. Forming any is acceptable Examples: Input: arr[] = { 2, 1, 3}Output: 2 1 3Explanation: The tree formed is show below. The preorder traversal is 2 1 3 2 / \ 1 3 Input: arr[] = {4, 3, 1, 2}O
5 min read
Sorting Vector of Pairs by 1st element in ascending and 2nd element in descending
A pair is a container that stores two values mapped to each other, and a vector containing multiple numbers of such pairs is called a vector of pairs. While solving problems there come many instances where there is a need to sort the elements of vector on the basis of both the first and second elements of the pair. In that instance we have to pass
8 min read
What are the negative aspects of Java Stack class inheriting from Vector?
Java Vector: Vectors are analogous to arrays in a way that both of them are used to store data, but unlike an array, vectors are not homogeneous and don't have a fixed size. They can be referred to as growable arrays that can alter their size accordingly. It is relatively a memory-efficient way of handling lists whose size could change drastically.
2 min read
Smallest value of X not present in given Vector by searching X*K repeatedly
Given a vector vec, and integers X and K, the task is to keep replacing X with product of X and K, each time X is found in the vector. Return the final product which is not present in the vector. Examples: Input: vec = {1, 2, 6, 10}, X = 2, K = 3Output: 18Explanation: Since the original X is 2 which is present in the vector, multiply it by 3 (2*3=6
7 min read
How to implement our own Vector Class in C++?
The given task is to implement a class in C++ which behaves just like the Vector class.Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can b
5 min read
Difference between ArrayList, LinkedList and Vector
ArrayList:Array List is an implemented class of List interface which is present in package java.util. Array List is created on the basis of the growable or resizable array. And Array List is an index-based data structure. In ArrayList, the element is stored in a contiguous location. It can store different data types. And random access is allowed. W
11 min read
Sort Vector of Pairs in descending order in C++
We have discussed some of the cases of sorting vector of pairs in below set 1. Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second) More cases are discussed in this article. Sometimes we require to sort the vector in reverse order. In those instances, rather than first sorting the vector and later using "reverse" function increases the
5 min read
Sorting 2D Vector in C++ | Set 2 (In descending order by row and column)
We have discussed some of the cases of sorting 2D vector in below set 1. Sorting 2D Vector in C++ | Set 1 (By row and column) More cases are discussed in this article Case 3 : To sort a particular row of 2D vector in descending order This type of sorting arranges a selected row of 2D vector in descending order . This is achieved by using “sort()” a
4 min read
Sorting 2D Vector in C++ | Set 3 (By number of columns)
We have discussed some of the cases of sorting 2D vector in below set 1 and set 2.Sorting 2D Vector in C++ | Set 1 (By row and column) Sorting 2D Vector in C++ | Set 2 (In descending order by row and column)More cases are discussed in this articleAs mentioned in one of the article published of this set, A 2D Vector can also have rows with different
4 min read
Convert an Array to reduced form using Vector of pairs
Given an array with n distinct elements, convert the given array to a form where all elements are in range from 0 to n-1. The order of elements is same, i.e., 0 is placed in place of smallest element, 1 is placed for second smallest element, ... n-1 is placed for largest element. Input: arr[] = {10, 40, 20}Output: arr[] = {0, 2, 1}Input: arr[] = {5
11 min read
How to Draw Vector Shapes in Photoshop?
Photoshop is basically a raster-based image editing software developed and published by Adobe Inc. but in Photoshop we can also edit vector images. So in this article, we will learn how to draw different types of vector shapes, such as rectangles, circles, squares, ellipses, etc. We will also learn how to draw our custom shape and how to use the Pr
10 min read
Typographic Designs with Photoshop Vector Tools
Typographic design is the skill of composing a message in a way that is both readable and beautiful. The skill of designing a successful design allows the creator to invite the viewer to pause and focus on significant messages. This design element is important because it helps define the meaning and tone of the brand as well as establish hierarchy,
3 min read
Combine Vector Paths with Photoshop
The vector shape's border is known as a path in Photoshop. One or more straight or curved segments make up a path. The path segments' ends are indicated by anchor points. Each chosen anchor point on curved segments shows one or two direction lines that end in direction points. The size and shape of a curved segment are determined by the locations o
2 min read
File Compression in Photoshop using Vector Tools
We all utilize image compression as a daily tool, thus it's essential. Without it, sending enormous files would take hours, we would be emailing hundreds of megabyte-sized files, our landing page would never load, and navigating the internet would feel like walking through thick mud. But being aware of how and why picture files are compressed might
5 min read
Sort Vector of Pairs in ascending order in C++
What is Vector of Pairs? A pair is a container which stores two values mapped to each other, and a vector containing multiple number of such pairs is called a vector of pairs. Syntax: vector&lt;pair&lt;Type1, Type2&gt;&gt; vecName;Here, Type 1: The data type of the first element of the pair.Type 2: The data type of the second element of the pair.ve
5 min read
Sorting of Vector of Tuple in C++ (Ascending Order)
What is the Vector of a Tuple?A tuple is an object that can hold several elements and a vector containing multiple numbers of such a tuple is called a vector of the tuple. The elements can be of different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed. [GFGTABS] CPP // C++ program to demo
4 min read
Practice Tags :