Recent Articles

Various ways to swap two numbers (integers)
2 weeks ago

The following are the commonly used logic to swap two values.

Approach 1: Swap using third (temporary) variable

#include <stdio.h>

int main(){
   int x,y;
   scanf("%d%d",&x,&y);
   int temp = x;
   x = y;
   y = temp;
   printf("%d %d",x,y);
}

Approach 2: Swap using XOR operator

#include <stdio.h>

int main(){
   int x,y;
   scanf("%d%d",&x,&y);
   x = x^y;
   y = x^y; //Now y = (x^y)^y = x. So y has value of x now
   x = x^y; //Now x = (x^y)^x = x  
   printf("%d %d",x,y);
}

Approach 3: Swap using Addition and Subtraction

#include <stdio.h>

int main(){
   int x,y;
   scanf("%d%d",&x,&y);
   x = x+y; //Assume x=5 and y=3. Now x=8, y=3
   y = x-y; //Now x=8 and y=5
   x = x-y; //Now x=3 and y=5 and hence swapped.
   printf("%d %d",x,y);
}

Approach 4: Swap using Multiplication and Division

#include <stdio.h>

int main(){
   int x,y;
   scanf("%d%d",&x,&y);
   x = (x*y)/(y=x); 
   printf("%d %d",x,y);
}

 

View

Left Shift Operator
2 weeks ago

Left Shift operator is denoted by <<

<< shifts the bits to the left by the denoted positions.

N << 1 shifts the bits in N to the left by 1 position.

Consider 9 whose binary representation is 1001.

Now when 1001 is shifted left using << by 1, we get 10010 (a zero is added in the end).

Decimal value of 10010 is 18.

So the below program prints 18 as the output.

#include <stdio.h>

int main(){
  //Binary representation of 9 is 1001
  int N = 9;

  /*
    Now 1001 is shifted left using << by 1. 
    So it becomes 10010.  Decimal value of 10010 is 18.
  */
  printf("%d", N << 1);
}

Another Example:

Consider N=6. Binary representation of 6 is 110. Now 110 is shifted left using << by 2 giving the value as 11000.  Decimal value of 11000 is 24.

So the output of the program is 24.

#include <stdio.h>

int main(){
  //Binary representation of 6 is 110
  int N = 6;

  /*
    Now 110 is shifted left using << by 2.
    So it becomes 11000.  Decimal value of 11000 is 24.
  */
  printf("%d", N << 2);
}

 

View

Add Two Numbers in All Supported Languages
2 weeks ago

How to add two numbers in all supported programming languages?

 

C
Accept two integers then add and print their sum.

#include<stdio.h>
#include <stdlib.h>

int main()
{
    int num1, num2;
    scanf("%d %d", &num1, &num2);
    printf("%d", num1 + num2);
}

 

C++/C++17
Accept two integers then add and print their sum.

#include<iostream>
using namespace std;

int main()
{
    int num1, num2;
    cin>>num1>>num2;
    cout<<num1+num2;
}

 

Java
Accept two integers then add and print their sum.

import java.util.*;
public class Hello {

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
        System.out.println(num1 + num2);
    }
}

 

Python 2
Read and convert the first line to two integers. Then print their sum.

num1, num2 = map(int, raw_input().split())
print num1 + num2

 

Python 3
Read and convert the first line to two integers. Then print their sum.

num1, num2 = map(int, input().split())
print(num1 + num2)

 

C#
Read and convert the first line to two integers. Then print their sum.

using System;
namespace Hello
{
    class Hello
    {
        public static void Main (string[] args)
        {
            char[] splitchar = { ' ' };
            String[] stringValues = Console.ReadLine().Split(splitchar);
            Int32 num1 = Convert.ToInt32(s[0]);
            Int32 num2 = Convert.ToInt32(s[1]);
            Console.WriteLine(num1+num2);
        }
    }
}

 

Javascript
Read and convert the first line to two integers. Then print their sum.

var readline = require('readline');
var reader = readline.createInterface({
  input: process.stdin,
  terminal: true
});

var lines = [];

reader.on('line', function (line) {
    lines.push(line);
});

reader.on('close', function () {
    var stringValues = lines[0].split(" ");
    var num1 = parseInt(stringValues[0])
    var num2 = parseInt(stringValues[1])
    console.log(num1 + num2)
});

 

Go
Accept two integers then add and print their sum.

package main
import "fmt"
func main() {
    var a int
    var b int
    fmt.Scanf("%d %d", &a, &b)
    fmt.Println(a+b)
}

 

