Coding Problem/프로그래머스

[프로그래머스/Lv1] - 내적

마탁이 2021. 4. 25. 19:33

programmers.co.kr/learn/courses/30/lessons/70128

 

코딩테스트 연습 - 내적

길이가 같은 두 1차원 정수 배열 a, b가 매개변수로 주어집니다. a와 b의 내적을 return 하도록 solution 함수를 완성해주세요. 이때, a와 b의 내적은 a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1] 입니다. (n은 a, b의

programmers.co.kr

  • 간단한 for()를 이용한 계산식 문제

더보기
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// a_len은 배열 a의 길이입니다.
// b_len은 배열 b의 길이입니다.
int solution(int a[], size_t a_len, int b[], size_t b_len) {
    int answer = 1234567890;

    int sum = 0;
    for (int idx = 0; idx < a_len; idx++)
    {
        const int aVal = a[idx];
        const int bVal = b[idx];
        const int abVal = aVal * bVal;
        sum += abVal;
    }

    answer = sum;

    return answer;
}

int main()
{
    int a[] = { 1,2,3,4 };
    int a_len = sizeof(a) / sizeof(int);
    int b[] = { -3,-1,0,2 };
    int b_len = sizeof(b) / sizeof(int);
    
    int ans = solution(a, a_len, b, b_len);
    printf("%d\n", ans);

    return 0;
}