Open In App

How to begin with Competitive Programming?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report
 

At the very beginning to competitive programming, barely anyone knows the coding style to be followed. Below is an example to help you understand how problems are crafted in competitive programming.
 

competitive-programming

Let us consider below problem statement as an example. 
Problem Statement: 
 

Linear Search: Given an integer array and an element x, find if element is present in array or not. If element is present, then print index of its first occurrence. Else print -1.
Input: 
First line contains an integer, the number of test cases ‘T’. Each test case should be an integer. Size of the array ‘n’ in the second line. In the third line, input the integer elements of the array in a single line separated by space. Element X should be input in the fourth line, i.e., after entering the elements of array. Repeat the above steps second line onwards for multiple test cases.
Output: 
Print the output in a separate line returning the index of the element X. If the element is not present, then print -1.
Constraints: 
1 <= T <= 100 
1 <= n <= 100 
1 <= arr[i] <= 100
Example Input and Output for Your Program: 
 

Input:
2
4
1 2 3 4
3
5
10 90 20 30 40
40
Output:
2
4

Explanation: 
 

There are 2 test cases (Note 2 at the beginning of input)
Test Case 1: Input: arr[] = {1, 2, 3, 4},
Element to be searched = 3.
Output: 2
Explanation: 3 is present at index 2.
Test Case 2: Input: arr[] = {10, 90, 20, 30, 40},
Element to be searched = 40.
Output: 4
Explanation: 40 is present at index 4.

 

C++




// A Sample C++ program for beginners with Competitive Programming
#include<iostream>
using namespace std;
 
// This function returns index of element x in arr[]
int search(int arr[], int n, int x)
{
    for (int i = 0; i < n; i++)
    {
        // Return the index of the element if the element
        // is found
        if (arr[i] == x)
            return i;
    }
 
    // return -1 if the element is not found
    return -1;
}
 
int main()
{
    // Note that size of arr[] is considered 100 according to
    // the constraints mentioned in problem statement.
    int arr[100], x, t, n;
 
    // Input the number of test cases you want to run
    cout << "Enter the number of test cases: ";
    cin >> t;
 
    // One by one run for all input test cases
    while (t--)
    {
        // Input the size of the array for the current test case
        cout << "Enter the size of array for this test case: ";
        cin >> n;
 
        // Input the array elements for the current test case
        cout << "Enter " << n << " elements of array separated by space: ";
        for (int i = 0; i < n; i++)
            cin >> arr[i];
 
        // Input the element to be searched for the current test case
        cout << "Enter the element to be searched: ";
        cin >> x;
 
        // Compute and print result
        cout << search(arr, n, x) << "\n";
    }
    return 0;
}


C




// A Sample C program for beginners with Competitive Programming
#include<stdio.h>
 
// This function returns index of element x in arr[]
int search(int arr[], int n, int x)
{
    int i;
    for (i = 0; i < n; i++)
    {
       // Return the index of the element if the element
       // is found
       if (arr[i] == x)
         return i;
    }
 
    //return -1 if the element is not found
    return -1;
}
 
int main()
{
    // Note that size of arr[] is considered 100 according to
    // the constraints mentioned in problem statement.
    int arr[100], x, t, n, i;
 
    // Input the number of test cases you want to run
    scanf("%d", &t);
 
    // One by one run for all input test cases
    while (t--)
    {
        // Input the size of the array
        scanf("%d", &n);
 
        // Input the array
        for (i=0; i<n; i++)
           scanf("%d",&arr[i]);
 
        // Input the element to be searched
        scanf("%d", &x);
 
        // Compute and print result
        printf("%d\n", search(arr, n, x));
    }
    return 0;
}


Java




// A Sample Java program for beginners with Competitive Programming
import java.util.*;
import java.lang.*;
import java.io.*;
 
class LinearSearch
{
    // This function returns index of element x in arr[]
    static int search(int arr[], int n, int x)
    {
        for (int i = 0; i < n; i++)
        {
            // Return the index of the element if the element
            // is found
            if (arr[i] == x)
                return i;
        }
 
        // return -1 if the element is not found
        return -1;
    }
 
    public static void main (String[] args) throws IOException
    {
        // Note that size of arr[] is considered 100 according to
        // the constraints mentioned in problem statement.
        int[] arr = new int[100];
 
        // Using BufferedReader class to take input
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         
        int t = Integer.parseInt(br.readLine());
         
        // String Buffer to store answer
        StringBuffer sb = new StringBuffer();
 
        // One by one run for all input test cases
        while (t > 0)
        {
            // Input the size of the array
            int n = Integer.parseInt(br.readLine());
 
            // to read multiple integers line
            String line = br.readLine();
            String[] strs = line.trim().split("\\s+");
             
            // Input the array
            for (int i = 0; i < n; i++)
                arr[i] = Integer.parseInt(strs[i]);
 
            // Input the element to be searched
            int x = Integer.parseInt(br.readLine());
 
            // Compute and print result
            sb.append(search(arr, n, x)+"\n");
 
            t--;
        }
         
        System.out.print(sb);
    }
}


C#




using System;
 