PHP
Accept two integers then add and print their sum.

<?php
    fscanf(STDIN, "%d %d\n", $num1, $num2);
    echo $num1 + $num2;
?>

 

Scala
Accept two integers then add and print their sum.

import java.util.Scanner;
object Hello {
    def main(args: Array[String])
    {
        var scanner = new Scanner(System.in);
        var num1 = scanner.nextInt();
        var num2 = scanner.nextInt();
        println(num1+num2);
    }
}

 

Ruby
Read and convert the first line to two integers. Then print their sum.

stringValues = gets.chomp.split(" ")
num1 = stringValues[0].to_i
num2 = stringValues[1].to_i
puts num1+num2

 

Kotlin
Accept two integers then add and print their sum.

import java.util.Scanner

fun main(vararg args: String) {
  val input = Scanner(System.`in`)
  val num1 = input.nextInt()
  val num2 = input.nextInt()
  println(num1 + num2)
}

 

Perl
Read and convert the first line to two integers. Then print their sum.

while (<STDIN>) 
{
    ($x, $y) = split;
    print ($x+$y);
}

 

R
Read and convert the first line to two integers. Then print their sum.

f <- file("stdin")
on.exit(close(f))
T <- readLines(f)
T <- strsplit(T, " ")
num1 <- as.numeric(T[[1]][1])
num2 <- as.numeric(T[[1]][2])
write(num1+num2, stdout())

 

Groovy
Read and convert the first line to two integers. Then print their sum.

def str = System.in.newReader().readLine()
def (num1, num2) = str.tokenize( ' ' )
println num1.toInteger()+num2.toInteger()

 

D
Read and convert the first line to two integers. Then print their sum.

import std.stdio;
import std.string;
import std.conv;

void main()
{
    auto input = strip(stdin.readln());
    auto arr = input.split(" ");
    int a = to!int(arr[0]);
    int b = to!int(arr[1]);
    writeln(a+b);
}

 

Lua
Read and convert the first line to two integers. Then print their sum.

local str = io.read()
local sum = 0
for token in string.gmatch(str, "[^%s]+") do
   sum = sum + tonumber(token)
end
print(sum)

 

View

Valid main method signatures in Java
4 weeks ago

The commonly used main method signature is

    public static void main(String[] args) {
        
    }

But from Java SE 5.0 onwards we can also use the varargs as given below.

    public static void main(String... args) {
        
    }

The three dots indicates varargs (Variable arguments). You can use a varargs variable like an Array.
As an example when the following program is given Skill Rack as input, it prints Rack (which is the second argument. As index starts from 0, index 1 denotes second argument).

public class Hello {

    public static void main(String... args) {
        System.out.println(args[1]);
    }
}

 

View

Importance of Naming Variables and Functions
1 month ago

Consider the program below. Can you guess what the program is trying to do? Also note the amount of time you take to figure it out.

#include<stdio.h>
int main()
{
   int q,f,e,u,z;
   scanf("%d%d%d",&q,&f,&u);
   e=f-q;
   z=u-2;
   while(z-- > 0){
    f = f+e;
   }
   printf("%d",f);
}

If you took more than 10 seconds to decipher the program and you too write similar code with single letter variable names, then it is time you realize the importance of providing meaningful names to variables and functions. (If the naming convention was better where meaningful names were given to the variables, it would have been easier for one to understand the functionality of the code easily.)

View

Logic - How to check if a character is a vowel in a given String?
3 months ago

Let us say we are given a string and asked to print the vowels in the string. Vowels can be in upper case AEIOU or in lower case aeiou. Here instead of comparing all 10 values (5 in upper case and 5 in lower case), we convert the character to be compared to lower case and do the comparison. So we define a method isVowel to check if a given character is a vowel or not.

Let us explore the solutions in various programming languages.

Solution in C Programming Language:

#include<stdio.h>

