text:
The Pedant's Cosine
My boss just told me to write a cosine function. Being a good math geek, my mind immediately conjured the appropriate Taylor Series.
$$\cos(x) = \frac 1 {0!} - \frac {x^2} {2!} + \frac {x^4} {4!} - \frac {x^6} {6!} + \cdots + \frac{(-1)^k \times x^{2k}} {(2k)!} + \cdots$$
However, my boss is very picky. He would like to be able to specify exactly how many terms of the Taylor Series to compute. Can you help me write this function?
Your Task
Given a floating point value \$x\$ from \$0\$ to \$2\pi\$ and a positive integer \$n\$ less than \$100\$, compute the sum of the first \$n\$ terms of the Taylor series given above for \$\cos(x)\$.
This is code-golf, so shortest code wins. Input and output can be taken in any of the standard ways. Standard loopholes are forbidden.
Notes

Input can be taken in any reasonable form, as long as there is a clear separation between \$x\$ and \$n\$.
Input and output should be floating-point values, at least as accurate as calculating the formula using single-precision IEEE floating point numbers with some standard rounding rule.
If it makes sense for the language being used, computations may be done using exact rational quantities, but the input and output shall still be in decimal form.

Examples
 x  |  n | Output
----+----+--------------
0.0 |  1 | 1.0
0.5 |  1 | 1.0
0.5 |  2 | 0.875
0.5 |  4 | 0.87758246...
0.5 |  9 | 0.87758256...
2.0 |  2 | -1.0
2.0 |  5 | -0.4158730...

I'm assuming that n is also greater than 0?

@GamrCorps n will be greater than zero, yes.

@RosLuP I'm not sure I understand your question, but the challenge is to produce the sum of the first n terms of the Taylor series stated in the problem, so the Taylor series about x = 2 or any other point will not suffice.

@SilvioMayolo ok i make one error, not rember well, yes sin(x) or cos(x) Taylor series would be ok in all R

I'd say they technically isn't what pedant means, but that would be too meta.

If your Boss wants you write a good or at least readable function, you're in the wrong place.

A truly picky boss would want to calculate cosine using something a little more efficient (and accurate) than Taylor series...

@PM2Ring That would not be picky, that would be being reasonable. Taylor series is really the crudest option.

If you are rounding, you shouldn't use .... If you are going to use ..., use the exact digits up until that point.

Operation Flashpoint scripting language, 165 157 bytes
F={x=_this select 0;n=_this select 1;i=0;r=0;while{i<n*2}do{r=r+x^i/(i call{c=_this;j=c-1;while{j>0}do{c=c*j;j=j-1};if(c<1)then{c=1};c})*(-1)^(i/2);i=i+2};r}

Call with:
hint format["%1\n%2\n%3\n%4\n%5\n%6\n%7",
    [0.0, 1] call f,
    [0.5, 1] call f,
    [0.5, 2] call f,
    [0.5, 4] call f,
    [0.5, 9] call f,
    [2.0, 2] call f,
    [2.0, 5] call f]

Output:

Input and output should be floating-point values, at least as accurate as calculating the formula using single-precision IEEE floating point numbers with some standard rounding rule.

I'm fairly sure that the numbers are single-precision IEEE floating point numbers, even though in the printed output the longer decimals are not that precise. It is the printing that rounds the numbers like that, actually the numbers are more precise.
For instance, a=1.00001;b=1.000011;hint format["%1\n%2\n%3", a, b, a==b] will output this:
1.00001
1.00001
false

So clearly the actual precision of the numbers is greater than the printed precision.

But why?

@orlp Why not ?

@orlp I think the more appropriate question to ask is: why isn't the Operation Flashpoint scripting language a variant of ArnoldC?

@ceilingcat GET TO THE CHOPPER

Accept this! I can't stop ROFL. Pure genius! And the first comments...to the point. And @ceilingcat , thank you for closing THIS gap in my knowledge about programming languages!

Hmmm… do you enter the input by shooting a given number of rounds [n] to the given compass direction [x]?  Operation Flashpoint!

@Mormegil Well, generally no, but that can be done with this piece of code: dir=-1;num=1;player addEventHandler ["fired", {_dir=getdir (nearestObject [_this select 0, _this select 4]);if (dir < 0) then {dir = _dir} else {if (abs(dir - _dir) < 5) then {num = num + 1} else {hint format["%1", [dir*(pi/180), num] call F];dir=-1;num=1}}}] - Shooting to some direction increments the counter, and then shooting to another direction calls the cosine function with the earlier direction and the number of shots in that direction.

In the spirit of pedantry and the question, your "Call with" section uses a lowercase f but your function submission uses an uppercase F

@cairdcoinheringaahing I see your excellent point of pedantry and raise you another one: The game's scripting language does not care about letter case. All names are case-insensitive, so the f and F disparity does not matter.

