Skip to main content

Hackerrank > CPP > Introduction

                            Introduction

01-Hello World!

Let's start with the mandatory ritual. Print the string "Hello, World!". You can either use printf (preferred for this tutorial) or cout.
printf("Hello, World!");
Sample Output
Hello, World!
Solution
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
    printf("Hello, World!");
    return 0;
}

02-Input and Output

For any program that we write the basic things that we need to do is take the input and print the expected output.
In C++ you can take the input using cin and print the output using cout.Unlike C where you need the format specifier in printf and scanf, here you can use cin and cout.
Taking Input:
If you want to input a number: cin>>n ,  where n is the number.
If you want to input a number and a string: cin>>n>>s, where s is the string.
Printing output:
If you want to output a single number: cout<<n
If you want to output a number and a string separated by a new line: cout<<n<<endl<<s (where endl moves the pinter to the new line and then string gets printed.)
Take three numbers as inputs and print the sum of the three numbers.
Input Format
The first line of the input contains three integers A,B and C.
1A,B,C1000
Output Format
In a single line print the sum of the three numbers.
Sample Input
1 2 7
Sample Output
10
Explanation
Sum of the three numbers 1,2 and 7 is 10.
Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int a = 0, b = 0, c = 0;
    cin >> a;
    cin >> b;
    cin >> c;
    cout << a + b + c;
    return 0;
}

03-Basic Data Types

C++ has the following data types along with their format specifier:
  • Int ("%d"): 32 Bit integer
  • Long ("%ld"): 32 bit integer (same as Int for modern systems)
  • Long Long ("%lld"): 64 bit integer
  • Char ("%c"): Character type
  • Float ("%f"): 32 bit real value
  • Double ("%lf"): 64 bit real value

Reading In order to read a data type, you need the following syntax:
scanf("`format_specifier`", &val)
E.g., in order to read a character and then a double
char ch;
double d;
scanf("%c %lf", &ch, &d);
P.S.: For the moment, we can ignore the spacing between format specifiers.

Printing In order to print a data type, you need the following syntax:
printf("`format_specifier`", val)
E.g., in order to print a character and then a double
char ch = 'd';
double d = 234.432;
printf("%c %lf", ch, d);
You can always use cin and cout instead of scanf and printf but if you are taking a million numbers as input and printing a million lines using scanf and printf is faster in such a case.
Input Format
Input will consist of an int, long, long long, char, float and double, each separated by a space.
Output Format
Print the elements in the same order, but each in a new line.
Sample Input
3 444 12345678912345 a 334.23 14049.30493
Sample Output
3
444
12345678912345
a
334.23
14049.30493
Solution
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
    int a;
    long int b;
    long long int c;
    char d;
    float e;
    double f;
    scanf("%d %ld %lld %c %f %lf", &a, &b, &c, &d, &e, &f);
    printf("%d\n%ld\n%lld\n%c\n%f\n%lf", a, b, c, d, e, f);
    return 0;

}

04-Conditional Statements

if and else are two of the most heavily used conditionals in C/C++. They are used to execute zero or one statement among many statements.
They are be used in the following three ways.
  1. if: It is used to execute a statement, given the condition is true.
    if(condition) {
        ...
    }
    
  2. if - else: It is used to execute exactly one of the two statements.
    if(first condition) {
        ...
    }
    else {
        ...
    }
    
  3. if - else if - else: It is used to execute one of the multiple statements.
    if(first condition) {
        ...
    }
    else if(second condition) {
        ...
    }
    .
    .
    .
    else if((n-1)'th condition) {
    
    }
    else {
        ...
    }
    

You are given a positive integer, n,:
  • If 1n9, then print the English representation of it. That is "one" for 1, "two" for 2, and so on.
  • Otherwise print "Greater than 9" (without quotes).
Input Format
Input will contain only one integer, n.
Sample Input
5
Sample Output
five
Sample Input #01
8
Sample Output #01
eight
Sample Input #02
44
Sample Output #02
Greater than 9
Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int n;
    string num[10] = {"Greater than 9", "one", "two", "three", "four",
        "five", "six", "seven", "eight", "nine"};
    cin >> n;
    if(n > 9){
        cout << num[0];
    }
    else{
        cout << num[n];
    }
    return 0;
}

05-For Loop

for loop is a programming language statement which allows co/e to be repeatedly executed.
The syntax for this is
for ( <expression_1> ; <expression_2> ; <expression_3> )
    <statement>
  • expression1_ is used for intializing variables which are generally used for controlling terminating flag for the loop.
  • expression2_ is used to check for the terminating condition. If this evaluates to false, then the loop is terminated.
  • expression3_ is generally used to update the flags/variables.
