Arrays Introduction

Problem Statement

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:Movie Fifty Shades Darker (2017)

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 Ai is the 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() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n,i,a[max];
    cin>>n;
    for(i=0;i<n;i++)
        cin>>a[i];
    for(i=n-1;i>=0;i--)
        cout<<a[i]<<" ";
    return 0;
}


Input and Output

Problem Statement

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() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int a,b,c;
    cin>>a>>b>>c;
    cout<<a+b+c;
    return 0;
}

Class

Problem Statement

Class is the C++ equivalent of struct. Along with storing multiple data in a common block, it also assigns some functions (known as methods) to manipulate/access them. It serves as the building block of Object Oriented Programming.

It also has access specifiers, which restrict the access of member elements. The primarily used ones are the following:

  • public: Public members (variables, methods) can be accessed from anywhere the code is visible.
  • private: Private members can be accessed only by other member functions, and it can not be accessed outside of class.

Class can be represented in the form of

class ClassName {
    access_specifier1:
        type1 val1;
        type2 val2;
        ret_type1 method1(type_arg1 arg1, type_arg2 arg2,...)
        ...
    access_specifier2:
        type3 val3;
        type4 val4;
        ret_type2 method2(type_arg3 arg3, type_arg3 arg3,...)
        ...
};

It’s a common practice to make all variables private, and set/get them using public methods. For example:

class SampleClass {
    private:
        int val;
    public:
        void set(int a) {
            val = a;
        }
        int get() {
            return val;
        }
};

We can store details related to a student in a class consisting of his age (int), first_name (string), last_name (string) and standard (int).

You have to create a class, named Student, representing the student’s details, as mentioned above, and store the data of a student. Create setter and getter functions for each element; that is, the class should at least have following functions:

  • get_age, set_age
  • get_first_name, set_first_name
  • get_last_name, set_last_name
  • get_standard, set_standard

Also, you have to create another method to_string() which returns the string consisting of the above elements, separated by a comma(,). You can refer to stringstream for this.

Input Format

Input will consist of four lines.
The first line will contain an integer, representing the age. The second line will contain a string, consisting of lower-case Latin characters (‘a’-‘z’), representing the first_name of a student.
The third line will contain another string, consisting of lower-case Latin characters (‘a’-‘z’), representing the last_name of a student.
The fourth line will contain an integer, representing the standard of student.

Note: The number of characters in first_name and last_name will not exceed 50.

Output Format

The code provided by HackerRank will use your class members to set and then get the elements of the Student class.

Sample Input

15
john
carmack
10

Sample Output

15
carmack, john
10

15,john,carmack,10

Solution

  
#include <cmath>
#include <cstdio>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;

/*
Enter code for class Student here.
Read statement for specification.
*/
class Student{
    private:
    int age;
    string first_name;
    string last_name;
    int standard;
    public:
    
    void set_age(int a)
        {
        age=a;
    }
    void set_first_name(string f)
        {
        first_name= f;
    }
    void set_last_name(string l){
        last_name=l;
    }
    void set_standard(int s)
       {
        standard= s;
    }
    int get_age()
        {
        return age;
    }
    int get_standard(){
        return standard;
    }
    string get_first_name(){
        return first_name;
    }
    string get_last_name(){
        return last_name;
    }
   string to_string(){
       return std::to_string(age)+","+first_name+","+last_name+","+std::to_string(standard)+"\n";
    }
};

int main() {
    int age, standard;
    string first_name, last_name;
    
    cin >> age >> first_name >> last_name >> standard;
    
    Student st;
    st.set_age(age);
    st.set_standard(standard);
    st.set_first_name(first_name);
    st.set_last_name(last_name);
    
    cout << st.get_age() << "\n";
    cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
    cout << st.get_standard() << "\n";
    cout << "\n";
    cout << st.to_string();
    
    return 0;
}


Structs

Problem Statement

struct is a way to combine multiple fields to represent a composite data structure, which further lays the foundation for Object Oriented Programming. For example, we can store details related to a student in a struct consisting of his age (int), first_name (string), last_name (string) and standard (int).

struct can be represented as

struct NewType {
    type1 value1;
    type2 value2;
    .
    .
    .
    typeN valueN;
};

You have to create a struct, named Student, representing the student’s details, as mentioned above, and store the data of a student.

Input Format

Input will consist of four lines.
The first line will contain an integer, representing age.
The second line will contain a string, consisting of lower-case Latin characters (‘a’-‘z’), representing the first_name of a student.
The third line will contain another string, consisting of lower-case Latin characters (‘a’-‘z’), representing the last_name of a student.
The fourth line will contain an integer, representing the standard of student.

Note: The number of characters in first_name and last_name will not exceed 50.

Output Format

Output will be of a single line, consisting of age, first_name, last_name and standard, each separated by one white space.

P.S.: I/O will be handled by HackerRank.

Sample Input

15
john
carmack
10

Sample Output

15 john carmack 10

Solution

  
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <string>
using namespace std;

/*
    add code for struct here.
*/
struct Student{
    int age;
    string first_name;
    string last_name;
    int standard;
};

int main() {
    Student st;
    
    cin >> st.age >> st.first_name >> st.last_name >> st.standard;
    cout << st.age << " " << st.first_name << " " << st.last_name << " " << st.standard;
    
    return 0;
}


StringStream

Problem Statement