class Program
{
    // This function returns index of element x in arr[]
    static int Search(int[] arr, int n, int x)
    {
        for (int i = 0; i < n; i++)
        {
            // Return the index of the element if the element is found
            if (arr[i] == x)
                return i;
        }
 
        // return -1 if the element is not found
        return -1;
    }
 
    static void Main(string[] args)
    {
        // Note that size of arr[] is considered 100 according to
        // the constraints mentioned in problem statement.
        int[] arr = new int[100];
        int x, t, n;
 
        // Input the number of test cases you want to run
        Console.Write("Enter the number of test cases: ");
        if (!int.TryParse(Console.ReadLine(), out t))
        {
            Console.WriteLine("Invalid input. Please enter a valid integer.");
            return;
        }
 
        // One by one run for all input test cases
        while (t-- > 0)
        {
            // Input the size of the array for the current test case
            Console.Write("Enter the size of array for this test case: ");
            if (!int.TryParse(Console.ReadLine(), out n))
            {
                Console.WriteLine("Invalid input. Please enter a valid integer.");
                continue;
            }
 
            // Input the array elements for the current test case
            Console.Write($"Enter {n} elements of array separated by space: ");
            string[] input = Console.ReadLine().Split();
            if (input.Length != n)
            {
                Console.WriteLine("Invalid input. Please enter exactly n elements separated by space.");
                continue;
            }
            for (int i = 0; i < n; i++)
            {
                if (!int.TryParse(input[i], out arr[i]))
                {
                    Console.WriteLine("Invalid input. Please enter valid integers separated by space.");
                    continue;
                }
            }
 
            // Input the element to be searched for the current test case
            Console.Write("Enter the element to be searched: ");
            if (!int.TryParse(Console.ReadLine(), out x))
            {
                Console.WriteLine("Invalid input. Please enter a valid integer.");
                continue;
            }
 
            // Compute and print result
            Console.WriteLine(Search(arr, n, x));
        }
    }
}


Javascript




// Function to search for the index of element x in arr[]
function search(arr, x) {
    for (let i = 0; i < arr.length; i++) {
        // Return the index of the element if found
        if (arr[i] === x)
            return i;
    }
 
    // Return -1 if the element is not found
    return -1;
}
 
// Main function
function main() {
    let t; // Number of test cases
    console.log("Enter the number of test cases: ");
    t = parseInt(prompt());
 
    // One by one run for all input test cases
    while (t--) {
        let n; // Size of the array
        console.log(`Enter the size of array for test case ${t + 1}: `);
        n = parseInt(prompt());
 
        let arr = new Array(n); // Array to store elements
        console.log(`Enter ${n} elements of array separated by space: `);
        let elements = prompt().split(' ');
 
        // Convert input string to integer array
        for (let i = 0; i < n; i++) {
            arr[i] = parseInt(elements[i]);
        }
 
        let x; // Element to be searched
        console.log("Enter the element to be searched: ");
        x = parseInt(prompt());
 
        // Compute and print the result
        console.log(`Result for test case ${t + 1}: ${search(arr, x)}`);
    }
}
 
// Calling the main function
main();


Python3




# A Sample Python program for beginners with Competitive Programming
 
# Returns index of x in arr if it is present,
# else returns -1
def search(arr, x):
    n = len(arr)
    for j in range(0,n):
        if (x == arr[j]):
            return j
    return -1
 
# Input number of test cases
print("Enter the number of test cases: ")
t = int(input())
 
# One by one run for all input test cases
for i in range(0,t):
 
    # Input the size of the array for the current test case
    print(f"Enter the size of array for test case {i + 1}: ")
    n = int(input())
 
    # Input the array elements for the current test case
    print(f"Enter {n} elements of array separated by space: ")
    arr = list(map(int, input().split()))
 
    # Input the element to be searched for the current test case
    print("Enter the element to be searched: ")
    x = int(input())
 
    # Print the result of the search operation for the current test case
    print(search(arr, x))
 
    # The element can also be searched by the index method
    # But you need to handle the exception when the element is not found
    # Uncomment the below line to get that working.
    # arr.index(x)


Common mistakes by beginners 
 

  1. Program should not print any extra character. Writing a statement like printf(“Enter value of n”) would cause rejection on any platform.
  2. Input and output format specifications must be read carefully. For example, most of the problems expect a new line after every output. So if we don’t write printf(“\n”) or equivalent statement in a loop that runs for all test cases, the program would be rejected.

How to Begin Practice? 
You can begin with above problem itself. Try submitting one of the above solutions here. It is recommended solve problems on Practice for cracking any coding interview.
Now you know how to write your first program in Competitive Programming Environment, you can start with School Practice Problems for Competitive Programming or Basic Practice Problems for Competitive Programming.

Platforms for practicing the Competitive Programming 

Related Courses

Competitive Programming – Live Course

Unleash the competitive programmer within you with our Competitive Programming – Live Course. In this course, you’ll learn important topics of DSA, improving problem-solving & coding skills, various techniques for competitive programming, and efficient implementation of mathematical algorithms. As soon as you start, better will be your programming skills. Enrol Now! We’ll see you inside the course!



Last Updated : 10 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads