The Wayback Machine - https://web.archive.org/web/20241107091632/https://www.geeksforgeeks.org/rock-paper-scissor-in-c/
Open In App

Rock Paper Scissor in C

Last Updated : 26 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Rock Paper Scissor (which is also called Stone Paper Scissor) is a hand game and played between two people, in which each player simultaneously forms one of three shapes. The winner of the game is decided as per the below rules:

  • Rock vs Paper -> Paper wins.
  • Rock vs Scissor -> Rock wins.
  • Paper vs Scissor -> Scissor wins.

In this game, the user will be asked to make choice and according to the choice of user and computer and then the result will be displayed along with the choices of both computer and user.

Approach: Below is the functionality that needed to be implemented in the program:

main() function: 

  • It consists of the declaration of the variables.
  • printf() and scanf() functions for displaying the content and taking input from the user. It also contains  two predefined functions:
    • srand() and rand() which are used to generate random numbers in the range [0, RAND_MAX) and srand() especially will help to generate a random number at each time.
    • Take modulo of random number generated with 100 to make its range between (0 and 100).
    • As the range is up to 100 only, the distribution among all the options i.e., stone, paper, and scissors is equal as all of them have an equal probability of coming.

Note: This random number will decide the choice of computer as:

  • If the number is between 0-33 then the choice will be Stone.
  • If the number is between 33-66 then the choice will be Paper.
  • If the number is between 66-100 then the choice will be Scissors.

game() function: This function consists of if-else statements that will compare the choice of user and computer. If the user wins then it will return 1. Otherwise, if the computer wins then it will return 0. If it is a tie, it will return -1.

Below is the implementation of the above approach:

C




// C program for the above approach
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
// Function to implement the game
int game(char you, char computer)
{
    // If both the user and computer
    // has choose the same thing
    if (you == computer)
        return -1;
 
    // If user's choice is stone and
    // computer's choice is paper
    if (you == 's' && computer == 'p')
        return 0;
 
            // If user's choice is paper and
            // computer's choice is stone
            else if (you == 'p' && computer == 's') return 1;
 
    // If user's choice is stone and
    // computer's choice is scissor
    if (you == 's' && computer == 'z')
        return 1;
 
    // If user's choice is scissor and
    // computer's choice is stone
    else if (you == 'z' && computer == 's')
        return 0;
 
    // If user's choice is paper and
    // computer's choice is scissor
    if (you == 'p' && computer == 'z')
        return 0;
 
    // If user's choice is scissor and
    // computer's choice is paper
    else if (you == 'z' && computer == 'p')
        return 1;
}
 
// Driver Code
int main()
{
    // Stores the random number
    int n;
 
    char you, computer, result;
 
    // Chooses the random number
    // every time
    srand(time(NULL));
 
    // Make the random number less
    // than 100, divided it by 100
    n = rand() % 100;
 
    // Using simple probability 100 is
    // roughly divided among stone,
    // paper, and scissor
    if (n < 33)
 
        // s is denoting Stone
        computer = 's';
 
    else if (n > 33 && n < 66)
 
        // p is denoting Paper
        computer = 'p';
 
    // z is denoting Scissor
    else
        computer = 'z';
 
    printf("\n\n\n\n\t\t\t\tEnter s for STONE, p for PAPER and z for SCISSOR\n\t\t\t\t\t\t\t");
 
    // input from the user
    scanf("%c", &you;);
 
    // Function Call to play the game
    result = game(you, computer);
 
    if (result == -1) {
        printf("\n\n\t\t\t\tGame Draw!\n");
    }
    else if (result == 1) {
        printf("\n\n\t\t\t\tWow! You have won the game!\n");
    }
    else {
        printf("\n\n\t\t\t\tOh! You have lost the game!\n");
    }
        printf("\t\t\t\tYOu choose : %c and Computer choose : %c\n",you, computer);
 
    return 0;
}


Output:

  • Firstly the user will be asked about the choice:

Output#1

  • When the user enters the choice then the result is displayed:

Output#2

 



Previous Article
Next Article

Similar Reads