05AB1E, 14 11 bytes
FIn(NmN·!/O

Try it online!
Explanation
F                # for N in [0 ... n] do
 In              # push (x^2)
   (             # negate
    Nm           # raise to the Nth power
      N·!        # push (2*N)!
         /       # divide
          O      # sum

@JamesHolderness: Yes, the language has gone through a pretty major overhaul since then. A weird bug seem to have afflicted ², but it can instead be replaced by I.

Mathematica, 49 41 39 31 bytes
Sum[(-#^2)^k/(2k)!,{k,0,#2-1}]&

Old, more "fun" version: (39 bytes)
Normal@Series[Cos@k,{k,0,2#2-2}]/.k->#&

Saved 10 bytes thanks to @Pavel and 8 thanks to @Greg Martin!

While Mathematica's Series capability is indeed awesome and fun, it turns out the by-hand implementation Sum[(-#^2)^k/(2k)!,{k,0,#2-1}]& is shorter here.

MATL, 14 bytes
U_iqE:2ep/YpsQ

Try it online! Or verify all test cases.
Explanation with example
All numbers have double precision (this is the default).
Consider inputs x = 2.0, n = 5.
U_     % Implicitly input x. Square and negate
       % STACK: -4
iqE    % Input n. Subtract 1, multiply by 2
       % STACK: -4, 8
:      % Range
       % STACK: -4, [1 2 3 4 5 6 7 8]
2e     % Reshape into a 2-row matrix
       % STACK: -4, [1 3 5 7;
       %             2 4 6 8]
p      % Product of each column
       % STACK: -4, [2 12 30 56]
/      % Divide, element-wise
       % STACK: [-2 -0.333333333333333 -0.133333333333333 -0.0714285714285714]
Yp     % Cumulative product of array
       % STACK: [-2 0.666666666666667 -0.0888888888888889 0.00634920634920635]
s      % Sum of array
       % STACK: -1.41587301587302
Q      % Add 1. Implicitly display
       % STACK: -0.41587301587302

Jelly, 12 11 bytes
ḶḤµ⁹*÷!_2/S

Try it online!
How?
ḶḤµ⁹*÷!_2/S - Main link: n, x           e.g. 5, 2.0
Ḷ           - lowered range(n)              [0,1,2,3,4]
 Ḥ          - double (vectorises)           [0,2,4,6,8]
  µ         - monadic chain separation (call that i)
   ⁹        - link's right argument         2.0
    *       - exponentiate(i) (vectorises)  [1.0,4.0,16.0,64.0,256.0]
      !     - factorial(i) (vectorises)     [1,  2,  24,  720, 40320]
     ÷      - divide (vectorises)           [1.0,2.0,0.6666666666666666,0.08888888888888889,0.006349206349206349]
        2/  - pairwise reduce by:
       _    -     subtraction               [-1.0,0.5777777777777777,0.006349206349206349]
         S  - sum                           -0.41587301587301617

Jelly, 22 bytes
-*ð×ø⁹*⁸²ð÷ø⁸Ḥ!
⁸R’Ç€S

This is a full program which takes n as the first argument and x as the second.
Explanation:
              Creates a function to compute each term in the series.
Its argument we will call k, eg k=3 computes 3rd term. Take x=2 for example.
-*           Computes (-1)^k. Eg -1
ð×ø        Multiplies by the quantity of
⁹             x.
*             to the power of
⁸             k
²             ...squared. Eg -1 × (2³)²
ð÷ø        divides by the quantity of
⁸              k
Ḥ             doubled
!               ...factorial. Eg -1 × (2³)²/(6!).

                Main link, first argument n and second argument n. Eg n=4, x=2.
⁸R            Creates range(n). Eg [1,2,3,4]
’                Decrements each element. Eg [0,1,2,3]
Ç€            Maps the above function over each element. Eg [1,-2,0.666,-0.0889]
S               Sum all all of the elements.  Eg -0.422.

Welcome to PPCG!

Python, 54 bytes
f=lambda x,n,t=1,p=1:n and t+f(x,n-1,-t*x*x/p/-~p,p+2)

If using Python 2, be sure to pass x as a float, not an integer, but I my understanding is that it doesn't matter if you're using Python 3.

4 years late, but 46 bytes

TI-Basic, 41 40 bytes
Prompt X,N
sum(seq((-(X+1E-49)2)^Q/((2Q)!),Q,0,N-1

1E-49 is added to the angle because TI-Basic throws an error for 0^0, it's just large enough to not cause the error,  and it is not large enough to change the answer.

-3 bytes I suppose: X+1e-49 => X+e-49 and .../((2Q)!) => .../(2Q)!

or even better (-(X+1e-49)²)^Q => (e-99-X²)^Q

R, 70 64 47 bytes
function(x,n,m=1:n-1)sum((-x^2)^m/gamma(2*m+1))

Try it online!

uses gamma(n+1) instead of factorial(n)
1:n-1 is equivalent to 0:(n-1)

Thanks to Dominic van Essen for golfing 17 bytes off by using a basic R feature: vectorization!

Is there a reason that you didn't use vectorization...?

@DominicvanEssen probably because I was a young R golfer, so excited to use sapply that I completely overlooked vectorization!

C, 71 bytes
using Horner scheme
float f(n,x)float x;{float y;for(n+=n;n;)y=1-(y*x*x/n--)/n--;return y;}

Ungolfed version:
float f(n,x) float x;
{
  float y = 0.0;
  for(n = 2*n; n>0; n -= 2)
  {
    y = 1-y*x*x/n/(n-1);
  }
  return y;
}

On which platform does this work?

JavaScript (ES6), 46 bytes

f=
x=>g=(n,t=1,p=0)=>n&&t+g(--n,-t*x*x/++p/++p,p)

<input id=x><input type=number min=1 value=1 id=n>
1

Takes curried inputs (x)(n).

Why not make it a snippet?

C, 96 bytes
Recursive Live
f(n){return n?n*f(n-1):1;}float c(n,x)float x;{return n?c(n-1,x)+pow(-1,n)*pow(x,2*n)/f(2*n):1;}

Detailed
f(n) // factorial(n)
{
    return n ?   // n != 0 ?
        n*f(n-1) // n! = n * (n-1)!
    : 1;         // 0! = 1
}

float c(n,x)float x; // cos(x) with n+1 terms
{
    return n ?        // n != 0 ?
        c(n-1, x)     // cos(x) (n-1)th term
        + pow(-1, n)  // + (-1)^n
        * pow(x, 2*n) // * x^(2n)
        / f(2 * n)    // / (2n)!
    : 1;              // cos(x) at n=0
}

Progressive Recursive, 133 bytes Live
#define F float
#define c(x,n) 1+g(1,n,x,1,1,1)
F g(F i,F n,F x,F s,F p,F f){s=-s;p*=x*x;f*=i;return i<n?g(i+1,n,x,s,p,f)+s/2*p/f:0;}

Detailed
#define F float // shorthand float

#define c(x,n) 1+g(1,n,x,1,1,1) // macro function

F g(F i,F n,F x,F s,F p,F f)
{
    s = -s;   // (-1)^n = (-1) * (-1)^(n-1)
    p *= x*x; // x^(2n) =  x^2 * x^(2(n-1))
    f *= i;   //    2n! =    2 * (1*2*..*n)

    return i < n ?       // i = 0 .. n-1
        g(i+1,n,x,s,p,f) // next term
        + s / 2 * p / f  // s*p/2f = s/2*p/f
        : 0;             // don't compute nth term
}

96b version c(0.5, 80) => NaN, for overflow f(80)=0

@l4m2 recursive functions are here for the purpose of golfing, but they're impractical as they can easily overflow as the number of calls exceed the call-stack limit, & even with higher limits it's a waste of resource, for the solution above try smaller numbers.

Problem directly say n<100 so you at least don't go that far in the range. Not stack overflow

If problem say n<100 and you use O(2^n) solution I guess it's okay, as long as it eventually retuan the result

FYI, the NaN result has got nothing to do with recursion - it's an overflow of the factorial calculation which is using integers when it should be using floats (198! is never going to fit in an int).

oK, 38 bytes
This also works in k, but takes 39 bytes because one ' has to be written as /: instead (at least, in kmac 2016.06.28 it does).
{+/(y#1 -1)*{(*/y#x)%*/1+!y}.'x,'2*!y}

Explanation:
Let's start with the middle bit. (*/y#x) is exponentiation, it is equivalent to x^y. */1+!y would be y!, or y factorial. % is division. Therefore the function in the middle is middle(x,y) = (x^y)/(y!).
Now the bit on the right, to which the function above gets applied. 2*!y is {0, 2, 4, ..., 2*(y-1)}. x,' prepends x to every item in that list, turning it into {(x, 0), (x, 2), (x, 4), ..., (x, 2*(y-1))}. The .' then applies middle to every pair of numbers (map, essentially).
Finally, (y#1 -1)* multiplies the result by 1 or -1 (alternating), and +/ takes the sum.

Haskell, 71 Bytes
f x n=sum$map(\i->(-1)^i*x^(2*i)/fromIntegral(product[1..2*i]))[0..n-1]

This is a pretty boring answer that's not too hard to decipher. The fromIntegral really bites, though. (The / operator requires operands of the same numeric type in Haskell, and coercing between numeric types is not allowed without a wordy function.)

A list comprehension can save you a few bites: f x n=sum[(-1)^i*x^(2*i)/fromIntegral(product[1..2*i])|i<-[0..n-1]]

Welcome to PPCG and Haskell golfing in particular!

Jelly, 12 bytes
²N*Ḷ}©÷®Ḥ!¤S

Try it online!
How it works
²N*Ḷ}©÷®Ḥ!¤S  Main link. Left argument: x. Right argument: n

²             Square; yield x².
 N            Negate; yield -x².
     ©         Call the link to the left and copy the result to the register.
   Ḷ}          Call unlength on the right argument, yielding [0, 1, ..., n-1].
  *           Yield [1, -x², ..., (-x²)**(n-1)].
          ¤   Combine the three links to the left into a niladic chain.
       ®        Yield the value in the register, [0, 1, ..., n-1].
        Ḥ       Unhalve; yield [0, 2, ..., 2n-2].
         !      Factorial; yield [0!, 2!, ..., (2n-2)!].
      ÷         Division; yield [1/0!, -x²/2!, ..., (-x²)**(n-1)/(2n-2)!].
           S  Take the sum.

Haskell, 61 bytes
x#n=sum[(-1*x^2)^i/fromIntegral(product[1..2*i])|i<-[0..n-1]]

This seemed different enough from the other Haskell solution to warrant a separate answer. Implementation should be pretty self-explanatory—call with x#n where x is the number the cosine of which is to be computed and n is the order of the partial sum to be taken.

You can save quite a few bytes by removing the fromIntegral and using ** in place of ^, such as this

x#n=sum[(-x*x)**i/product[1..2*i]|i<-[0..n-1]] saves 3 more bytes.

Pyth, 16 bytes
sm_Fc^vzyd.!yddU

Accepts n first, then x. Example run.

Pyt, 37 34 33 bytes
←←ĐĐ↔3Ș1~⇹ř⁻^04Ș⇹ř⁻^²*0↔ř⁻2*!+/+Ʃ

Perl 6, 53 bytes
{(sum (1,*i*$^x...*)[^2*$^n] »/»(1,|[\*] 1..*)).re}

Try it online!
This actually computes the complex exponential eiθ for twice the number of requested terms and then takes the real part.

J, 26 24 Bytes
+/@:(!@]%~^*_1^2%~])2*i.

-2 bytes thanks to @cole
I originally planned to use a cyclic gerund to alternate between adding and subtracting, but couldn't get it to work.
Explanation:
                    2*i.     | Integers from 0 to 2(n-1)
    (              )         | Dyadic train:
            _1^-:@]          | -1 to the power of the left argument
          ^*                 | Times left arg to the power of right arg
     !@]%~                   | Divided by the factorial of the right arg
+/@:                         | Sum

24 bytes: +/@:(!@]%~^*_1^2%~])2*i. Gonna investigate a cyclic gerund: it probably failed since J evaluates / right-to-left so you need to use |. (or maybe you accounted for this and still had difficulty).

Julia, 37 bytes
x$n=1>(n-=1)||x$n+(-x^2)^n/prod(1:2n)

Try it online!

MATLAB with Symbolic Math Toolbox, 57 bytes
@(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))

This defines an anonymous function with that takes double inputs x,n and outputs the result as a double.
Example (tested on R2015b):
>> @(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))
ans =
    @(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))
>> f = ans; format long; f(0,1), f(0.5,1), f(0.5,2), f(0.5,4), f(0.5,9), f(2,2), f(2,5)
ans =
     1
ans =
     1
ans =
   0.875000000000000
ans =
   0.877582465277778
ans =
   0.877582561890373
ans =
    -1
ans =
  -0.415873015873016

C 144 130 bytes
F(m){int u=1;while(m)u*=m--;return u;}float f(float x,n){float s;for(int i=1;i<n;i++)s+=pow(-1,i)*pow(x,2*i)/(F(2*i));return 1+s;}

Ungolfed Version:
//Function to calculate factorial
int F(int m)
{
  int u=1;

  while(m>1)
   u*=m--;

  return u;
}

//actual function called in main function
float f(float x, int n)
{

  float s=0.0;

  for(int i=1;i<=n-1;i++)
     s+=pow(-1,i)*pow(x,2*i)/(F(2*i));

  return 1+s;
 }

Thanks Kevin for saving some bytes!

You can save a few bytes by massaging the function definitions: F(m){...}f(x,n)float x;{...}

Since u * 1 == u, you can make the loop in the first function either while(m)u*=m-- or u=m;while(--m)u*=m (same length)

i<=n-1 is the same as i<n

@Kevin Thanks, you're absolutely right, have not golfed in a while now. :)

You probably could save some extra bytes if you use f() recursively instead of a loop therein. If you also use the ternary operator your whole function body becomes a one-liner with a few basic math. See my answer.

101 bytes

JavaScript ES7 60 bytes
x=>a=n=>--n?(-1)**n*x**(2*n)/(f=m=>m?m*f(m-1):1)(2*n)+a(n):1

x=>a=n=>                                                         // Curry-d function, it basically returns another function
        --n?                                              :1  // subtract one from n. If n - 1 is 0, return 1
            (-1)**n*                                             // This generates the sign of the number
                    x**(2*n)/                                    // This creates the part before the division, basicaly x^2n
                             (f=m=>m?m*f(m-1):1)(2*n)            // This creates a recursive factorial function and calls it with 2n
                                                     +a(n)    // Recursively call the function. This adds the elements of the taylor series together

To use it:
Press F12, type in the function and then do
c(x)(n)

Tcl, 126 bytes
proc c {x n k\ 0 r\ 0} {proc F n {expr $n?($n)*\[F $n-1]:1}
time {set r [expr $r+-1**$k*$x**(2*$k)/[F 2*$k]]
incr k} $n
set r}

Try it online!

Failed outgolf: 129

Stax, 12 bytes
ü┘·.ⁿYeò≥Vîû

Run and debug it
Unpacked, ungolfed, and commented, it looks like this.
            Input is `x n`
Z           Push a zero underneath the top.  The stack is now `x 0 n`
D           Run the rest of the program n times.
  xJNi|*    (-x*x)^i where i is the iteration index
  iH|F/     divide that by factorial(2i)
  +         add to the running total so far
            final result is implicitly printed

Run this one

Desmos, 36 bytes
\sum_{k=0}^{n-1}{(-1)^kv^{2k}/(2k)!}