A sample loop will be
for(int i = 0; i < 10; i++) {
    ...
}
Input Format
You will be given two positive integers, a and b (ab), separated by a newline.
Output Format
For each integer n[a,b] (so all numbers in that range):
  • If 1n9, then print the English representation of it. That is "one" for 1, "two" for 2, and so on.
  • Else if n>9 and it is even, then print "even".
  • Else if n>9 and it is odd, then print "odd".
Note: [a,b] represents the interval, i.e., [a,b]={xZ| axb}={a, a+1,,b}
Sample Input
8
11
Sample Output
eight
nine
even
odd
Solution
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
    int a, b;
    string num[9] = {"one", "two", "three", "four", "five",
        "six", "seven", "eight", "nine"};
    cin >> a;
    cin >> b;
    for(int i = a; i <= b; i++) {
        if (i > 9) {
            if (i % 2 == 0) {
                cout << "even\n";
            }
            else {
                cout << "odd\n";
            }
        }
        else {
            cout << num[i-1] << "\n";
        }
    }
    return 0;
}

06-Functions

Functions are a bunch of statements glued together. A function is provided with zero or more arguments, and it executes the statements on it. Based on the return type, it either returns nothing (void) or something.
A sample syntax for a function is
return_type function_name(arg_type_1 arg_1, arg_type_2 arg_2, ...) {
    ...
    ...
    ...
    [if return_type is non void]
        return something of type `return_type`;
}
For example, a function to read four variables and return the sum of them can be written as
int sum_of_four(int a, int b, int c, int d) {
    int sum = 0;
    sum += a;
    sum += b;
    sum += c;
    sum += d
    return sum;
}

You have to write a function int maxoffour(int a, int b, int c, int d) which reads four arguments and returns the greatest of them.
Input Format
Input will contain four integers - a,b,c,d , one in each line.
Output Format
Print the greatest of the four integers. PS: I/O will be automatically handled.
Sample Input
3
4
6
5
Sample Output
6
Solution
#include <iostream>
#include <cstdio>
using namespace std;
int maxoffour(int a, int b, int c, int d) {
    int max = a;
    if (b > max) {
        max = b;
    }
    if (c > max) {
        max = c;
    }
    if (d > max) {
        max = d;
    }
    return max;
}
int main() {
    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = maxoffour(a, b, c, d);
    printf("%d", ans);
    return 0;
}

07-Pointer

pointer in C is a way to share a memory address among different contexts (primarily functions). They are primarily used whenever a function needs to modify the content of a variable, of which it doesn't have ownership.
In order to access the memory address of a variable, val, we need to prepend it with & sign. E.g., &val" returns the memory address of val.
This memory address is assigned to a pointer and can be shared among various functions. E.g. intp=&val will assign the memory address of val to pointer p. To access the content of the memory to which the pointer points, prepend it with a ". For example, p will return the value reflected by val and any modification to it will be reflected at the source (val).
void increment(int *v) {
    (*v)++;
}

int main() {
    int a;
    scanf("%d", &a);
    increment(&a);
    printf("%d", a);
    return 0;
}  

You have to complete the function void update(int *a,int *b), which reads two integers as argument, and sets a with the sum of them, and b with the absolute difference of them.
  • a=a+b
  • b=|ab|
Input Format
Input will contain two integers, a and b, separated by a newline.
Output Format
You have to print the updated value of a and b, on two different lines.
P.S.: Input/ouput will be automatically handled. You only have to complete thevoid update(int *a,int *b) function.
Sample Input
4
5
Sample Output
9
1
Explanation
  • a=4+5=9
  • b=|45|=1
Solution
#include <stdio.h>
#include <stdlib.h>     /* abs /
void update(int a,int b) {
    int c = a;
    int d = b;
    a = c + d;
    b = abs(c - d);
}
int main() {
    int a, b;
    int pa = &a, *pb = &b;
    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);
    return 0;
}

08-Arrays Introduction

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.
Declaration:
int arr[10]; //Declares an array named arr of size 10, i.e; you can store 10 integers.
Accessing elements of an array:
Indexing in arrays starts from 0.So the first element is stored at arr[0],the second element at arr[1]...arr[9]
You'll be an given array of N integers and you have to print the integers in the reverse order.
Input Format
The first line of the input contains N,where N is the number of integers.The next line contains N integers separated by a space.
Constraints
1<=N<=1000
1<=Ai<=10000, where <span class="MathJaxPreview">Ai is the <span class="MathJaxPreview">ith integer in the array.
Output Format
Print the N integers of the array in the reverse order in a single line separated by a space.
Sample Input
4
1 4 3 2
Sample Output
2 3 4 1
Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int n; 
    cin>>n;
    int numbers[n];
    for(int i = 0; i < n; i++) {
        cin >> numbers[i];
    }
    for(int i = n-1; i >= 0; i--) {
        cout << numbers[i] <<" ";
    }
    return 0;
}

