Friday, March 29, 2019

Difference between scanf() and gets() in C || what is scanf and get function in C language

Difference between scanf() and gets() in C

scanf()

  • It is used to read the input(character, string, numeric data) from the standard input(keyboard).
  • It is used to read the input until it encounters a whitespace, newline or End Of File(EOF).
// C program to see how scanf() 
// stops reading input after whitespaces 

#include <stdio.h> 
int main() 
char str[20]; 
printf("enter something\n"); 
scanf("%s", str); 
printf("you entered: %s\n", str); 

return 0; 


Here the input will be provided by the user and output will be as follows:
Input: Geeks for Geeks
Output: Geeks

Input: Computer science
Output: Computer

gets

  • It is used to read input from the standard input(keyboard).
  • It is used to read the input until it encounters newline or End Of File(EOF).
// C program to show how gets() 
// takes whitespace as a string. 

#include <stdio.h> 
int main() 
char str[20]; 
printf("enter something\n"); 
gets(str); 
printf("you entered : %s\n", str); 
return 0; 


Here input will be provided by user as follows
Input: Geeks for Geeks
Output: Geeks for Geeks

Input: Computer science
Output: Computer science
The main difference between them is:
  1. scanf() reads input until it encounters whitespace, newline or End Of File(EOF) whereas gets() reads input until it encounters newline or End Of File(EOF), gets() does not stop reading input when it encounters whitespace instead it takes whitespace as a string.
  2. scanf can read multiple values of different data types whereas gets() will only get character string data.
The difference can be shown in tabular form as follows:

Difference between ‘AND’ vs ‘&&’ as operator in PHP

The AND operator is called logical operator. It returns true if both the operands are true.
Example:

<?php 

// Variable declaration and 
// initialization 
$a = 100; 
$b = 50; 

// Check two condition using 
// AND operator 
if ($a == 100 and $b == 10) 
echo "True"; 
else
echo "False"; 

?> 


Output:
False
Explanation: Since variable $a = 100 and another variable $b = 10, the condition $a == 100 evaluates to true and $b == 10 also evaluates to true. Therefore, ‘$a == 100 and $b == 10’ evaluates to true because AND logic states that if both the operands are true, then result also be true. But when the input $b = 20, the condition $b == 10 is false, so the AND operation result will be false.
‘&&’ Operator
The && operator is called logical operator. It returns true if both operands are true.
Example:

<?php 

// Declare a variable and initialize it 
$a = 100; 
$b = 10; 

// Check the condition 
if ($a == 100 && pow($b, 2) == $a) 
echo "True"; 
else
echo "False"; 
?> 
Output:

True
Explanation: Since variable $a = 100 and another variable $b = 10, the condition $a == 100 evaluates to true and pow($b, 2) == $a also evaluates to true because $b = 10 raised to the power of 2 is 100 which is equal to $a. Therefore, ‘$a == 100 && pow($b, 2) == $a’ evaluates to true as AND logic states that only when both the operands are true, the AND operation result is true. But when the input $b = 20, the condition pow($b, 2) == $a is false, so the AND operation result is false.
Comparison between ‘AND’ and ;&&’ operator: There are some difference between both operator are listed below:
  • Based on Precedence: Precedence basically decides which operations are performed first in an expression. The precedence of ‘&&amp’ operator is high and the precedence of ‘AND’ operator is low.
  • Based on operation:

Double not (!!) operator in PHP || How to use !! in PHP

Double not (!!) operator in PHP

The “NOT NOT” operator or Double not(!!) operator in PHP simply returns the truth value of the variable or expression. To explain in very simple terms, the first not operator(!) negates the expression. The second not operator(!) again negates the expression resulting the true value which was present before.
The (!!) operator returns as that Boolean function. If use !! to an expression the true value will be true and false value would be false. That is no change in the Boolean value. By using this double not(!!) operator it can increase the code readability and also ensure the truth and false values to be strictly Boolean data types.

<?php 

// Declare a variable 
// and initialize it 
$a = 1; 