int isVowel(char ch){
   ch = tolower(ch);
   return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

int main()
{
   char str[1001];
   scanf("%s",str);
   for(int index=0; str[index] != '\0'; index++){
        if(isVowel(str[index])){
            printf("%c",str[index]);
        }
   }
}

Solution in Java Programming Language:

import java.util.*;

public class Hello {

    private static boolean isVowel(char ch) {
        ch = Character.toLowerCase(ch);
        return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
    }

    public static void main(String... args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        for (char ch : str.toCharArray()) {
            if (isVowel(ch)) {
                System.out.print(ch);
            }
        }

    }

}

Solution in Python Programming Language:

def isVowel(ch):
    ch = ch.lower()
    return ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'
    

inputstr=input().strip();
for ch in inputstr:
    if isVowel(ch):
        print(ch, end='')

Solution in C++ Programming Language:

int isVowel(char ch)
{
    ch = tolower(ch);
    return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}

int main()
{
    char str[1001];
    cin >> str;
    for(char *ptr = str; *ptr; ptr++)
    {
        if(isVowel(*ptr))
        {
            cout << *ptr;
        }
    }
    return 0;
}

 

View

How to scan (accept) a single character in Java?
4 months ago

There is NO method as nextChar() in java.util.Scanner class in Java. We need to use the next() method to read a single character as a string and then use charAt(0) to get the first character of that string.

Scanner scanner = new Scanner(System.in);
String str = scanner.next();
char ch = str.charAt(0);

or

Scanner scanner = new Scanner(System.in);
char ch = scanner.next().charAt(0);

The below program accepts a character and prints the same character as the output.

import java.util.*;

public class Hello {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        char ch = scanner.next().charAt(0);
        System.out.println(ch);
    }

}

Note: Here we are reading the single character as a string and getting the first character using charAt(0) from that string.

View

How to get a space separated String as input in C
4 months ago

Accepting space separated String value in C Programming Language:

In C, using %s in scanf accepts a string value only till the first non-white space character. For example, the below program will print only One when One Two Three is given as input.

#include <stdio.h>

int main()
{
    char inputStringValue[101];
    scanf("%s",inputStringValue);
    printf("%s",inputStringValue);
}

So to accept a string with space we can use the following approaches.

Approach 1:
Use fgets to accept the input string value (which has one or more spaces in it).
This program will print One Two Three when One Two Three is given as input.

#include <stdio.h>

int main()
{
    char inputStringValue[101];
    fgets(inputStringValue,100,stdin);
    printf("%s",inputStringValue);
}

 

Approach 2:
Use ^\n to instruct the scanf to read till a new line character is encountered in the input value.

#include <stdio.h>

int main()
{
    char inputStringValue[101];
    scanf("%[^\n]",inputStringValue);
    printf("%s",inputStringValue);
}

 

View

KickStart - SkillRack initiative for students to learn programming
4 months ago

The portal http://kickstart.skillrack.com/ is an initiative from SkillRack for students who wish to learn programming. Over 1000+ programs will be published. No login or payment is required.

SOLUTION is provided for all programs in any one of the programming languages - C, Java or Python 3.x

Visit http://kickstart.skillrack.com/

 

View

C/Java PROGRAMMING KICKSTART in Bengaluru (Bangalore)
6 months ago

SkillRack.com is an online platform to learn from programming basics to enhance your skills till competitive programming.

SkillRack is arranging a free half day orientation session for the 2018 batch students who are not yet placed. The session will consist of the following.

- 10 programming concepts and solving related programs asked in major IT companies hands-on (You will solve the programs using www.skillrack.com) and SkillRack mentors will assist you.

When is this session happening?
- The session will be happening on 11th October 2018 from 10:00 am to 12:30 noon at our Bengaluru office address mentioned below.

Address

What is the cost involved?
- The orientation session is free and you need not pay for it.

Why is the session free (as every one has a business motive)?
- We are doing it free as a promotional activity

What's the count of participants allowed?
- Only 30 are allowed in a session. Hence please register at this Google Form link entering your email and phone number. We will email and confirm the approval of your registration.

The Google Form link is  https://goo.gl/forms/tzrvQmJNqrWiyIPE2

What should you bring?
- Bring your own laptop or two can share one laptop (if your friend has one)
- You must your mobile HOTSPOT to connect to internet and solve the programs using www.skillrack.com

View

TCS NINJA Test Pattern 2018-2019 Batch
8 months ago

TCS Ninja test pattern for 2019 Batch students to be conducted in September 2018

MCQ - Section 1:
Session 1: Contains 20 questions related to Quantitative Aptitude, Reasoning (Duration 40 minutes). (This session will not be there for students who have got 75% in 10th, 12th and in their college. This is applicable only students from accredited colleges)
Session 2: Contains 10 questions related to English Verbal Reasoning and Proficiency (Duration 10 minutes).
Session 3: Contains 10 questions related to C programming proficiency (Duration 20 minutes)

Programming - Section 2:
Contains 1 Programming Challenge to be solved in 20 minutes.