View it on Desmos
Unfortunately, not a ton to golf here.

\sum_{k=0}^{n-1}{(-v^2)^k/(2k)!} for 32 bytes

Wolfram Language (Mathematica), 30 bytes
Normal[Cos@x+O@x^(2#2)]/.x->#&

Try it online!
Mathematica has a more (byte-)efficient way to generate SeriesData objects than Series. O[x]^p truncates the power series of the function at the pth power.

Husk, 20 bytes
⌊*!9İ⁰ṁ§/ȯΠḣD`^o_□⁰ŀ

Try it online!
Outputs sign + 9 decimal places; the initial decimal point is implicit.
14 bytes (ṁ§/ȯΠḣD`^o_□⁰ŀ) to calculate the cosine, plus 6 bytes (⌊*!9İ⁰) to extract the decimal representation from the a rational number...

MMIX, 60 bytes (15 instrs)
cos SETH $5,#3FF0       // E0053FF0: one = 1.0
    SETL $2,0           // E3020000: twon = 0
    SET  $3,$5          // C1030500: term = one
    FMUL $4,$0,$0       // 10040000: numer = x *. x
    SETL $0,0           // E3000000: accum = 0
    INCH $4,#8000       // E4048000: numer = -.numer
0H  FADD $0,$0,$3       // 04000003: loop: accum +.= term
    FADD $255,$2,$5     // 04FF0205: temp = twon +. 1
    FADD $2,$255,$5     // 0402FF05: twon = temp +. 1
    FMUL $255,$255,$2   // 10FFFF02: temp *.= twon
    FDIV $255,$4,$255   // 14FF04FF: temp = numer /. temp
    FMUL $3,$3,$255     // 100303FF: term *.= temp
    SUBU $1,$1,1        // 27010101: count--
    PBZ  $1,0B          // 5301FFF9: likelyif(!count) goto loop
    POP  1,0            // F8010000: return(accum)

This is a really simpleminded algorithm. I managed to avoid using more than three stack temporaries ($255 is global and free for temporary use, any register numbered less than 32 is guaranteed on-stack).
A few clever tricks and misc notes:
SET $X,$Y is a short version of OR $X,$Y,0;
it's nice that 1.0 fits entirely in the top quarter of a float, otherwise we would have had to use another instruction to set it;
PBZ is a predicted branch (faster if taken) if the register operand is 0;
the 0H is a local label that the 0B refers back to;
and POP a,b means return a local variables and skip b instructions after the function call.

PowerShell Core, 89 70 bytes
param($x,$n)0..--$n|%{$s+="-$x*$x*"*$_+(1..(2*$_)-ne0-join'/')|iex}
$s

Try it online!
Explanation
Generates a string containing each of the member of the sum like
-0.5*0.5*-0.5*0.5*0.5*-0.5*0.5*-0.5*1/2/3/4/5/6/7/8

Then pass it through iex and sums the different iterations.
-6 bytes thanks to mazzy!

Try it online?

JavaScript, 59 bytes
x=>k=n=>--n?k(n)+(-1)**n*x**(n*=2)/f(n):1
f=p=>p?p*f(p-1):1

Try it online!

This is 65 bytes

@Bálint had made a mistake in copying the changes over. (n) was supposed to just be n

Axiom, 36 bytes
g(a,n)==eval(taylor(cos(x)),a).(2*n)

Build the infinite (in the meaning finite but one can ask to build the list of 2*n elements if PC has enough memory) list of partial sums for the Taylor series for cos(x) calculate in 'a',
in "eval(taylor(cos(x)),a)"; gets the 2*n element of that list in ".(2*n)".
Test cases:
(47) -> g(0,1)
   (47)  1
                                                 Type: Expression Integer
(48) -> g(0.5,1)
   (48)  1.0
                                                   Type: Expression Float
(49) -> g(0.5,2)
   (49)  0.875
                                                   Type: Expression Float
(50) -> g(0.5,4)
   (50)  0.8775824652 7777777778
                                                   Type: Expression Float
(51) -> g(0.5,9)
   (51)  0.8775825618 9037271611
                                                   Type: Expression Float
(52) -> g(2.0,5)
   (52)  - 0.4158730158 7301587302
                                                   Type: Expression Float
(53) -> g(2.0,800)
   (53)  - 0.4161468365 471423870

PHP, 76 bytes
for($f=1;$i<$argv[2]*2;$f*=++$i)$i&1?:$s+=(-1)**$k++*$argv[1]**$i/$f;echo$s;

takes X and N from command line arguments; run with -r.
loop $i from 0 to N*2-1, hold fac($i) in $f; if $i is even, add term to sum$s. print sum.

I wish I had complex numbers (with M_I as imaginary unit);
I would simply multiply $f with M_I*++$i and save 7 bytes.
Maybe Mathematica can do that. But Mathematica doesn´t have to.
I could save two bytes with cos(M_PI*$i/2) instead of $i&1?: and (-1)**$k++;
but it would feel a bit odd to use a cosine builtin to build a cosine function.

Java, 92 bytes
double c(double x,double c,long d,int i){return i>0?r+=c(x,-c/x/x,d/(4*i*i-2*i),--i)+c/d:r;}

Try it online!
With comments and whitespaces:
C.java
    /*
     * Class 'C' (for 'Cosine').
     * Copyright (C) 2017 Gerold 'Geri' Broser (geribro@users.sourceforge.net)
     *
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program. If not, see <http://www.gnu.org/licenses/>.
     */
    //package p;

    /** Class 'C' (for Cosine).
     *
     * @author Gerold 'Geri' Broser
     * @version 17.04.21
     * @see https://codegolf.stackexchange.com/questions/116705/the-pedants-cosine
     */
    class C {

        /** The added up results of the polynomial's terms.
         */
        double r;

        /** This one-liner method 'c' (for calculate) returns the part (i=n-1) of a
         *  cosine of a given angle 'x' that's calculated from the second term of a
         *  Taylor series of n polynomial terms onwards (or backwards until the
         *  second term [i=1], to be precise, see below).
         *
         *  It achieves this by doing the following:
         *
         * ● It doesn't calculate the first term since it is always 1 anyway.
         *
         * ● It uses recursion for calculating the terms of the polynomial.
         *
         * ● It calculates from the rightmost term back to the leftmost. Such avoiding
         *   to keep the upper boundary stored till the end for the recursion's stop
         *   condition.
         *
         * ● It is supplied with values for the counter and denominator of the
         *   rightmost term at invocation. Such also the user can decide which
         *   library to take for power and factorial.
         *
         * ● It calculates the counters and denominators for each term from scratch
         *   at each recursion but uses the values calculated at the previous
         *   recursion. Such the new values can be calculated by using trivial
         *   parenthesis, division, multiplication, decrement and negation only.
         *   This doesn't only save characters but probably is also faster than
         *   power and factorial.
         *   [It could be made be even faster for x=2^n, n ∈ N, because we can
         *   use the unsigned right shift operator '>>>' instead of divisions then
         *   (see method 'calculateForXisPowerOfTwo()' of class 'Cosine').]
         *
         * @param x angle (independent variable) in radians
         * @param c counter of last term specified by index 'i' including proper sign
         *          (see class 'CTest')
         * @param d denominator of last term specified by index 'i' (see class 'CTest')
         * @param i index of last term used in the calculation (=number of terms 'n'
         *          minus 1; Σ's upper boundary)
         *
         * @see https://en.wikipedia.org/wiki/Taylor_series#Trigonometric_functions
         */

        // Copy the following three lines to immediately after the function header for testing:
        //  System.out.printf(
        //          "c(): x:%4.1f  c:%24.17f  d:%,19d  i:%2d  t:%40.35f%n",
        //          x, c, d, i, c / d);

        // Position of 'i' is relevant here, since it is prefix-decremented inline!
        double c( double x, double c, long d, int i ) {
            return i > 0
                    ? r += c(
                        x,
                        -c / x / x,
                        d / (4 * i * i - 2 * i),
                        --i )
                        + c / d
                    : r;
        } // c()
    } // C

CTest.java
    /*
     * Class 'CTest' (for 'Cosine Test').
     * Copyright (C) 2017 Gerold 'Geri' Broser (geribro@users.sourceforge.net)
     *
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program. If not, see <http://www.gnu.org/licenses/>.
     */
    package p;

    import org.apache.commons.math3.util.CombinatoricsUtils;

    /** Test class for methods 'c' (for calculate) of class 'C' (for Cosine).
     *
     * @author Gerold 'Geri' Broser
     * @version 17.04.21
     * @see https://codegolf.stackexchange.com/questions/116705/the-pedants-cosine
     */
    public class CTest {

        /** The Unicode character 'ₛ' is the subscript character for 's'. It stands for the plural 's'
         *  in the array's names. ('xs' wasn't matching my BMI. 'ns' looked like a system that we have
         *  overcome since decades and like the German abbreviation for...I'm leaving that one out now.)
         *
         * @param args command line arguments
         */
        public static void main( String[] args ) {

            double[] xₛ = { .0, .5, .5, .5, .5, 2., 2. };
            int[] nₛ = { 1, 1, 2, 4, 9, 2, 5 };

            System.out.println(
                    "┌────┬─────┬───┬───────────────────────┐\n" +
                    "│ No │  x  │ n │        cos(x)         │\n" +
                    "├────┤─────┼───┼───────────────────────┤" );
            for ( int i = 0; i < xₛ.length; i++ ) {

                System.out.printf( "│ %d. │ %2.1f │ %d │ %,21.18f │%n",
                        i + 1,
                        xₛ[i], // x (angle)
                        nₛ[i]--, // n (number of terms of the polynomial, decreased for further processing as index)
                        1.0 + new C().c(
                                xₛ[i], // x (angle in radians)
                                Math.pow( -1, nₛ[i] ) // negate alternating starting with minus for the second term
                                        * Math.pow( xₛ[i], 2 * nₛ[i] ), // counter for the rightmost term (c)
                                CombinatoricsUtils.factorial( 2 * nₛ[i] ), // denominator for the rightmost term (d)
                                nₛ[i] // index of last term of the polynomial
                        ) );

            } // for ( C test case )
            System.out.println( "└────┴─────┴───┴───────────────────────┘" );
        } // main()
    } // CTest

Output
┌────┬─────┬───┬───────────────────────┐
│ No │  x  │ n │        cos(x)         │
├────┤─────┼───┼───────────────────────┤
│ 1. │ 0,0 │ 1 │  1,000000000000000000 │
│ 2. │ 0,5 │ 1 │  1,000000000000000000 │
│ 3. │ 0,5 │ 2 │  0,875000000000000000 │
│ 4. │ 0,5 │ 4 │  0,877582465277777700 │
│ 5. │ 0,5 │ 9 │  0,877582561890372800 │
│ 6. │ 2,0 │ 2 │ -1,000000000000000000 │
│ 7. │ 2,0 │ 5 │ -0,415873015873015950 │
└────┴─────┴───┴───────────────────────┘

J, 17 bytes
4 :'2&o.T.(+:y)x'

Try it online!
Uses a built-in, which I assume is OK.
Unfortunately, I don't really know how to work well with functions that take arguments via currying like this, so I had to do this explicitly. I'm sure that there is a way to do it tacitly or shorter.

Clean, 77 bytes
import StdEnv
?x n=sum[(-1.0)^(p/2.0)*x^p/prod[1.0..p]\\p<-take n[0.0,2.0..]]

Try it online!

Pari/GP, 35 bytes
f(x,n)=sum(i=0,n-1,(-x^2)^i/(2*i)!)

Try it online!

F#, 177 146 bytes
let rec f x=if x<2 then 1 else f(x-1)*x
let i n x=(pown -1.0 n)*(pown x (2*n))/float(f(2*n))
let t x k=seq{for j=0 to(k-1)do yield i j x}|>Seq.sum

Try it online!
Shaved off 31 bytes thanks to Emmanuel showing me operators in F# that I wasn't aware of. I had a look at Microsoft.FSharp.Core.Operators and found some useful stuff there. Thanks a million!
f is a recursive factorial function. i is one item in the series, and t is the actual Taylor Series itself - iterate through from 0 to k-1, evaluating i at each stage, and sum the results.

You could try with the **exponential operator.

Ah, I wasn't aware that F# had an exponential operator! This is what I love about Code Golf - I'm inexperienced with F# so I didn't know about ** or any of the other goodies in Microsoft.FSharp.Core.Operators. Now I know about ** and pown and a load of other good things, and I can take 31 bytes off the solution. Thanks a lot, I really appreciate it!

PowerShell Core, 59 56 bytes
-3 bytes thanks to Julian
param($x,$n)$v=1
1..$n|%{$s+=$v;$v*=-$x*$x/++$k/++$k}
$s

Try it online!

Try it online! ?

exactly! ☚ (<‿<)☚

54 bytes!

APL(NARS), 64 chars
r←p C w;d;v;m
r←d←1⋄m←w×w×¯1⋄v←¯1,0
→0×⍳0≥p-←1⋄r+←d×←m÷×/v+←2⋄→2

13+21+28+2=64
How to use and test:
  {⍵,⍵ C 0.5} ¨ 0..5
┌6─────────────────────────────────────────────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───────┐ ┌2──────────────┐ ┌2──────────────┐ ┌2──────────────┐│
││ 0 1│ │ 1 1│ │ 2 0.875│ │ 3 0.8776041667│ │ 4 0.8775824653│ │ 5 0.8775825622││
│└~───┘ └~───┘ └~───────┘ └~──────────────┘ └~──────────────┘ └~──────────────┘2
└∊─────────────────────────────────────────────────────────────────────────────┘

OT these below should be the answers 100% precise but not in decimal
  {⍵,⍵ C 1r2} ¨ 0..5
┌6─────────────────────────────────────────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2─────┐ ┌2─────────┐ ┌2─────────────┐ ┌2──────────────────┐│
││ 0 1│ │ 1 1│ │ 2 7r8│ │ 3 337r384│ │ 4 40439r46080│ │ 5 9058337r10321920││
│└~───┘ └~───┘ └~─────┘ └~─────────┘ └~─────────────┘ └~──────────────────┘2
└∊─────────────────────────────────────────────────────────────────────────┘

7r8 means 7/8  .

Vyxal ḋ, 8 bytes
ʁd~e$¡/∑

Try it Online! The ḋ flag is to output as a decimal.
ʁ        # Range from 0 to n-1
 d       # doubled
  ~e     # x ** each of that
      /  # Divided by
    $¡   # Factorial of each of that
       ∑ # Sum

C (tcc), 103 bytes
double r,d,m,co(int n,double w){int x=-1,y=0;for(r=d=1,m=-w*w;--n>0;x+=2,y+=2,r+=d*=m/(x*y));return r;}

Try it online!

92 bytes

84 https://tio.run/##LY7RygIhEIXvfQopAs3ZzYKubHqSbkxXGthff8xlhejZN5eai4E55zDfcV1xblnCmGzhGTxUcIJi4RG@2ixfIWWR0WPFI8x77GbTdfGqTVV4klmh3@N8qAdxVFWaPJQpR57Ne9lSdOPkB355Fk@pf1zZn6UoJHv5NN3HgXOLuj9DSzO@Qn9D7VyhhNrQBc9GKZJsdf5ziwWxcekpdh52/SlIbFuHW9wAgV3bg5Wyffg10Ya9lw8

@ceilingcat 81 float r,d,x,c(int n,float w){for(r=d=x=1;--n>0;x+=2)r+=d*=-ww/x/(1+x);return r;} this seems ok with tcc and this 79 not with tcc float r,d,x,c(n,w)float w;{for(r=d=x=1;--n>0;x+=2)r+=d=-ww/x/(1+x);return r;} but ok with Borland C, here compile and return it seems right, but for each element of sum there is one product ww more than the min. Possible not all the multiplication sign are seen here

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
One Expression, Many Values
Using our familiar mathematical symbols: +, x, parenthesis, and any rational number, it's easy to create expressions that evaluates to some desired number. For example: 1+(2x3)=7, (1+2)+(3x6.5)=22.5 and so on. Boring enough.
In this challenge, we'll use a new operator: ±. The use of ± in an expression means you need to evaluate the expression by replacing the ±'s by + or - in all possible ways, and return the set of all possible values. For example:

1±2±3 = {-4,0,2,6} because 1±2±3 can be any of 1+2+3, 1+2-3, 1-2+3 and 1-2-3 and their values are 6,0,2,-4 respectively.
(±2)x(2±3) = {-10,-2,2,10} for similar reasons.

Now, as it turns out, given any set of distinct real numbers, it's possible to create an expression with +,x,(,),±, and real numbers that evaluates to the given set.
Task
Your task is to write a program or function in a language of your choice, that takes a sequence (list/array/any convenient format) of integers and outputs an expression (as a string) consisting of +,x,(,),±, and rational numbers that evaluates to the set of the given numbers.

Note that the exact character ± doesn't matter; you can use any other character of your choice as long as it's distinguishable from the other characters you're using.  But you must mention which character you are using in your submission.
The input is allowed to consist of decimal approximations (up to reasonable accuracy) of the rational numbers used.
Input and output can be taken in any of the standard ways.
Standard loopholes are forbidden.
You can assume the given integers will be distinct, and provided in increasing order.
Output may contain spaces and newlines.

Winning Criterion
This is code-golf, so shortest code in bytes wins.
Examples

Input        |  Possible output
-------------+-----------------------------
[1,2,3]      |  2±0.5±0.5
[-7,-3,1,21] |  (1±2)x(3±4)

Idea taken from a question in the Tournament of Towns, Fall 2015.

Welcome to PPCG! Nice first challenge! I think this would attract more answers if it were the other way around (find the set given the expression) because it seems like this is quite a tricky challenge. Good challenge nonetheless!

Welcome again! Adding on to @HyperNeutrino, there will probably be multiple solutions to some of the sets, which could be a problem, when deciding which question is the "best" unless the deciding factor is the conciseness

@HyperNeutrino Thanks! I did apprehend this might turn to be a bit hard, but I fully believe in the superior capabilities of the golfers here; let's see how it turns out. :)

Yes. Some of the golfers on this site have amazing superpowers, and we even suspect some are golfing bots >_> :D

@DavidArchibald Yes, the intended output is any solution that works.

Is the format .5 OK in the output?

@xnor Yep, it's fine.

Well it turns out that the golfing people here were had golfing superpowers and got this challenge in a few hours >_> lol I still don't get how it works

0.0 The fact that the first three answers were all different methods to do this in Haskell has me worried.

Python 2, 56 bytes
f=lambda h,*t:t and"(.5?.5)*(%s+%%s)+"%f(*t)%-h+`h`or`h`

Try it online!
The ? stands for ±. Example usage:
f(-3,5,20) ->
(.5?.5)*((.5?.5)*(20+-5)+5+3)+-3

The idea is that we can take an expression E and adjoin a new value h to its set of values by doing (.5±.5)*(E+-h)+h.

Why +-h, and not just -h? That is, why not make the + a - and remove the - that's currently in the program?

@isaacg The spec doesn't allow for a - operator in the expression.

Haskell, 52 bytes
f(h:t)=shows h"+(.5?.5)*("++f[x-h|x<-t]++")"
f e="0"

Try it online!
Uses ? for ±. Example:
f [1,3,7] ->
1+(.5?.5)*(2+(.5?.5)*(4+(.5?.5)*(0)))

The function shows does shows a b=(show a)++b, a trick I learned from Lynn.
shows 12 "abc" ->
"12abc"

Haskell, 58 bytes
Using # for ±, as it's one less byte.
f takes a list of integers and returns a string.
f[x]=show x
f(x:r)=show x++"+(.5#.5)x("++f((-x+)<$>r)++")"

Result is of the form n+(.5#.5)x(rest), where n is the first element of the list and rest is the representation of all the others with n subtracted from each.
Try it online!

Jelly, 29 bytes
“(¤)”j.⁾+×j;”(
I;@Ḣj¢;”)ẋ⁸L¤¤

Prints v+(0.5¤0.5)×(i1+(0.5¤0.5)×((i2+(0.5¤0.5)×(...(in)...))) where v is the first number in the input array and in is the nth incremental difference between elements of the input array.
Try it online!
How?
“(¤)”j.⁾+×j;”( - Link 1, adjoining list: no input
“(¤)”          - literal     ['(','¤',')']
      .        - literal     0.5
     j         - join        ['(',0.5,'¤',0.5,')']
       ⁾+×     - literal     ['+','×']
          j    - join        ['+',['(',0.5,'¤',0.5,')'],'×']
            ”( - literal     '('
           ;   - concatenate ['+',['(',0.5,'¤',0.5,')'],'×','(']

I;@Ḣj¢;”)ẋ⁸L¤¤ - Main link: list a               e.g. [-1,5,2]
I              - incremental differences(a)           [6,-3]
   Ḣ           - head(a)                              [-1]
 ;@            - concatenate (rev @rgs)               [-1,6,-3]
     ¢         - last link (1) as a nilad             ['+',['(',0.5,'¤',0.5,')'],'×','(']
    j          - join                                 [-1,['+',['(',0.5,'¤',0.5,')'],'×','('],6,['+',['(',0.5,'¤',0.5,')'],'×','('],-3]
             ¤ - nilad followed by link(s) as a nilad
            ¤  -     nilad followed by link(s) as a nilad
          ⁸    -         link's left argument, a
           L   -         length                       3
       ”)      -     literal ')'
         ẋ     -     repeat                           [')',')',')']
      ;        - concatenate                          [-1,['+',['(',0.5,'¤',0.5,')'],'×','('],6,['+',['(',0.5,'¤',0.5,')'],'×','('],-3,')',')',')']
               - implicit print                       -1+(0.5¤0.5)×(6+(0.5¤0.5)×(-3))

05AB1E, 25 bytes
0¸«¥X;D"+(ÿ±ÿ)*("ý¹g<')×J

Try it online!
Explanation
0¸«                        # prepend a 0 to input list
   ¥                       # calculate delta's
    X;D                    # push 0.5 twice
       "+(ÿ±ÿ)*("          # push this string and interpolate 0.5 where "ÿ" is
                 ý         # merge the list of delta's with this string as a separator
                  ¹g<')×J  # add the closing parenthesis

Building the expression from the right unfortunately ends up at that the same byte count with
0¸«¥¤s¨RvX;Dy"ÿ+(ÿ±ÿ)*(ÿ). The 8 bytes used for the setup is the big waste here.

Haskell, 54 bytes
f[]="0"
f(x:s)=show x++"+(.5?.5)*("++f(map(-x+)s)++")"

the +- sign is '?'. example:
f[1,2,3,4] = "1+(.5#.5)*(1+(.5#.5)*(1+(.5#.5)*(1+(.5#.5)*(0))))"

JavaScript (ES6), 56 51 bytes
f=([v,...a],x=v)=>x?x+`+(.5@.5)*(${f(a,a[0]-v)})`:0

Based on @JonathanAllan's formula. @ stands for ±.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Shortest python A + B program with input and output
Some of you may say that I am wasting my time, but this task does not give me peace for more than 500 days. It is required to write a program in Python 3.x that takes two numbers as input and displays their sum. The numbers are given in the following format:
a b

Some example test cases:
100 500 -> 600
3 4     -> 7

The length of the code is calculated with the formula max(code length without spaces or tabs or newlines, code length / 4). I know only 2 solutions, each of them has a length of 36 characters:
print(sum(map(int, input().split())))

and:
print(eval(input().replace(' ', '+')))

Also I know, that the exists solution with length of 34 symbols. You can check it on this website.

If spaces don't count, I have a 34-char solution (SHA1 is e3eb1f896cffc2dbff531ce5ba8fa25d34c22c76). I'm not sure though it would be good to publicly post a solution to what seems to be a continuing programming competition. Do we have a site policy on that?

@ xnor, it's very old task, nobody can stop you to solve this problem here.

@xnor as we already got an 34-char solution, would you mind posting yours? Claudio's SHA1 is different than yours

@FelipeNardiBatista It's the same thing with double quotes.

Given the right hint toward the solution in the comment to the same question asked on stackoverflow ( see here ), I have got it right down to 34 and without any limitations on the input number or other tricks necessary:
print(eval(input().replace(*' +')))
Here a short summary of currently known different solutions:

print(eval(input().replace(' ','+')))  # 36
print(sum(map(int,input().split())))   # 36
print(eval(input().replace(*' +')))    # 34
print(sum(map(int,input()[::2])))      # 33 (limited to numbers between 0 and 9)

Maybe it could be considered cheating, but maybe not. At least there is no rule for this defined yet so let's include it into the collection of possible solutions:

import f;f.f()                         # 13

Required for this solution to work is a script f.py available in a search directory for modules of Python with following content:
def f():
    print(sum(map(int,input().split())))

If you read the question, it has to work on the given website, where there would not be an external script to import.

@mbomb007 : I have read the question and it is not mentioned in the question, or can you provide a citation from the question stating that it is?

"You can check it [(the problem)] on this website." And on the website, the specifications require input from STDIN. http://acmp.ru/index.asp?main=task&id_task=1 You don't get to create another module.

@Claudio thank for the answer. The correct version is print(eval(input().replace(*' +')))    # 34

@Claudio, can I close duplicate of this question on stackoverflow?

If you will be allowed to do that, why not? I can then see if my reputation there will decrease. Let's try :) . Personally I think that your posting at stackoveflow is valuable there, but most admins think probably it is not. My opinion is that diversity and duplicates are not necessary bad, but this is my personal opinion. Here some funny thing: as I wanted to make the answer 100% same as on stackoverflow my edit was rejected. I posted as guest but edited from new account I have created here on codegolf. Funny thing that I was not allowed to edit my own answer ... :D :D :D

By the way: I have hard time to understand why the admins downvote and want get rid of some very interesting questions/answers. I am getting the feeling that under time pressure they reject what is hard to grasp or understand not able to see the positive potential behind it. I learned very much about Python syntax and standard library out of this question and wouldn't run into it if it was posted only here. Putting things in clear and unambiguous categories is hard to accomplish and in most cases pure subjective decision ...

@Claudio I posted my question here because I was advised to do this on stackoverflow. Generally, I think people disagree with me on stackoverflow because the question not trivial and expect a lot of syntax knowledge. Also I agree with you, that question may be exists on both of network sites

@Claudio, if you are interesting in C++, I have the same question. I know the solution for Linux, but not for Windows. Let me know, I can post it.

@ЕвгенийКондратенко I am currently not into C++, also not into any questions without direct practical use and definitely not into Windows. From this perspective dealing with your question on stackoverflow was an absolute exception. I just wanted to see how good am I at Python and detected that I was not aware that the *[itemA,itemB] syntax apply also to characters in strings. That's it - now I'm done with riddles and Co for a while. Thanks for the offer (y) :) .

@Claudio if it's possible, try to combine two Claudio into the one.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Make me a s'more!
Make me a s'more! I tell you the width, the amount of graham cracker, the amount of chocolate, and the amount of marshmallow. An example:
Input:
Width: 10
Graham: 3
Chocolate: 2
Marshmallow: 1.
Output:
GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG
CCCCCCCCCC
CCCCCCCCCC
MMMMMMMMMM
GGGGGGGGGG
GGGGGGGGGG
GGGGGGGGGG

Is it that easy? Um... yes.
Note that the input should be a list of arguments to a function or a program, not a string. You might choose the first being Width, then Graham, but any order is fine.
Full test cases if you are interested.
Stack snippet (for testing, etc.)
This is to test the output.

var smore = function(width, graham, chocolate, marshmallow){
 return ("G".repeat(width) + "\n").repeat(graham) +
 ("C".repeat(width) + "\n").repeat(chocolate) +
 ("M".repeat(width) + "\n").repeat(marshmallow) +
 ("G".repeat(width) + "\n").repeat(graham);
};
Snippetify(smore);

Width: <input type = "number">
Graham: <input type = "number">
Chocolate: <input type = "number">
Marshmallow: <input type = "number">
<button>Try it out!</button>

Notes:

You may include a trailing newline on the end of the last line. You may also use a \ instead of a newline.
This is code-golf.
Any questions? Comment below:

I edited out your Let Me Google That For You link. It really wasn't funny.

can the output be a matrix of characters?

@FelipeNardiBatista yes.

Some answers are assuming flexible input order and format (as usual in PPCG), but the challenge seems to require a specific order and rule out strings (not sure what that means). Can you clarify?

@LuisMendo, you can use any input order desired.

Thanks for clarifying. You should then reword the sentence the input should be a list of arguments to a function or a program, not a string, with the first being Width, then Graham, etc. Personally I would say something like "Input format is flexible as usual"

@LuisMendo added. If there is anything else you think should be added, feel free to edit that in.

@programmer5000 but why? If they downvoted, it's 90% likely it's because they think it's a boring and trivial challenge. Furthermore, it's quite rude to tell people to explain or retract. They have the right to downvote without comment.

S'more what?

@EngineerToast A gram of what?

Jelly, 11 bytes
ṁ4“GCMG”x×Y

Try it online!
How it works
ṁ4“GCMG”x×Y  Main link. Left argument: g, c, m. Right argument: w

ṁ4           Mold 4; repeat g, c, m until length 4 is reached. Yields [g, c, m, g].
  “GCMG”x    Repeat 'G' g times, then 'C' c times, then 'M' m times, and finally
             'G' g times. This yields a string.
         ×   Multiply each character w times. This is essentially a bug, but
             Jelly's × behaves like Python's * (and vectorizes), so it can be
             abused for character repetition.
          Y  Join, separating by linefeeds.

Python 2, 73 48 bytes
lambda w,g,c,m:zip(*['G'*g+'C'*c+'M'*m+'G'*g]*w)

Try it online!
Creates a transposed version of the answer, than transposes it to the correct format with zip(*l)

05AB1E, 21 19 19 bytes
"GCMG"S×|D«‚øvy`.D»

Try it online!
-2 thanks to my oversight and Emigna.
"GCMG"S×            # Push GCMG, separate, duplicate n times.
        |D«         # Push rest of inputs, doubled.
           ‚ø       # Wrap GCMG array and input array, then zip them into pairs.
             vy`.D» # For each pair, print n of G/C/M/G.

(See Emigna's answer, it's better: https://codegolf.stackexchange.com/a/116787/59376)

You seem to have accidentally left a © in there.

You could also replace ¬¸ with D as the extra elements are lost when you zip.

@Emigna I both like and hate that functionality.

Yes, it's often very annoying but now and then (like now) it becomes useful :)

"GCMG" can be …GCMĆ for -1 (although I've also just posted a 14-byter with a different approach).

05AB1E, 17 16 bytes
1 bytes saved thanks to carusocomputing.
"GCMG"S×vy²Nè.D»

Try it online!
Input order is W, [G,C,M]
Explanation
10, [3,2,1] used as example.
"GCMG"S           # push the list ['G','C','M','G']
       ×          # repeat each W times
                  # STACK: ['GGGGGGGGGG', 'CCCCCCCCCC', 'MMMMMMMMMM', 'GGGGGGGGGG']
        v         # for each [string, index] y,N in the list
          ²Nè     # get the amount of layers at index N from the [G,C,M] list
         y   .D   # duplicate the string y that many times
               »  # join strings by newlines

"GCMG"S×vy²Nè.D» wonder-twin powers, activate! Form of, 05AB1E code! Also, arguments get swapped, but it's still 16.

@carusocomputing: It has the benefit of not leaving unprinted crap on the stack, but it seems similarly irreducible to me.

It's still 1 byte less and will beat your tie with MATL ;).

@carusocomputing: Oooh, when did that happen? I was sure it was 17 when I saw it. Nice! ;)

I often post stupid stuff and make edits to it 1 minute after I realize I'm being an idiot.

"GCMG" can be …GCMĆ for -1 (although I've also just posted a 14-byter with a different approach).

JavaScript (ES6), 71 bytes
(W,G,C,M)=>[...'GCMG'].map(X=>`${X.repeat(W)}
`.repeat(eval(X))).join``

Woohoo, beat 3 other JavaScript answers!

f=
(W,G,C,M)=>[...'GCMG'].map(X=>`${X.repeat(W)}
`.repeat(eval(X))).join``

console.log(
    f(10, 3, 2, 1)
)

Nice, very nice - gets my vote.

MATL, 17 bytes
'GCMG'iK:)Y"!liX"

Input format is: first input [G, C, M], second input W.
Try it online!
Explanation with example
Consider inputs [3 2 1]  and 10.
'GCMG' % Push this string
       % STACK: 'GCMG'
i      % Take first input: array of three numbers
       % STACK: 'GCMG', [3 2 1]
K:     % Push [1 2 3 4]
       % STACK: 'GCMG', [3 2 1], [1 2 3 4]
)      % Index (modular, 1-based). This repeats the first entry of the input array
       % STACK: 'GCMG', [3 2 1 3]
Y"     % Run-length decoding
       % STACK: 'GGGCCMGGG'
!      % Transpose. Gives a column vector of chars
       % STACK: ['G'; 'G'; 'G'; 'C'; 'C'; 'M'; 'G'; 'G'; 'G']
l      % Push 1
       % STACK: ['G'; 'G'; 'G'; 'C'; 'C'; 'M'; 'G'; 'G'; 'G'], 1
i      % Take second input: number
       % STACK: ['G'; 'G'; 'G'; 'C'; 'C'; 'M'; 'G'; 'G'; 'G'], 1, 10
X"     % Repeat the specified numbers of times along first and second dimensions
       % STACK: ['GGGGGGGGGG';'GGGGGGGGGG';'GGGGGGGGGG';'CCCCCCCCCC';...;'GGGGGGGGGG']
       % Implicitly display

C#, 204 bytes

Golfed
(w,g,c,m)=>{string G="\n".PadLeft(++w,'G'),C="\n".PadLeft(w,'C'),M="\n".PadLeft(w,'M'),o="".PadLeft(g,'G');o+="".PadLeft(m,'M')+"".PadLeft(c,'C')+o;return o.Replace("G",G).Replace("C",C).Replace("M",M);};

Ungolfed
( w, g, c, m ) => {
   string
      G = "\n".PadLeft( ++w, 'G' ),
      C = "\n".PadLeft( w, 'C' ),
      M = "\n".PadLeft( w, 'M' ),
      o = "".PadLeft( g, 'G' );

   o +=
      "".PadLeft( m, 'M' ) +
      "".PadLeft( c, 'C' ) +
      o;

   return o
      .Replace( "G", G )
      .Replace( "C", C )
      .Replace( "M", M );
};

Ungolfed readable
// Function with 4 parameters
//   w : Width
//   g : Graham
//   c : Chocolate
//   m : Marshmallow
( w, g, c, m ) => {

   // Initialization of vars with the contents
   //    of each line, with a new line at the end
   string
      G = "\n".PadLeft( ++w, 'G' ),
      C = "\n".PadLeft( w, 'C' ),
      M = "\n".PadLeft( w, 'M' ),

      // Trick to reduce the byte count
      //   Initialize the output with n 'G's
      o = "".PadLeft( g, 'G' );

   // Add again n 'M's and n 'C's
   //   Append the 'G's at the end.
   o +=
      "".PadLeft( m, 'M' ) +
      "".PadLeft( c, 'C' ) +
      o;

   // Replce every instance of 'G'/'C'/'M'
   //    with the full line
   return o
      .Replace( "G", G )
      .Replace( "C", C )
      .Replace( "M", M );
};

Full code
using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<Int32, Int32, Int32, Int32, String> f = ( w, g, c, m ) => {
            string
               G = "\n".PadLeft( ++w, 'G' ),
               C = "\n".PadLeft( w, 'C' ),
               M = "\n".PadLeft( w, 'M' ),
               o = "".PadLeft( g, 'G' );

            o +=
               "".PadLeft( m, 'M' ) +
               "".PadLeft( c, 'C' ) +
               o;

            return o
               .Replace( "G", G )
               .Replace( "C", C )
               .Replace( "M", M );
         };

         List<Tuple<Int32, Int32, Int32, Int32>>
            testCases = new List<Tuple<Int32, Int32, Int32, Int32>>() {
               new Tuple<Int32, Int32, Int32, Int32>( 1, 1, 1, 1 ),
               new Tuple<Int32, Int32, Int32, Int32>( 1, 1, 1, 2 ),
               new Tuple<Int32, Int32, Int32, Int32>( 1, 1, 2, 1 ),
               //
               // ...
               //
               // The link above contains the code ready to run
               //    and with every test from the pastebin link
               //
               // Yes, it contains 342 tests ready to run.
               //
               // I can barely fit every test on a 1080p screen...
               //    ... and there's 6 tests per line... Jebus...
               //
            };

         foreach( var testCase in testCases ) {
            Console.WriteLine( $"Input:\nWidth: {testCase.Item1,3} Graham: {testCase.Item2,3} Chocolate: {testCase.Item3,3} Marshmellow: {testCase.Item4,3}\nOutput:\n{f( testCase.Item1, testCase.Item2, testCase.Item3, testCase.Item4 )}\n" );
         }

         Console.ReadLine();
      }
   }
}

