The function is defined piecewise:
y = x^2 - 3x + 4, if x < 5;
y = x + 7, if x \ge 5.
The conditions x < 5 and x \ge 5 are mutually exclusive and together cover all values of . Therefore, a single if ... else statement is enough.
Check the condition x < 5: if it is true, compute using the first formula; otherwise, use the second one. There is no need to check x \ge 5 separately in the else branch.
Since –1000 \le x \le 1000, the int type is sufficient.
Algorithm implementation
Read the input value of .
scanf("%d", &x);Find the value of .
if (x < 5)
y = x * x – 3 * x + 4;
else
y = x + 7;Print the result.
printf("%d\n",y);Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int y, x = con.nextInt();
if (x < 5)
y = x*x - 3*x + 4;
else
y = x + 7;
System.out.println(y);
con.close();
}
} Python implementation
Read the input value of .
x = int(input())Find the value of .
if x < 5:
y = x*x - 3*x + 4
else:
y = x + 7Print the result.
print(y)Go implementation
package main
import "fmt"
func main() {
var x, y int
fmt.Scanf("%d", &x)
if x < 5 {
y = x*x - 3*x + 4
} else {
y = x + 7
}
fmt.Println(y)
}C# implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppCSharp
{
class Program
{
static void Main(string[] args)
{
int x, y;
x = Convert.ToInt32(Console.ReadLine());
if (x >= 5)
y = x + 7;
else
y = x * x - 3 * x + 4;
Console.WriteLine("{0}", y);
}
}
}