LOG into www.SkillRack.com to take TCS NInja tests.

View

Medals - When Gold, Silver and Bronze are awarded?
11 months ago

Bronze medals are awarded when the following tasks are fulfilled.
- 1 medal for solving a Daily Challenge
- 1 medal for scoring 40% or above in any MCQ Aptitude Test
- 2 medals for scoring 60% or above in any MCQ Aptitude Test
- 1 medal for posting approved solution in Discussion Forum
- 1 medal for posting approved Interview Experience in Discussion Forum
- 1 medal for posting approved On Campus Event in Discussion Forum
- 1 medal for solving a challenge in Programming Test
- 2 medals for completing a unit in Programming Course (Like C, Java & Python)
- 5 medals for completing a programming track (Set of 10 problems)
- 2 medals for completing a unit in Aptitude Course
- 1 medal for solving exactly one challenge in CPL Programming Test


Silver medals are awarded when the following tasks are fulfilled.
- 1 medal for solving exactly two challenges in CPL Programming Test


Gold medals are awarded when the following tasks are fulfilled.
- 1 medal for solving all three challenges in CPL Programming Test

 

More tasks will be added when new features are introduced or based on the feedback from users.

View

Reverse a String in Java
11 months ago

In this program we will reverse an input String and print the reversed String.

We will use StringBuilder to achieve the reversal.

import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        
        //We will reverse the String using StringBuilder.
        StringBuilder sb=new StringBuilder(input);
       
        //Now reverse the input value and print 
        System.out.println(sb.reverse().toString());
       
    }
}

 

View

Program to print Fibonacci series in Java
11 months ago

In this article we will look at a Java program that will print Fibonacci series upto a certain number of terms using recursion.

The number of terms is passed as input.

import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int termsCount = sc.nextInt();
        int sum = 1, curr = 1;
        System.out.println(curr);
        fibonacci(curr, sum, termsCount);
    }

    private static void fibonacci(int curr, int sum, int remainingTerms) {
        if (remainingTerms != 1) {
            System.out.print(sum);
            fibonacci(sum, curr + sum, remainingTerms - 1);
        }
    }
}

 

View

INFOSYS Test Pattern 2019 Batch - LATEST
11 months ago

INFOSYS Campus Hiring TEST Pattern (The campus hiring online test pattern has not been changed for the past 4 years. The latest Infosys pattern for 2018 - 2019 graduation batch is given below.

Test Duration: 95 minutes
Total Questions: 65
Sectional Cut-Off: Yes it is present
Negative Marking: No (There is no negative marking for all the three sections)

3 Sections in the test are
Section 1: Quantitative/CryptArithmetic/Analytical Puzzles: 10 questions in 35 minutes
Section 2: Logical/Analytical Reasoning : 15 questions in 25 minutes
Section 3: Verbal :  40 questions in 35 minutes.

But Infosys changes the question by preparing different question sets for each event. So while you will get the similar pattern of questions, it is difficult to get the exact questions repeated.

Section 1 Quantitative/CryptArithmetic/Analytical Puzzles Topics:
 - Time Speed & Distance
 - Crypt Arithmetic
 - Percentages
 - Profit & Loss
 - Mensuration/Geometry
 - Permutation & Combination
 - One analytical puzzle where data is given and 3-4 questions are asked based on the given data.

Observation: 5-6 questions will be easy to solve. Remaining questions will be time consuming - particularly crypt arithmetic and the analytical puzzle questions.
 
Section 2 Logical/Analytical Reasoning Topics:
 - Data Interpretation / Logical Puzzle
 - Logically Following Options/ Syllogism questions modified in a different manner
 - Data Suffiency
 
Observation: Easiest section to solve if you have practised similar type of questions earlier.
 
Section 3 Verbal Topics:
 - Reading Comprehension
 - Theme Detection (Inference from a passage)
 - Sentence Correction / Improvement
 - Sentence Completion (Fill in the blanks type)
 - Remaining questions from a variety of topics like One word substitution, Synonyms and Antonyms etc but the above 4 are asked often.

Observation:
The verbal section contains lengthy paragraphs for Reading Comprehension and is time consuming. The time to be spent on a single question (40 to be answered in 35 minutes) is a mere 52 seconds. Also the theme detection questions consists of paragraphs which take time to read. So one must be grazing fast through the paragraphs and answer really quick (Must not spend more time on a single question as time management is important in Verbal section)

To practice INFOSYS pattern MOCK TESTS, please log into www.SkillRack.com

 

View