Recent Articles

Find the square root of an integer without using any in-built function
2 months ago

How to find the square root of an integer without using any in-built function?

Using Newton Raphson method we can find the square root of an integer without using any in-built function.

The C solution is given below.

#include<stdio.h>
//Newton Raphson method to find square root without using in built function

double absolute(double val){
  return val < 0 ? -val:val;    
}

double findSquareRoot(int N){
    const double diff = 0.00001;
    double sqRoot = 1.0;
    while( absolute(N - (sqRoot*sqRoot)) >= diff){
        sqRoot = (N/sqRoot + sqRoot)/2.0;        
    }
    return sqRoot;    
}


int main()
{
    int N;
    scanf("%d",&N);
    printf("\n%.5lf",findSquareRoot(N));
    return 0;
}

 

View

Print 1 to N without using a loop
4 months ago

In the below program we use recursion to call the function print1ToN to print from 1 to N. You can observe that we have NOT used a loop (for or while loop) in the code.

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

void print1ToN(int value){
    if(value > 1){
        print1ToN(value-1);
    }
    
    printf("%d ",value);        
}

int main()
{
    int N;
    scanf("%d",&N);
    print1ToN(N);
}

 

View

C Program - Find if a given number is Prime without using inbuilt functions
5 months ago

The below C program prints if a given number is Prime or not without using any in-built functions like square root.

Instead of square root we use divisor*divisor <= N so that the value of divisor goes up only till square root. Please note that checking divisibility only till square root is optimal than checking for divisibility till N/2.

#include <stdio.h>

int isPrime(int N){
    if(N <= 1){
        return 0;
    }
    
    for(int divisor=2; divisor*divisor <= N; divisor++){
        if(N%divisor == 0){
            return 0;
        }
    }
    return 1;
}

int main()
{
   int N;
   scanf("%d",&N);
   printf(isPrime(N) ? "Prime":"Not Prime");
   return 0;
}

 

View

Common Scenarios for Segmentation fault (Core dumped) Error
5 months ago

Let us now look at the most common scenarios where core dumped error can occur in C programming.

Scenario 1: 
We forget to include & - the address of operator in statements involving scanf function.

The below program will give Segmentation fault (Core dumped) error when executed.

#include <stdio.h>

int main()
{
    int x,y;
    scanf("%d%d",x,y); //It must be &x,&y
    printf("%d", x+y);
    return 0;
}

 

Scenario 2:
We use a char array (String) to accept a string value which is larger than it's length.

The below program will give 
*** stack smashing detected ***:  terminated
Aborted (core dumped) error when executed.

#include <stdio.h>

int main()
{
    char str[3];
    scanf("%s",str); 
    /*
     * Input is abcdefghijklmnopqrstdsjskdhkdhkdhskjdhsjdskjdhskjdhsjdhskjdhskj whose 
     * length is more than size of str which is 3
     */ 
    
    printf("%s",str);
    return 0;
}

 

Scenario 3:
When we traverse beyond the memory allocated for the Array.

The below program will give Segmentation fault (core dumped) error.

#include <stdio.h>

int main()
{
    char str[3];
    str[0] = 's';
    str[1] = 'r';
    str[2] = 'a';
    /*
	Array str size is only 3 but we traverse till 50000.
    */
    for(int index=0; index < 50000; index++){
        printf("%c",str[index]);
    }
    return 0;
}

 

Scenario 4:
When we use %s format specifier for printing a character.

The below program will give Segmentation fault (core dumped) error.

#include<stdio.h>

int main()
{
    char str[101] = "hello";
    printf("%s", str[1]);
}

 

Scenario 5:
When we return an array which is declared in the same function.

The below program will give Segmentation fault (core dumped) error.

#include <stdio.h>

int* fun(){
    int arr[100];
    arr[0] = 1;
    return arr;
}
int main()
{
    int *arr = fun();
    printf("%d", arr[0]);
    return 0;
}

 

View

Various ways to swap two numbers (integers)
5 months 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
6 months 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
6 months 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
6 months 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
6 months 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?
8 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?
9 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
9 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
9 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)
11 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
1 year 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