Releases

v1.0 - 204 bytes - Initial solution.

Notes

Looking for a picture of my beautiful test screen?
On a second thought, CSharpPad can't handle those tests, here's a version with fewer tests

Appreciated! :D

Ruby, 47 bytes
->w,g,c,m{puts r=[?G*w]*g,[?C*w]*c,[?M*w]*m,r}

thanks to ventero
Ruby, 51 bytes
->w,g,c,m{(?G*g+?C*c+?M*m+?G*g).chars{|i|puts i*w}}

Call like this:
f=->w,g,c,m{(?G*g+?C*c+?M*m+?G*g).chars{|i|puts i*w}}

f[10,3,2,1]

->w,g,c,m{puts r=[?G*w]*g,[?C*w]*c,[?M*w]*m,r} is a bit shorter

C, 108 105 bytes
Thanks to @Quentin for saving 3 bytes!
#define F(i,c)for(;i--;puts(""))for(j=w;j--;)putchar(c);
i,j;f(w,g,c,m){i=g;F(i,71)F(c,67)F(m,77)F(g,71)}

Try it online!

#define F(i,c)for(;i--;puts(""))for(j=w;j--;)putchar(c); saves three bytes :)

@Quentin Thanks! I wonder why I missed that in the first place :)

PowerShell, 49 bytes
$a,$b=$args;0..2+0|%{,("$('GCM'[$_])"*$a)*$b[$_]}