// Use double not operator 
$a = !!$a; 

// Display the value 
// of variable a. 
echo $a; 
?> 


Difference between logical NOT(!) operator and Double NOT(!!) operator in PHP: The Not operator is the mathematically complements or negates the Boolean value of the concerned data. For example a Boolean value of $a = True, then the NOT operator imposed on it !$a would be False. This is about logical NOT or Negation operator. Where as the Double NOT (!!) operator returns only the Boolean cast or the truth value. That is !!$a is always TRUE.
Here is an another example based on double NOT operator.
Example 2:

<?php 

// PHP program to illustrate 
// Double NOT operator 

// Declare a variable and 
// initialize it 
$t = 10; 

// Check condition 
if ($t !== 10) 
echo "This is NOT operator!"; 
elseif (!!$t) 
echo "This is Double NOT operator!"; 
else
echo "Finish!"; 
?> 
The above code strictly save the Boolean data type and returns the truth value of the variable.

How to hundle exception in php

An exception is unexpected program result that can be handled by the program itself. Exception Handling in PHP is almost similar to exception handling in all programming languages.
PHP provides following specialized keywords for this purpose.
  • try: It represent block of code in which exception can arise.
  • catch: It represent block of code that will be executed when a particular exception has been thrown.
  • throw: It is used to throw an exception. It is also used to list the exceptions that a function throws, but doesn’t handle itself.
  • finally: It is used in place of catch block or after catch block basically it is put for cleanup activity in PHP code.
  • Why Exception Handling in PHP ?
    Following are the main advantages of exception handling over error handling
    • Separation of error handling code from normal code: In traditional error handling code there is always if else block to handle errors. These conditions and code to handle errors got mixed so that becomes unreadable. With try Catch block code becomes readable.
    • Grouping of error types: In PHP both basic types and objects can be thrown as exception. It can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types.
    Exception handling in PHP:
    • Following code explains the flow of normal try catch block in PHP:
  • <?php 

  • // PHP Program to illustrate normal 
  • // try catch block code 
  • function demo($var) { 
  • echo " Before try block"; 
  • try { 
  • echo "\n Inside try block"; 
  • // If var is zero then only if will be executed 
  • if($var == 0) 
  • // If var is zero then only exception is thrown 
  • throw new Exception('Number is zero.'); 
  • // This line will never be executed 
  • echo "\n After throw (It will never be executed)"; 
  • // Catch block will be executed only 
  • // When Exception has been thrown by try block 
  • catch(Exception $e) { 
  • echo "\n Exception Caught", $e->getMessage(); 
  • // This line will be executed whether 
  • // Exception has been thrown or not 
  • echo "\n After catch (will be always executed)"; 

  • // Exception will not be rised 
  • demo(5); 

  • // Exception will be rised here 
  • demo(0); 
  • ?> 
Output
Before try block Inside try block After catch (will be always executed) Before try block Inside try block Exception CaughtNumber is zero. After catch (will be always executed)

What is the use of the @ symbol in PHP?

The at sign (@) is used as error control operator in PHP. When an expression is prepended with the @ sign, error messages that might be generated by that expression will be ignored. If the track_errors feature is enabled, an error message generated by the expression and it will be saved in the variable $php_errormsg. This variable will be overwritten on each error.

<?php 

// File error 
$file_name = @file ('non_existent_file') or
die ("Failed in opening the file: error: '$errormsg'"); 

// It is used for expression 
$value = @$cache[$key]; 

// It will not display notice if the index $key doesn't exist. 


?> 

RunTime Error:
PHP Notice:  Undefined variable: errormsg in /home/fe74424b34d1adf15aa38a0746a79bed.php on line 5
Output:
Failed in opening the file: error: ''
Program 2:
<?php 

// Statement 1 
$result= $hello['123'] 

// Statement 2 
$result= @$hello['123'] 
?> 

It will execute only statement 1 and display the notice message
PHP Notice:  Undefined variable: hello.
Note: The use of @ is very bad programming practice as it does not make error disappear, it just hides them, and it makes debugging a lot worse since we can’t see what’s actually wrong with our code.

Use of copyOf() syntax in Java || How to use copyOf() method in Java

Using copyOf() method:
Syntax:
Object[] gfg= a1.toArray()
String[] str = Arrays.copyOf(gfg, 
                             gfg.length, 
                             String[].class);
Approach:
  1. Get the ArrayList of String.
  2. Convert ArrayList to Object array using toArray() method.
  3. Convert it to String Array using Arrays.copyOf() method.
  4. Print String Array.

// Java program to Convert ArrayList to 
// String ArrayList using get() method 

import java.util.*; 

public class GFG { 

// Function to convert ArrayList<String> to String[] 
public static String[] GetStringArray(ArrayList<String> arr) 

// Convert ArrayList to object array 
Object[] objArr = arr.toArray(); 

// convert Object array to String array 
String[] str = Arrays 
.copyOf(objArr, objArr 
.length, 
String[].class); 

return str; 

// Driver code 
public static void main(String[] args) 

// declaration and initialise ArrayList 
ArrayList<String> 
a1 = new ArrayList<String>(); 

a1.add("Geeks"); 
a1.add("for"); 
a1.add("Geeks"); 

// print ArrayList 
System.out.println("ArrayList: " + a1); 

// Get String Array 
String[] str = GetStringArray(a1); 

// Print Array elements 
System.out.print("String Array[]: "
+ Arrays.toString(str)); 
  1. Output:
    ArrayList: [Geeks, for, Geeks]
    String Array[]: [Geeks, for, Geeks]
    

Convert an ArrayList of String to a String array in Java

Given an ArrayList of String, the task is to convert the ArrayList to String array in java.
Examples:
Input: ArrayList = [ "Geeks", "for", "Geeks" ]
Output: String[] = {"Geeks", "for", "Geeks"}

Input: ArrayList = [ "Jupiter", "Saturn", "Uranus", "Neptune", "Sun"]
Output: String[] = {"Jupiter", "Saturn", "Uranus", "Neptune", "Sun"}
  1. Using ArrayList.get() Method
    Syntax:
     str[j] = a1.get(j)
    Approach:
    1. Get the ArrayList of Strings.
    2. Find the size of ArrayList using size() method, and Create a String Array of this size.
    3. Fetch each element of the ArrayList one by one using get() method.
    4. Assigned each element into String Array using assignment(=) operator.
    5. Print String Array.
    Below is the implementation of the above approach:// Java program to Convert ArrayList to 
    // String ArrayList using get() method 

    import java.util.*; 

    public class GFG { 

    // Function to convert ArrayList<String> to String[] 
    public static String[] GetStringArray(ArrayList<String> arr) 

    // declaration and initialise String Array 
    String str[] = new String[arr.size()]; 

    // ArrayList to Array Conversion 
    for (int j = 0; j < arr.size(); j++) { 

    // Assign each value to String array 
    str[j] = arr.get(j); 

    return str; 

    // Driver code 
    public static void main(String[] args) 

    // declaration and initialise ArrayList 
    ArrayList<String> 
    a1 = new ArrayList<String>(); 

    a1.add("Geeks"); 
    a1.add("for"); 
    a1.add("Geeks"); 

    // print ArrayList 
    System.out.println("ArrayList: " + a1); 

    // Get String Array 
    String[] str = GetStringArray(a1); 

    // Print Array elements 
    System.out.print("String Array[]: "
    + Arrays.toString(str)); 
  2. Output:
    ArrayList: [Geeks, for, Geeks]
    String Array[]: [Geeks, for, Geeks]
    
  3. Using Object array as intermediate
    Syntax:
    Object[] arr = a1.toArray()
    String str = (String)obj;
    
    Approach:
    1. Get the ArrayList of String.
    2. Convert ArrayList to Object array using toArray() method.
    3. Iterate and convert each element to desired type using typecasting. Here it is converted to String type and added to the String Array.
    4. Print String Array.