Linked List in C
A linked list is a linear data structure where each element, known as a node, is connected to the next one using pointers. Unlike array, elements of linked list are stored in random memory locations. In this article, we will learn about the linked list, its types, representation of the linked list in C, and discuss what link list offers as compared
8 min read
How to Create a Linked List in C?
Write a C program to create a linked list. A linked list is a sequential data structure that stores the data in non-contiguous memory locations unlike array. In a linked list, each element is referred to as a node. Each node in the linked list stores data and a pointer to the next node present in the list. Example Input: 1 -> 2 -> 3 -> 4 -
5 min read
C Exercises - Practice Questions with Solutions for C Programming
The best way to learn C programming language is by hands-on practice. This C Exercise page contains the top 30 C exercise questions with solutions that are designed for both beginners and advanced programmers. It covers all major concepts like arrays, pointers, for-loop, and many more. So, Keep it Up! Solve topic-wise C exercise questions to streng
12 min read
Quick Sort in C
QuickSort is one of the best sorting algorithms that follows the divide-and-conquer approach like Merge Sort but unlike Merge Sort, this algorithm does in place sorting. In this article, we will learn how to implement quicksort in C language. What is QuickSort Algorithm?The basic idea behind QuickSort is to select a pivot element from the array and
4 min read
Reverse String in C
In C, reversing a string means rearranging the characters such that the last character becomes the first, the second-to-last character becomes the second, and so on. For example, Input: S = "hello"Output: "olleh"Explanation: The reverse of "hello" is "olleh". Input: S = "world"Output: "dlrow"Explanation: The reverse of "world" is "dlrow". Program t
4 min read
rand() in C
The rand() function in the C programming language is used to generate pseudo-random numbers. It is used in C to generate random numbers in the range 0 to RAND_MAX. The rand() function is part of the standard C library <stdlib.h> so to use this function, we need to include the <stdlib.h> library. Syntax of rand()int rand(void)ParametersT
3 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
Convert String to int in C
In C, we cannot directly perform numeric operations on a string representing a numeric value. We first need to convert the string to the integer type. In this article, we will discuss different ways to convert the numeric string to integer in C language. Example: Input: "1234"Output: 1234Explanation: The string "1234" is converted to the integer 12
6 min read
C Program For Bubble Sort
Bubble Sort is a comparison based simple sorting algorithm that works by comparing the adjacent elements and swapping them if the elements are not in the correct order. It is an in-place and stable sorting algorithm that can sort items in data structures such as arrays and linked lists. In this article, we will learn how to implement bubble sort al
4 min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
9 min read
C Functions
A function in C is a set of statements that when called perform some specific tasks. It is the basic building block of a C program that provides modularity and code reusability. The programming statements of a function are enclosed within { } braces, having certain meanings and performing certain operations. They are also called subroutines or proc
10 min read
C Program To Print Your Own Name
Printing your own name means displaying your name on the computer screen. In this article, we will learn how to print your own name using a C program. Examples Input: name = "Rahul"Output: RahulExplanation: The program prints "Rahul" to the screen. Input: name = "Vikas"Output: VikasExplanation: The program prints "Vikas" to the screen. Print Your O
4 min read
C Program to Make a Simple Calculator
A simple calculator is a program that can perform addition, subtraction, multiplication, and division of two numbers provided as input. In this article, we will learn to create a simple calculator program in C. Example Input: a = 10, b = 5, op = +Output: 15.00Explanation: Chosen operation is addition, so 10 + 5 = 15 Input: a = 12, b = 3, op = /Outp
3 min read
Matrix Multiplication in C
A matrix is a collection of numbers organized in rows and columns, represented by a two-dimensional array in C. Matrices can either be square or rectangular. In this article, we will learn the multiplication of two matrices in the C programming language. ExampleInput: mat1[][] = {{1, 2}, {3, 4}} mat2[][] = {{5, 6}, {7, 8}} Multiplication of two mat
3 min read
Macros and its types in C
In C, a macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;). Examples of Macros in CBelow are the programs to il
6 min read
C Program to Sort an Array in Ascending Order
Sorting an array in ascending order means arranging the elements from smallest element to largest element. In this article, we will learn how to sort an array in ascending order in a C program. Examples Input: arr = {170, 45, 75, 90, 802, 24, 2, 66}Output: arr = {2, 24, 45, 66, 75, 90, 170, 802}Explanation: The array is sorted from the smallest to
5 min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"The following C program displays "Hello World" in
2 min read
Arrow operator -> in C/C++ with Examples
An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below. Syntax: (pointer_name)->(variable_name) Operation: The -> operator in C or C++ gives the val
4 min read
GDB (Step by Step Introduction)
GDB stands for GNU Project Debugger and is a powerful debugging tool for C (along with other languages like C++). It helps you to poke around inside your C programs while they are executing and also allows you to see what exactly happens when your program crashes. GDB operates on executable files which are binary files produced by the compilation p
5 min read
C program to Find the Largest Number Among Three Numbers
Given 3 integer numbers, the task is to find the largest number among them. Examples Input: a = 10, b = 22, c = 19Output: 22 is the largest number.Explanation: Among the numbers 5, 8, and 3, the largest number is 8.Input: a = 12, b = 7, c = 9Output: 12 is the largest number.Explanation: Among the numbers 12, 7, and 9, the largest number is 12. Find
5 min read
C Program to Add Two Integers
Given two integers, the task is to add these integer numbers and return their sum. Examples Input: a = 5, b = 3Output: 8Explanation: The sum of 5 and 3 is 8. Input: a = -2, b = 7Output: 5Explanation: The sum of -2 and 7 is 5. Add Two Numbers in CIn C, we can add two numbers easily using addition operator (+). This operator works by taking two opera
4 min read
Prime Number Program in C
A prime number is a natural number greater than 1 and is completely divisible only by 1 and itself. In this article, we will learn how to check whether the given number is a prime number or not in C. Examples Input: n = 29Output: 29 is primeExplanation: 29 has no divisors other than 1 and 29 itself. Hence, it is a prime number. Input: n = 15Output:
3 min read
Generating Random Numbers in a Range in C
Write a C program to generate random numbers in a range. Examples Input: min = 5, max = 15Output: 9, 11, 2Explanation: Any integer between 5 and 15 can be the output. Input: min = 0, max = 100Output: 42, 27, 11, 98Explanation: Any integer between 0 and 100 can be the output. Different Ways to Generate Random Numbers in a Range in CWe can use any of
7 min read
C Program for Linear Search
Linear Search is a sequential searching algorithm in C that is used to find an element in a list. Linear Search compares each element of the list with the key till the element is found or we reach the end of the list. Example Input: arr = {10, 50, 30, 70, 80, 60, 20, 90, 40}, key: 30Output: Key Found at Index: 2Explanation: Start from index 0, comp
4 min read
C Program to Check for Palindrome String
A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program. Example Input: str = "madam"Output: "madam" is palindrome.Explanation: The reverse of "madam" is "madam". So, it is palindrome Input: str = "hello"Output
5 min read
Factorial Program in C
Write a C program to find the factorial of the given number. A factorial is the product of all the natural numbers less than or equal to the given number N. Examples Input: N = 5Output: 120Explanation: 5! = 5 × 4 × 3 × 2 × 1 = 120 Input: N = 0Output: 1Explanation: 0! = 1 by definition Different Ways to Find the Factorial of a Number in CThe logic o
4 min read
C Program to Swap Two Numbers
Swapping two numbers means exchanging their values. In this article, we will learn how to swap values of two numbers in a C program. Example Input: a = 5, b = 10Output: a = 10, b = 5 Input: a = 51, b = 17Output: a = 17, b = 51 Swap Two Numbers Using Temporary VariableThe easiest method to swap two numbers is to use a temporary variable. First, we a
3 min read
C Program for Merge Sort
Merge Sort is a comparison-based sorting algorithm that works by dividing the input array into two halves, then calling itself for these two halves, and finally it merges the two sorted halves. In this article, we will learn how to implement merge sort in C language. What is Merge Sort Algorithm?Merge sort is based on the three principles: divide,
3 min read
C Program For Insertion Sort
Insertion sort is a simple sorting algorithm used to sort a collection of elements in a given order. It is less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort but it is simple to implement and is suitable to sort small data lists. In this article, we will learn about the insertion sort, how it work
4 min read
C Program to Print Fibonacci Series
The Fibonacci series is the sequence where each number is the sum of the previous two numbers of the sequence. The first two numbers are 0 and 1 which are used to generate the whole series. Example Input: n = 5Output: 0 1 1 2 3Explanation: The first 5 terms of the Fibonacci series are 0, 1, 1, 2, 3. Input: N = 7Output: 0 1 1 2 3 5 8Explanation: The
4 min read
three90RightbarBannerImg