Try it online!
Takes input as four command-line arguments, width graham chocolate marshmallow, stores the first into $a and the rest into $b (implicitly as an array). Loops from over the range 0,1,2,0. Each loop, we index into string GCM, re-cast that char as a string, and multiply it out by $a (the width), and then using the comma-operator ,, turns that into an array by multiplying the appropriate index of $b (i.e., how many layers). Those resultant string arrays are all left on the pipeline and output is implicit, with a newline between elements.

Batch, 146 bytes
@set s=
@for /l %%i in (1,1,%1)do @call set s=G%%s%%
@for %%w in (%2.%s% %3.%s:G=C% %4.%s:G=M% %2.%s%)do @for /l %%i in (1,1,%%~nw)do @echo%%~xw

Relies on the obscure behaviour of echo in that it can often ignore the symbol between echo and the text to be echoed to collapse the four loops into a nested loop.

V, 22 bytes
éGÄÀäjMoC
MÀÄkÀÄHdêÀP

Try it online!
Hexdump:
00000000: e947 c4c0 e46a 4d6f 430a 4d1b c0c4 6bc0  .G...jMoC.M...k.
00000010: c448 64ea c050                           .Hd..P

Input order is
Graham, Marshmallow, Chocolate, Width

Explanation:
éG                  " Insert 'G'
  Ä                 " Duplicate this line
   Àäj              " *arg1* times, duplicate this line and the line below it
      M             " Move to the middle line
       o            " Open up a newline, and enter insert mode
        C<cr>M<esc> " Insert 'C\nM'