09-Operator Overloading

Classes define new types in C++. Types in C++ not only interact by means of constructions and assignments but also via operators. For example:
int a=2, b=1, c;
c = b + a;
The result of variable c will be 3. Similarly, classes can also perform operations using operator overloading. Operators are overloaded by means of operator functions, which are regular functions with special names. Their name begins with the operator keyword followed by the operator sign that is overloaded. The syntax is:
type operator sign (parameters) { /*... body ...*/ }
You are given a main() function which takes a set of inputs to create two matrices and prints the result of their addition. You need to write the classMatrix which has a member a of type vector >. You also need to write a member function to overload the operator +. The function's job will be to add two objects of Matrix type and return the resultant Matrix.
Input Format
First line will contain the number of test cases T. For each test case, there are three lines of input.
The first line of each test case will contain two integers N and M which are the sizes of the rows and columns respectively of the two matrices that will follow on the next two lines. These next two lines will each contain NM elements of both the matrices in a row-wise format.
Constraints 1<=T<=1000 1<=N<=100 1<=M<=100 1<=Ai,j<=10 , where <span class="MathJaxPreview">Ai,j is the element in the <span class="MathJaxPreview">ith row and jth column of the matrix.
Output Format
The code provided in the editor will use your class Matrix and overloaded operator function to add the two matrices and give the output.
Sample Input
1
2 2
2 2 2 2
1 2 3 4
Sample Output
3 4 
5 6
Explanation
The sum of first matrix and the second matrix is the matrix given in the output.
Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Matrix{
    public:
        vector< vector<int> > a;
        Matrix operator + (const Matrix &other){
            Matrix mat;
            mat.a.reserve(1000);
            int n = a.size();
            int m = a[0].size();
            int i, j;
            for (i = 0; i < n; i++) {
                int sum = 0;
                vector<int> line;
                for (j = 0; j < m; j++) {
                    sum = this->a[i][j] + other.a[i][j];
                    line.pushback(sum);
                }
                mat.a.pushback(line);
            }
            return mat;
        }
};
int main () {
    int cases,k;
    cin >> cases;
    for(k=0;k<cases;k++) {
        Matrix x;
        Matrix y;
        Matrix result;
        int n,m,i,j;
        cin >> n >> m;
        for(i=0;i<n;i++) {
            vector<int> b;
            int num;
            for(j=0;j<m;j++) {
                cin >> num;
                b.pushback(num);
            }
            x.a.pushback(b);
        }
        for(i=0;i<n;i++) {
            vector<int> b;
            int num;
            for(j=0;j<m;j++) {
                cin >> num;
                b.pushback(num);
            }
            y.a.pushback(b);
        }
        result = x+y;
        for(i=0;i<n;i++) {
            for(j=0;j<m;j++) {
                cout << result.a[i][j] << " ";
            }
            cout << endl;
        }
    }

    return 0;
}

Comments

Popular posts from this blog

C Questions

C Questions
C Questions

Note : All the programs are tested under Turbo C/C++ compilers.
It is assumed that,
Programs run under DOS environment, The underlying machine is an x86 system, Program is compiled using Turbo C/C++ compiler.
The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed).
Predict the output or error(s) for the following:

void main()
{
int const * p=5; printf("%d",++(*p));
}
Answer:
Compiler error: Cannot modify a constant value.
Explanation:
p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".
main()
{
char s[ ]="man"; int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer: mmmm
aaaa nnnn
Explanation

Zoho Interview | Set 1 (Advanced Programming Round)

Third Round: (Advanced Programming Round) Here they asked us to create a “Railway reservation system” and gave us 4 modules. The modules were:
    1. Booking
    2. Availability checking
    3. Cancellation
    4. Prepare chart
We were asked to create the modules for representing each data first and to continue with the implementation phase.

 My Solution :

#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<string.h>#include<iostream.h>#include<time.h>#include<iomanip.h>#include<fstream.h>char f[10]="f";char s[10]="s";int addr,ad,flag,f1,d,m,i,amt;float tamt; class login {public:char id[100];char pass[100];char*password;void getid(){ cout<<"Enter your id:";gets(id); password=getpass("Enter the password:");strcpy(pass,password);}void displayid(){ cout<<"Id:";puts(id); cout<<"Password:";puts(pass);}}; class detail {public:in…

Hackerrank > SQL > Basic Select

Select
01-Select All
Given a City table, whose fields are described as +-------------+----------+ | Field       | Type     | +-------------+----------+ | ID          | int(11)  | | Name        | char(35) | | CountryCode | char(3)  | | District    | char(20) | | Population  | int(11)  | +-------------+----------+
write a query that will fetch all columns for every row in the table.

My Solution
SELECT*FROM city;
---------------------------------------------------------------------------------
02-Select by ID
Given a City table, whose fields are described as