stringstream is a stream class to operate on strings. It basically implements input/output operations on memory (string) based streams. stringstream can be helpful in different type of parsing. The following operators/functions are commonly used here

  • Operator >> Extracts formatted data.
  • Operator << Inserts formatted data.
  • Method str() Gets the contents of underlying string device object.
  • Method str(string) Sets the contents of underlying string device object.

Its header file is sstream.

One common use of this class is to parse comma-separated integers from a string (e.g., “23,4,56”).

stringstream ss("23,4,56");
char ch;
int a, b, c;
ss >> a >> ch >> b >> ch >> c;  // a = 23, b = 4, c = 56

You have to complete the function vector parseInts(string str). str will be a string consisting of comma-separated integers, and you have to return a vector of int representing the integers.

Input Format

The first and only line consists of n comma-separated integers.

Output Format

Print the integers after parsing it.

P.S.: I/O will be automatically handled. You need to complete the function only.

Sample Input

23,4,56

Sample Output

23
4
56

Solution

  
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;

vector parseInts(string str) {
   // Complete this function
    stringstream ss(str);
    char ch;
    int temp;
    vector res;
    while(ss>>temp)
    { 
        res.push_back(temp);  
        if (ss.peek() == ',')
        ss.ignore();
    }
    return res;
     
}

int main() {
    string str;
    cin >> str;
    vector integers = parseInts(str);
    for(int i = 0; i < integers.size(); i++) {
        cout << integers[i] << "\n";
    }
    
    return 0;
}


Strings

Problem Statement

C++ provides a nice alternative data type to manipulate strings, and the data type is conveniently called string. Some of its widely used features are the following:

  • Declaration:
    string a = "abc";
    
  • Size:
    int len = a.size();
    
  • Concatenate two strings:
    string a = "abc";
    string b = "def";
    string c = a + b; // c = "abcdef".
    
  • Assessing ith element:
    string s = "abc";
    char   c0 = s[0];   // c0 = 'a'
    char   c1 = s[1];   // c1 = 'b'
    char   c2 = s[2];   // c2 = 'c'
    
    s[0] = 'z';         // s = "zbc"
    

P.S.: We will use cin/cout to read/write a string.

Input Format

You are given two strings, a and b, separated by a new line. Each string will consist of lower case Latin characters (‘a’-‘z’).

Output Format

In the first line print two space-separated integers, representing the length of a and b respectively.
In the second line print the string produced by concatenating a and b (a+b).
In the third line print two space-separated strings, a and b. a and b are the same as a and b, respectively, except that their first characters are swapped.

Sample Input

abcd
ef

Sample Output

4 2
abcdef
ebcd af

Explanation

  • a=abcd
  • b=ef
  • |a|=4
  • |b|=2
  • a+b=abcdef
  • a=ebcd
  • b=af

Solution

  
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main() {
   // Complete the program
    string a,b;
    cin>>a>>b;
    cout<<a.size()<<" "<<b.size()<<endl;
    cout<<a+b<<endl;
    char t=a[0];
    a[0]=b[0];
    b[0]=t;
    cout<<a<<" "<<b;
    return 0;
}


For Loop

Problem Statement

A for loop is a programming language statement which allows code to be repeatedly executed.

The syntax for this is

for ( <expression_1> ; <expression_2> ; <expression_3> )
    <statement>
  • expression_1 is used for intializing variables which are generally used for controlling terminating flag for the loop.
  • expression_2 is used to check for the terminating condition. If this evaluates to false, then the loop is terminated.
  • expression_3 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 <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    // Complete the code.
    int a,b;
    cin>>a>>b;
    for(int n=a;n<=b;n++)
    {
     if(n>9)
       {
          if(n%2==0)
              cout<<"even"<<endl;
           else cout<<"odd"<<endl;
       }
    else if(n==9)
        cout<<"nine"<<endl;
    else if(n==1)
        cout<<"one"<<endl;
    else if(n==2)
        cout<<"two"<<endl;  
    else if(n==3)
        cout<<"three"<<endl;        
    else if(n==4)
        cout<<"four"<<endl; 
    else if(n==5)
        cout<<"five"<<endl;
    else if(n==6)
        cout<<"six"<<endl;
    else if(n==7)
        cout<<"seven"<<endl;      
    else
        cout<<"eight"<<endl; 
     
    }
    return 0;
}


Conditional Statements

Problem Statement

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.

Output Format

Print the output as described above.

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() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin>>n;
if(n>9)
cout<<"Greater than 9"<<endl;
else if(n==9)
cout<<"nine"<<endl;
else if(n==1)
cout<<"one"<<endl;
else if(n==2)
cout<<"two"<<endl;
else if(n==3)
cout<<"three"<<endl;
else if(n==4)
cout<<"four"<<endl;
else if(n==5)
cout<<"five"<<endl;
else if(n==6)
cout<<"six"<<endl;
else if(n==7)
cout<<"seven"<<endl;
else
cout<<"eight"<<endl;

return 0;
}

 

Pointer

Problem Statement

A 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 the void 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>

void update(int *a,int *b) {
    // Complete this function 
    *a = *a+*b;
    *b = abs(*a-*b-*b);
}

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;
}


Basic Data Types

Problem Statement

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);

P.S.: For the moment, we can ignore the spacing between format specifiers.

Input Format

Input will consists 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() {
    // Complete the code.
    int a;
    long b;
    char ch;
    long long c;
    float d;
    double f;    
    scanf("%d %ld %lld %c %f %lf  ", &a,&b,&c,&ch,&d,&f);
    printf("%d\n%ld\n%lld\n%c\n%f\n%lf",a,b,c,ch,d,f);
    return 0;
}