ÀÄ                  " Make *arg2* copies of this line (Marshmallow)
  k                 " Move up one line
   ÀÄ               " Make *arg3* copies of this line (Chocolate)
     H              " Move to the first line
      dê            " Delete this column
        ÀP          " And paste it horizontally *arg4* times

Could you add an explanation?

@programmer5000 Sure! See my edit

05AB1E, 14 bytes
Code:
…GCM‚øü×¬)˜S×»

Uses the CP-1252 encoding. Try it online!
Explanation:
…GCM              # Push the string "GCM"
    ‚             # Wrap with the input
     ø            # Transpose the array
      ü×          # Compute the string product of each element (['A', 3] --> 'AAA')
        ¬)˜       # Get the last element and append to the list
           S      # Split the list
            ×     # Vectorized string multiplication with the second input
             »    # Join by newlines and implicitly print

Excel, 104 bytes
Oh, boy! A formula that requires line breaks.
=REPT(REPT("G",A1)&"
",A2)&REPT(REPT("C",A1)&"
",A3)&REPT(REPT("M",A1)&"
",A4)&REPT(REPT("G",A1)&"
",A2)

A1 has Width
A2 has Graham
A3 has Chocolate
A4 has Mallow

If pre-formatting is allowed, then you can format the cell for Vertical Text and shorten the formula to 65 bytes:
=REPT(REPT("G",A2)&REPT("C",A3)&REPT("M",A4)&REPT("G",A2)&"
",A1)

Jelly, 13 bytes
“GCM”ẋ"ṁ4Fẋ€Y

A dyadic program. Inputs are: [Graham's, Chocolates, Marshmallows], Width.
Try it online!
How?
“GCM”ẋ"ṁ4Fẋ€Y - Main link: [g,c,m], w    e.g. [1,2,1], 2
“GCM”         - literal ['G', 'C', 'M']
      "       - zip that and [g,c,m] with the dyadic operation:
     ẋ        -     repeat list               [['G'],['C','C'],['M']]
       ṁ4     - mould like [1,2,3,4]          [['G'],['C','C'],['M'],['G']]
         F    - flatten                       ['G','C','C','M','G']
          ẋ€  - repeat €ach w times           [['G','G'],['C','C'],['C','C'],['M','M'],['G','G']]
            Y - join with line feeds          ['G','G','\n','C','C','\n','C','C','\n','M','M','\n','G','G']
              - implicit print                GG
                                              CC
                                              CC
                                              MM
                                              GG

Python 2, 6757 bytes
(Edit: now that matrices are allowed, no need to newline-join it.)

def s(w,g,c,m):g=['G'*w]*g;print g+['C'*w]*c+['M'*w]*m+g

PHP, 85 Bytes
for($m=$argv;$i++<4;)for($c=$m[_2342[$i]]*$m[1];$c;)echo$c--%$m[1]?"":"\n",_GCMG[$i];

or
for($m=$argv;$i++<4;)for($c=$m[_2342[$i]];$c--;)echo"\n".str_pad("",$m[1],_GCMG[$i]);

Online Versions
PHP, 96 Bytes
<?[$n,$w,$G,$C,$M]=$argv;for(;$i<4;$i++)for($t=${"$n[$i]"};$t--;)echo"\n".str_pad("",$w,$n[$i]);

Online Version
Expanded
[$n,$w,$G,$C,$M]=$argv; # $argv[0] must contain a file beginning with "GCMG"
for(;$i<4;$i++) # Take the first 4 values of the filename
for($t=${"$n[$i]"};$t--;) # How many rows should be printed
echo"\n".str_pad("",$w,$n[$i]); # print $w times the actual letter

Swift, 138 137 134 130 bytes
Saved 7 bytes thanks to @Kevin
let f=String.init(repeating:count:)
let r={w,g,c,m in f(f("G",w)+"\n",g)+f(f("C",w)+"\n",c)+f(f("M",w)+"\n",m)+f(f("G",w)+"\n",g)}

Two functions that return the expected value: f is a helper function and r is the actual lamdba-like function that generates the output. Usage: print(r(10,3,2,1))
Check it out!

You can save several characters by just referencing the string initializer directly (var f=String.init(repeating:count:);). And it doesn't save you any characters but it doesn't cost any so they should both really be let.

And 3 more by dropping the explicit arguments in r (let r={f(f("G",$0)+"\n",$1)+f(f("C",$0)+"\n",$2)+f(f("M",$0)+"\n",$3)+f(f("G",$0)+"\n",$1)})

@Kevin Thanks, I had no idea that you can initialise a value to something like this: f=String.init(repeating:count:)...

@Kevin when it comes to your second suggestion, it seems like it exceeds the number of bytes in UTF-8, checked the byte count on TIO, don't know why

C, 90 bytes (based on Steadybox's answer)
Renamed the variables and exploited the stringification preprocessor operator to cut down on the macro parameters. I hope posting this idea as its own answer is fine :)
#define F(x)for(i=x;i--;puts(""))for(j=w;j--;)printf(#x);
i,j;f(w,G,C,M){F(G)F(C)F(M)F(G)}

TIO link

Would upvote, but hit vote limit :(

Java, 138 bytes
String s(int w,int g,int c,int m){String b="";int i=-g-c,j;for(;i++<g+m;){for(j=0;j++<w;)b+=i<=-c|i>m?'G':i<=0?'C':'M';b+="\n";}return b;}

Try it online!
Explanation:
String s(int w, int g, int c, int m) {
    String b = "";
    int i = -g - c, j;              // i is the layer
    for (; i++ < g + m;) {          // Repeat (G+C+M+G) times, starting from -g-c to m+g
                                    //Layer 0 is the last chocolate layer

        for (j = 0; j++ < w;) {     // Repeat W times
            b +=
                i <= -c | i > m ? 'G': //If before the chocolate or after the marshmellow, output a G
                i <= 0 ? 'C' :      // Else if equal or before last chocolate layer output C
                'M';                //Otherwise output an M
        }
        b += "\n";
    }
    return b;
}

Not bad...for Java!

C# (150 bytes)
void S(int w,int g,int c,int m){P(w,g,'G');P(w,c,'C');P(w,m,'M');P(w,g,'G');}void P(int w,int i,char c){while(i-->0)Console.Write("\n".PadLeft(w,c));}

Ungolfed:
void SMores(int w, int g, int c, int m)
{
    Print(w,g,'G');
    Print(w,c,'C');
    Print(w,m,'M');
    Print(w,g,'G');
}
void Print(int w, int i, char c)
{
    while(i-->0)
        Console.Write("\n".PadLeft(w,c));
}

JS (ES6), 111 bytes
n=`
`,G="G",C="C",M="M",r=(s,t)=>s.repeat(t),(w,g,c,m)=>r(r(G,w)+n,g)+r(r(C,w)+n,c)+r(r(M,w)+n,m)+r(r(G,w)+n,g)

Convex, 20 bytes
"GCM"f*]z{~N+*}%(_@@

Try it online!

JS (ES6), 87 bytes
x=(w,g,c,m)=>(f=>f`Gg`+f`Cc`+f`Mm`+f`Gg`)(([[x,y]])=>(x.repeat(w)+`
`).repeat(eval(y)))

x acts as a standalone lambda function. The result has a trailing newline.
Try in a snippet:

x=(w,g,c,m)=>(f=>f`Gg`+f`Cc`+f`Mm`+f`Gg`)(([[x,y]])=>(x.repeat(w)+`
`).repeat(eval(y)))

function doTheThing() {
  document.getElementById("target").innerText = x(
    document.getElementById("width").value,
    document.getElementById("graham").value,
    document.getElementById("chocolate").value,
    document.getElementById("marshmallow").value,
  )
}
Width: <input id='width' value='10'>
Graham: <input id='graham' value='3'>
Chocolate: <input id='chocolate' value='2'>
Marshmallow: <input id='marshmallow' value='1'>

<button onclick='doTheThing()'>Do the thing</button>

JavaScript (ES6), 91 bytes
Includes trailing newline.

f=

(w,g,c,m)=>(b=(`G`[r=`repeat`](w)+`
`)[r](g))+(`C`[r](w)+`
`)[r](c)+(`M`[r](w)+`
`)[r](m)+b

console.log(f(10,3,2,1))

JavaScript ES6, 69 68 66 bytes
Thanks @Arnauld for golfing off one byte
a=>b=>"GCMG".replace(/./g,(c,i)=>`${c.repeat(a)}
`.repeat(b[i%3]))

Try it online!
Explanation
Receives input in curried format (Width)([Graham,Chocolate,Marshmallow])
Using .replace(/./g,...) replaces each character in the string GCMG with the return value from the function (c,i)=>`${c.repeat(a)}
`.repeat(b[i%3])
`${c.repeat(a)}
` creates each line of the graham cracker with a newline appended
.repeat(b[i%3]) repeats this line the required number of times

Using replace() would save a byte: a=>"GCMG".replace(/./g,(c,i)=>\${c.repeat(a[0])}\n`.repeat(a[1+i%3]))`

Java 11, 226 171 132 bytes
(w,g,c,m)->{x(w,"G",g);x(w,"C",c);x(w,"M",m);x(w,"G",g);};void x(int w,String c,int x){for(;x-->0;)System.out.println(c.repeat(w));}

-55 bytes thanks to @ceilingcat.
Try it online.
Explanation:
(w,g,c,m)->{            // Main method with four integer parameters and String return-type
  x(w,"G",g);           //  Print all Graham rows
  x(w,"C",c);           //  Print all Chocolate rows
  x(w,"M",m);           //  Print all Marshmallon rows
  x(w,"G",g);}          //  Print all Graham rows again

void x(int w,String c,int x){
                        // Separated method with two integer & character parameters and
                        // String return-type
  for(;x-->0;)          //  Loop `x` amount of times:
    System.out.println( //   Print with trailing newline:
      c                 //    The given character `c`
       .repeat(w));}    //    repeated `w` amount of times

Not bad...for java!

@programmer5000 Hehe, thanks! I like golfing in Java 7 (and sometimes 8), although I don't think it will ever even compete with other answers.. The only time 'somewhat competed' with a Java answer was with this 8 byte answer and this 19 byte answer, actually outgolfing Python for the first time. ;p Although those golfing languages with their 1 or 2 byte submissions still leave Java in the dust of course.

@ceilingcat Thanks! This is a pretty old answer, so going from Java 7 to Java 11 saves a bunch more bytes. ;)

F# (148 99 bytes)
let s w q="GCMG"|>Seq.iteri(fun i c->for j in 1..(q|>Seq.item(i%3))do printf"%A"("".PadLeft(w,c)))

Usage:
s 10 [2;3;4]

Ungolfed:
let smores width quantities =
    "GCMG"
    |>Seq.iteri(fun i char ->
        for j in 1..(quantities|>Seq.nth(i%3))
            do printf "%A" ("".PadLeft(width,char)))

I'm still new to F#, so if I did anything weird or stupid, please let me know.

A link to F# would be nice.

Google Sheets, 103 Bytes
Anonymous Google Sheets worksheet formula that takes input from cells A1,B1,C1,D1 and outputs a s'more to the calling cell
=REPT(REPT("G",A1)&"
",B1)&REPT(REPT("C",A1)&"
",C1)&REPT(REPT("M",A1)&"
",D1)&REPT(REPT("G",A1)&"
",B1

K (oK), 32 17 bytes
Solution:
{x#',/4#y#'"GCM"}

Try it online!
Example:
> {x#',/4#y#'"GCM"}[10;(3;2;1)]
("GGGGGGGGGG"
 "GGGGGGGGGG"
 "GGGGGGGGGG"
 "CCCCCCCCCC"
 "CCCCCCCCCC"
 "MMMMMMMMMM"
 "GGGGGGGGGG"
 "GGGGGGGGGG"
 "GGGGGGGGGG")

Explanation:
{x#',/4#y#'"GCM"} / solution
{               } / lambda function with implicit parameters x and y
        y#'"GCM"  / take input each-both (#') number "G", "C" and "M"
      4#          / 4-take, ("GGG";"CC";"M") -> ("GGG";"CC";"M";"GGG")
    ,/            / flatten list into string, ("GGG";"CC";"M";"GGG") -> "GGGCCMGGG"
 x#'              / width-take each (10#"G" -> "GGGGGGGGGG" etc)

Notes:

-15 bytes as looking through other answers it seems acceptable to take parameters as [width;(graham;chocolate;marshmallow)], which means I don't have to explicitly list the parameters to the function

Canvas, 12 11 bytes
GCMG｛²└＠＊×Ｐ

Try it here!
Explanation:
GCMG     push "GCMG"
  {      for each character
   ²       push the counter.                     Stack: [(input2, input1), "G", 1]
    └      swap two items below ToS.             Stack: [(I1, I2), "G", I1, 1]
     @     get the counter'th item of the input. Stack: [(I1, I2), "G", I1[1] ]
      *    repeat horizontally.                  Stack: [(I1, I2), "G" * I1[1] ]
       ×   repeat vertically.                    Stack: [(I2, I1), I2 × "G" * I1[1] ]
        P  print that.                           Stack: [(I2, I1)]

R, 69 bytes
function(n,u)cat(rep(strrep(c("G","C","M","G"),n),c(u,u[1])),sep="
")

Try it online!
Trying this strrep function I just heard about... Probably a intToUtf8 approach could do better than that.
Thanks @Shaggy for pointing an issue...fixing it saved 6 bytes.

There's only one layer of chocolate.

@Shaggy you just saved me 6 bytes, ty!

@dzaima it takes a width n and a vector of heights u which you can input as c(g,c,m), like this

@Giuseppe oh. Really shouldn't ask questions about languages I don't know :p

Vyxal, 11 bytes
`GCM`f*εǏf⁋

Try it Online!
`GCM`f      # "GCM" as a char list
      *     # repeat each by width
       ε    # repeat each by input size amounts
        Ǐ   # Append the first item
         f  # Flatten
          ⁋ # Join by newlines

J, 14 bytes
#&>'GCMG'#~4&$

Attempt This Online!
Takes input as 10 f 3 2 1 for the example test case.
#&>'GCMG'#~4&$
           4&$    Cycle the right side to length 4; [3 2 1 3]
   'GCMG'#~       Repeat each char of GCMG that many times; 'GGGCCMGGG'
#&>               Repeat each char `left side` times and stack them into a matrix

Haskell, 91 bytes
import Data.List
(#)=replicate
f w g c m=intercalate"\n"$map(w#)$g#'G'++c#'C'++m#'M'++g#'G'

Should be pretty self-explanatory. Since it was noted in a comment that character matrices are allowed, here's a 58 byte version that returns a list of strings (one for each layer):
(#)=replicate
f w g c m=map(w#)$g#'G'++c#'C'++m#'M'++g#'G'

Mathematica 102 Bytes (100 Characters)
Heard the s'mores built-in isn't coming out til V12.
s=StringRepeat;StringReplace[s@@@({Characters@"GCMG",#/.#[[4]]->#[[1]]})<>"",x_:>x~s~#[[4]]<>"\n"]&

Pretty straightforward using the idea of building up a column first. Long function names waste 35 bytes.  The one box-looking symbol is actually a transpose character and will paste into Mathematica just fine.
Usage:
%@{Graham, Chocolate, Marshmallows, Width}
e.g.
%@{3, 2, 1, 11}

R, 117 114 bytes
f=function(w,g,h,m){s=strrep;f=function(a,b)s(paste0(s(a,w),'\n'),b);G=f("G",g);cat(G,f("C",h),f("M",m),G,sep='')}

Explanation:
function(w,g,h,m){              #width, graham, chocolate, marshmallow
  s=strrep                      #repeats strings (for each layer)
  f=function(a,b){              #for a given layer
    s(paste0(s(a,w),'\n'),b)    #repeat the corresponding letter w times, then repeat that + a newline the corresponding number of times
  }
  G=f("G",g)
  cat(                        #print to console:
      G,                 #so repeat "G" w times, over g lines
      f("C",h),                 #etc.
      f("M",m),
      G,sep='')        #with no separation
}

Saved 3 bytes thanks to @Giuseppe!

This can be shortened to 97 bytes with a different approach:  function(w,g,s,m)matrix(c(rep("G",w*g),rep("S",w*s),rep("M",w*m),rep("G",w*g)),g*2+s+m,w,byrow=T)

That seems to output a matrix, which doesn't quite look like what the OP specified.

Removing the brackets throws an error, but great catch on the 3 bytes!

Japt, 30 26 bytes
"GCMG"¬mpU £XÄ pVgY)q1Ãm·q

Try it online!
30-byte solution:
Y=VÆ'GpUÃ·[YWÆ'CpUÃ·XÆ'MpUÃY]·

Try it online!

T-SQL, 259 bytes
CREATE PROC S @ INT,@g INT,@c INT,@m INT,@b INT=0 AS SET @B=@G G:PRINT REPLICATE('G',@)SET @G-=1IF @G>0 GOTO G C:PRINT REPLICATE('C',@)SET @C-=1IF @C>0GOTO C M:PRINT REPLICATE('M',@)SET @M-=1IF @M>0GOTO M Q:PRINT REPLICATE('G',@)SET @B-=1IF @B>0 GOTO Q RETURN

This stored procedure loops for the first layer or graham, chocolate, and Marshmallow with a GOTO in order to print up to the established amount. For the last layer of graham the fourth optional parameter (previously setted to the @g value) is used to do the same as the first layer of graham. The width of the layer is created with the REPLICATE function.
Usage:
EXECUTE S @ = 5, --Width
    @g = 7, --Graham
    @c = 8, --Chocolate
    @m = 4, --Marshmallow
    @b = NULL --Control variable, can be ignored

Charcoal, 23 bytes
↷²Ｎγ×⟦⁺⁺⁺×Gγ×CＮ×MＮ×Gγ⟧Ｎ

Try it online!
Input is in the form graham, chocolate, marshmallow, width
Explanation
↷²                          Pivot right by 2 * 45 degrees
  Ｎγ                       Input number to g
      ⟦⁺⁺⁺×Gγ×CＮ×MＮ×Gγ⟧   "G" * g + "C" * input number + "M" * input number + "G" * g
     ×                   Ｎ Multiplied by N

Lists are implicitly printed joined by newlines.

I think you can save a byte by inputting ×GＮ to γ and another byte by using ↓ instead of ↷². (Note that the existing code no longer works because × now vectorises but you can concatenate a newline for the same byte count.)

SOGL V0.12, 11 bytes
GCM”{e*.∙Q≥

Try it Here!
Explanation:
GCM”         push "GCM"
    {        for each
     e*        multiply horizontally by e, which, when first called, gets the numerical value of the next input
       .∙      multiply vertically by the nest input
         Q     output without popping and without disabling implicit output
          ≥    put the top item of the stack at the bottom as to keep the first item on the top

wasn' sogl v0.12 released after this challange?

@FelipeNardiBatista Yes, but that's now allowed.

Japt -R, 16 bytes
"GCMG"ËpU*VgEÃòU

Try it

Explanation
                     :Implicit input of integer U=Width & array V=[Graham,Chocolate,Marshmallow]
"GCMG"               :String literal
      Ë              :Map each character at index E
       p             :  Repeat
        U*           :   U multiplied by
          VgE        :   Get the integer at index E in V (Yay, index wrapping!)
             Ã       :End mapping
              òU     :Split to an array of strings of length U
                     :Implicitly join with newlines and output

05AB1E, 14 12 bytes
…GCMS×ĆIĆÅΓ»

Try it online.
Explanation:
…GCM          # Push string "GCM"
    S         # Convert it to a list of characters: ["G","C","M"]
     ×        # Repeat each the (implicit) input-integer `w` amount of times as string
              #  i.e. w=4 → ["GGGG","CCCC","MMMM"]
      Ć       # Enclose this list; appending its own head as trailing item
              #  → ["GGGG","CCCC","MMMM","GGGG"]
       IĆ     # Push the second input-list, and enclose it as well
              #  i.e. [3,2,1] → [3,2,1,3]
         ÅΓ   # Run-length decode, repeating the strings the integers amount of times
              #  → ["GGGG","GGGG","GGGG","CCCC","CCCC","MMMM","GGGG","GGGG","GGGG"]
           »  # And join this list by newlines
              #  → "GGGG\nGGGG\nGGGG\nCCCC\nCCCC\nMMMM\nGGGG\nGGGG\nGGGG"
              # (after which the result is output implicitly)