Saturday, January 11, 2025

Arrow function in JavaScript

*Introduction*


Arrow functions are a concise way to write functions in JavaScript. They were introduced in ECMAScript 2015 (ES6) and have since become a popular choice among developers. In this article, we'll explore the basics of arrow functions, their syntax, and how they differ from traditional functions.


*Syntax*


The syntax for an arrow function is as follows:


```

const functionName = (parameters) => {

  // function body

}

```


Here, `functionName` is the name of the function, `parameters` is a comma-separated list of parameters, and `function body` is the code that gets executed when the function is called.


*Example*


Here's an example of a simple arrow function:


```

const greet = (name) => {

  console.log(`Hello, ${name}!`);

}


greet("John"); // Output: Hello, John!

```


*Concise Syntax*


One of the benefits of arrow functions is their concise syntax. If the function body consists of only one statement, you can omit the brackets and the `return` keyword:


```

const double = (x) => x * 2;

console.log(double(5)); // Output: 10

```


*Implicit Return*


Arrow functions also support implicit return. If the function body is an expression, the result of that expression is returned automatically:


```

const sum = (a, b) => a + b;

console.log(sum(2, 3)); // Output: 5

```


*This Context*


Unlike traditional functions, arrow functions do not have their own `this` context. Instead, they inherit the `this` context from the surrounding scope:


```

const person = {

  name: "John",

  greet: () => {

    console.log(`Hello, my name is ${this.name}`);

  }

}


person.greet(); // Output: Hello, my name is undefined

```


In this example, the `greet` function does not have its own `this` context, so `this.name` is `undefined`. To fix this issue, you can use a traditional function or bind the `this` context explicitly:


```

const person = {

  name: "John",

  greet: function() {

    console.log(`Hello, my name is ${this.name}`);

  }

}


person.greet(); // Output: Hello, my name is John

```


*Conclusion*


Arrow functions are a powerful feature in JavaScript that can simplify your code and make it more concise. They offer a more expressive syntax and can be used in a variety of situations, from simple functions to complex callbacks. However, it's essential to understand the differences between arrow functions and traditional functions, especially when it comes to the `this` context.

Tuesday, November 7, 2017

Writting a shell script file from linux command shell

$ echo '#!/bin/sh' > shell_from_cmd.sh
$ echo 'echo my firt script' >> shell_from_cmd.sh
$ chmod 755 my-script.sh
$ ./my-script.sh
my firt script
$

Saturday, March 7, 2015

Ouput of the program part 2

 Q. What is the output of following program?

#include <iostream>
using namespace std;

// main() is where program execution begins.
int g,t;
float f,h;
int main()
{
   int a,b;
   float d,l;
cout<<"GLobal Int g="<<g<<endl;
cout<<"GLobal Int t="<<t<<endl;
cout<<"Local Int a="<<a<<endl;
cout<<"Local Int b="<<b<<endl;
cout<<"Local float d="<<d<<endl;
cout<<"Local float l="<<l<<endl;
cout<<"Global float f="<<f<<endl;
cout<<"Global float h="<<h<<endl;
   return 0;
}

Answer:-

GLobal Int g=0    //always 0 if global int 
GLobal Int t=0    //always 0 if global int 
Local Int a=0    //any garbage value if local and not assigned , in most case it can take 0 if only one int or one float
Local Int b=4196896   //any garbage value if local and not assigned 
Local float d=0  //any garbage value if local and not assigned 
Local float l=5.88211e-39   //any garbage value if local and not assigned 
Global float f=0    //always 0 if global float 
Global float h=0    //always 0 if global float 


Explanation :
Local variable is not defined by the system and need to be initialized. I not initialized then it can take any garbage value but the Global variables are initialized automatically by the system when we define them.

Tuesday, December 30, 2014

Programing Tricks ----Part1

Ques 1 We all know that a function cant return more than one value. So for modifying the original values we use pointers and thus can use the values accordingly in main. But if we do not want to use pointer then what will you use??

Answer-- we will use structure in that case

for example:-

 #include<stdio.h>
 struct marks{
     int maths;
     int physics;
     int chem;
    
 };
 struct marks deviation(struct marks student , struct marks student2 );
 int main(){
        
         struct marks student1;
         student1.maths= 87;
         student1.chem = 67;
         student1.physics=96;
        
         struct marks avg;
         avg.maths= 55;
         avg.chem = 45;
         avg.physics=34;
         //struct marks dev;
         struct marks dev= deviation(student1 , avg );
         printf("%d %d %d" ,dev.maths,dev.chem,dev.physics);

     return 0;
 }
struct marks deviation(struct marks student , struct marks student2 ){
     struct marks dev;
     dev.maths = student.maths-student2.maths;
     dev.chem = student.chem-student2.chem;
    dev.physics = student.physics-student2.physics;   
     return dev;
 }

Saturday, December 27, 2014

Programming basic questions Part-2

1. Can we define a function with arguments as pointer as well as value??

I mean if a swap funcation is defined as :-

void swap(int num1 ,int*num2 );

is it correct to define like this??

Ans :-

Yes, we can. there is no issue in this case but as we know that the function does not allow to return values more than one. thus doing this wont change the value of num1 in the calling function and our main objective of swapping will remain incomplete.

Thursday, August 7, 2014

Enumerated type(ENUMs)

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Because they are constants, the names of an enum type's fields are in uppercase letters.

In the Java programming language, you define an enum type by using the enum keyword. For example, you would specify a days-of-the-week enum type as:


public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY
}

Monday, July 21, 2014

Print format string : printf

printf function as we know is used to give output on the screen,but while using so many times this function, I stuck at a point that why we use it in this way only ?


printf actually means print format string which helps us to print any variable whether it is integer float  character  or string. but what we need to do is wehave to tell this that we want to print particular type of variable in our statement.

printf undersatnds it and then converts that variable into string to give output as a statement.

for example:--
int num= 3;
float rate = 3.2;
char letter = 'A';

printf("%d, %f, %c" num, rate, letter);

output:--

3,3.2,A

for further information refer to this article.

Monday, June 16, 2014

Abstraction a simple programming strategy

It is necessary to have some formal way of constructing a program so that it can be built efficiently and reliably. Research has shown that this can be best done by decomposing a program into suitable small modules, which can themselves be written and tested before being incorporated into larger modules, which are in turn constructed and tested. The alternative is create what was often called "sphaghetti code" because of its tangled of statements and jumps. Many expensive, failed projects have demonstrated that, however much you like to eat sphaghetti, using it as a model for program construction is not a good idea!

It's rather obvious that if we split any task into a number of smaller tasks which can be completed individually, then the management of the larger task becomes easier. However, we need a formal basis for partitioning our large task into smaller ones. The notion of abstraction is extremely useful here. Abstractions are high level views of objects or functions which enable us to forget about the low level details and concentrate on the problem at hand.

To illustrate, a truck manufacturer uses a computer to control the engine operation - adjusting fuel and air flow to match the load. The computer is composed of a number of silicon chips, their interconnections and a program. These details are irrelevant to the manufacturer - the computer is a black box to which a host of sensors (for engines speed, accelerator pedal position, air temperature, etc) arconn.

In turn, the manager of a transport company has an even higher level or more abstract view of a truck. It's simply a means of transporting goods from point A to point B in the minimum time allowed by the road traffic laws. His specification contains statements like:

"The truck, when laden with 10 tonnes, shall need no more than 20l/100km of fuel when travelling at 110kph."


How this specification is achieved is irrelevant to him: it matters little whether there is a control computer or some mechanical engineer's dream of cams, rods, gears, etc.

There are two important forms of abstraction: functional abstraction and structural abstraction. In functional abstraction, we specify a function for a module, i.e.

"This module will sort the items in its input stream into ascending order based on an ordering rule for the items and place them on its output stream."


As we will see later, there are many ways to sort items - some more efficient than others. At this level, we are not concerned with how the sort is performed, but simply that the output is sorted according to our ordering rule.

The second type of abstraction - structural abstraction - is better known as object orientation. In this approach, we construct software models of the behaviour of real world items, i.e. our truck manufacturer, in analysing the performance of his vehicle, would employ a software model of the control computer. For him, this model is abstract - it could mimic the behaviour of the real computer by simply providing a behavioural model with program statements like:if ( pedal_pos > 50.0 ) { set_air_intake( 0.78*pedal_pos); set_fuel_valve( 0.12 + 0.32*pedal_pos); } Alternatively, his model could incorporate details of the computer and its program.

However, he isn't concerned: the computer is a "black box" to him and he's solely concerned with its external behaviour. To simplify the complexity of his own model(the vehicle as a whole), he doesn't want to concern himself with the internal workings of the control computer; he wants to assume that someone else has correctly constructed a reliable model of it for him.

Dynamic allocation

Dynamic allocatonThese variables are created when we need'em and then they must be deleted. 
notice that these variables are generated during the excution time not in the compiling time as the other variables.Creating a new variable : 
eg : int * xPtr = new int ; 
eg : char * NamePtr = new char[17] ;Deleting it : 
eg : delete xPtr; 
eg : delete [17] NamePtr ;

Friday, October 11, 2013

remove vowels string c

#include <stdio.h>
#include <string.h>
 
int check_vowel(char);
 
int main()
{
  char s[100], t[100];
  int i, j = 0;
 
  printf("Enter a string to delete vowels\n");
  gets(s);
 
  for(i = 0; s[i] != '\0'; i++) {
    if(check_vowel(s[i]) == 0) {       //not a vowel
      t[j] = s[i];
      j++;
    }
  }
 
  t[j] = '\0';
 
  strcpy(s, t);    //We are changing initial string
 
  printf("String after deleting vowels: %s\n", s);
 
  return 0;
}
 
 
int check_vowel(char c)
{
  switch(c) {
    case 'a':
    case 'A':
    case 'e':
    case 'E':
    case 'i':
    case 'I':
    case 'o':
    case 'O':
    case 'u':
    case 'U':
      return 1;
    default:
      return 0;
  }
}

Thursday, October 10, 2013

Searching programs in c

Linear Search

#include <stdio.h>
 
int main()
{
   int array[100], search, c, number;
 
   printf("Enter the number of elements in array\n");
   scanf("%d",&number);
 
   printf("Enter %d numbers\n", number);
 
   for ( c = 0 ; c < number ; c++ )
      scanf("%d",&array[c]);
 
   printf("Enter the number to search\n");
   scanf("%d",&search);
 
   for ( c = 0 ; c < number ; c++ )
   {
      if ( array[c] == search )     /* if required element found */
      {
         printf("%d is present at location %d.\n", search, c+1);
  break;
      }
   }
   if ( c == number )
      printf("%d is not present in array.\n", search);     
 
   return 0;
}
 

 Binary Search

#include <stdio.h>
 
int main()
{
   int c, first, last, middle, n, search, array[100];
 
   printf("Enter number of elements\n");
   scanf("%d",&n);
 
   printf("Enter %d integers\n", n);
 
   for ( c = 0 ; c < n ; c++ )
      scanf("%d",&array[c]);
 
   printf("Enter value to find\n");
   scanf("%d",&search);
 
   first = 0;
   last = n - 1;
   middle = (first+last)/2;
 
   while( first <= last )
   {
      if ( array[middle] < search )
         first = middle + 1;    
      else if ( array[middle] == search ) 
      {
         printf("%d found at location %d.\n", search, middle+1);
         break;
      }
      else
         last = middle - 1;
 
      middle = (first + last)/2;
   }
   if ( first > last )
      printf("Not found! %d is not present in the list.\n", search);
 
   return 0;   
}
 

Tuesday, September 10, 2013

Programming Problems(Find the output??)


What is the output of following programe?
Ques1.
#include <stdio.h>
main( )
{
i n t a, b y c;
scanf ( "%3d %3d %3d" , &a, &b, &c) ;
. . . . 

}
Input : 
1234 5678 9

Ans. Assignment will be like this:

a=123 b=4 c=567

Ques2.

Wednesday, September 4, 2013

Some interesting programs

#1 Printing the string containing Blank spaces while using Scanf

Problem: While using scanf for getting a string we have the limitation of string upto blank space.As soon as blank spaces occurs in a string scanf terminates to take that input.
 i.e .
char line[80];
scanf("%s",line);

for above program if we type
 India is my country. 
then line[ ] be assigned only "India"

Solution:
To solve this problem we could use a conversion process. 
Actually the "%s " in scanf converts our input to some string terminated with \0. As soon as the \0 occurs it does not take input. So following the rule of type conversion we can instruct our compiler to take input according to our own way.

An alternative method to print a string containing white space chararcter and uppercase character is that , write all uppercase letters including white sapce should be added in a square bracket in place of s, So that our compiler could interpret them and read them.

scanf (" %[  ABCDEFGHIJKLMNOPQRSTUWXYZ]", line ) ;

Now if our input is 
INDIA IS MY COUNTRY.

then line will be assigned the whole string "INDIA IS MY COUNTRY"
but now since we have not added the lowercase character hence as soon as it recognizes the lowercase letter it will terminate the scanning process.
Obviously , we could add lowercase character as well, but it will become cumbersome for us to write all those we want.


Now seeing the above solution, it comes to our mind that the above solution could be better if we could make compiler interpret the above things in opposite manner.i.e. what I mean to say that there should be some instruction , applying which we could help to ignore those characters which we are writing in code.
Because the ignored characters will be lesser than the used ones.

So ans is yes , we could use a circumflex (^)before our letters to be interpreted in opposite manner.

thus for ignoroing \n
the code will be simply like this :

scanf("%[^\n]",line);

Some C Facts

Scanf : In scanf all the operators are preceeded with the % sign because in scanf the argument presented by it are actually address. But the same does not apply to an array or string,why?
Because an array or string name is already an address of its first location , so no need to use % sign.

main( )
{char item[20];
int partno;
float cost;
scanf(" %s %d %f', item, &partno, &cost);
}

Sunday, September 1, 2013

Operator Precedence Groups

Operator category                                            Operators                                                  Associativity
unary operators                                           - ++ ! sizeof (type)                                           Right to Left
arithmetic  multiply, divide and remainder               * I %                                                      Left to Right
arithmetic add and subtract                                  + -                                                           Left to Right
relational operators                                           < <= > >=                                                  Left to Right
equality operators                                           !=                                                                 Left to Right
logical and                                                       &&                                                             Left to Right
logical or                                                            ||                                                               Left to Right
conditional operator                                      ? :                                                                   Right to Left
assignment operators                                 = += -= *= /= %=                                             Right to Left

Modulus Operator (%)

How to find remainders sign when one of the operand is negative??

When performing division it is very easy to find sign of quotient on the basis of elementary mathematics that if the two operands are of same sign then quotientwill be positive but negative in other case.

Now it feels cumbersome to us when we have to find the sign of remainder.It seems to us that the 'C' language is violating the rule of mathematics, But it is not actually true.
The mathematics is correct behind this , while our concepts have  proven to be weak.

In all opeartions of modiulus following ciondition should be satisfied:

a = ( ( a / b) * b) + (a % b)
i.e.
Dividend = Quotient * Divisor+ Remainder

From above equation

  Remainder = Dividend - Quotient * Divisor

 following the above equation we can calculate the remainder for following cases :
Finding remainder with negative opearnds 

Dividend||Divisor||Quoteint||Remainder

 10              3           3            1     // Remainder = 10- 3*3

-10             3          -3           -1     //Remainder = 10- {(-3)*3} 


 10            -3          -3            1     //Remainder = 10- {(-3)*(-3)} 

-10            -3           3           -1     //Remainder = -10- {3*(-3)} 


Division operator in c (Carefully divide)

Division Operator(/)

Integer division:
If two operands performing division operation are integer then the result will be an integer iwith truncated decimal values.

e.g.

a=10; b=3;
then  a/b = 3 ;  (rather than 3.333 in normal algebra.)


Ques. What will be the output of the following programme?

#include<stdio.h>
int main()
{
   float c;
 
    printf("%d\n", 10/3);
    printf("%f\n", 10/3);
    c=10/3;
    printf("%f\n",c);


return 0;

    }

output: 



 

3
0.000000 
3.000000

Notice that  all three expressions has both integers but all three expressions are having different outputs. all three expressions are performing integer division hence output first will be integer.

That is 10/3 =3 in short.


If one of the operands in division operation are float then result will be float.

#include<stdio.h>
int main()
{
   float c;    printf("%d\n", 10.0/3);
    printf("%f\n", 10.0/3);
    c=10.0/3;
    printf("%f\n",c);
  
    printf("%d\n", 10/3.0);
    printf("%f\n", 10/3.0);
    c=10/3.0;
    printf("%f\n",c);
  
    printf("%d\n", 10.0/3.0);
    printf("%f\n", 10.0/3.0);
    c=10.0/3.0;
    printf("%f\n",c);
  

            return 0;
   }


 Ans.


-1431655765
3.333333
3.333333

-1431655765
3.333333
3.333333

-1431655765
3.333333
3.333333

C-Programming questions part-1(basic)

1.How many characters are in the following string constant?

" \ t To continue, press the \"RETURN\" key\n"

Ans: total 38
27 normal characters
five blank spaces,
one special character(,)
four escape sequences (horizontal tab, two quotation marks and newline)
and the null character (\ 0) at the end of the string.


2.Which of the following are not valid identifires?
4th , _radius, value, the_tax_return,"My_name", area of circle

Ans.   4th,"My_name",area of circle

3.What is the differences between string constant "A"and character constant 'A'.

Ans. a character constant has an equivalent integer value, whereas a single-character string constant does not have an equivalent integer value and, in fact, consists of two characters -the specified character followed by the null character ( \ 0).

4.What will be the output of following programme?
 char array[11] = "Hello World";

    printf("%s\n",array);

Ans. Error

5. The unary operator always preceeds their operands (Trur/False)

Ans. Flase

i++,i-- are examples where unary operators comes after the operands

6. Write the unary operators.


Ans. ++,--,(type),sizeof,-,!

7. While considering the operators precedence and associativity , what is the difference between precedence and associativity?
Ans. Precedence tells the priority order of the operators in any expression.but ambuiguity arises while having same prirority  opereators occur in same expression.In that case an order from either right to left or left to right is followed to resolve this problem.

For example :
in     a=3+4-5
 + and - are of same priority.
then according to their associativity(Left to right) their operation will be performed in that order. Hence first addition is performed then subtraction.

NOTE: In all the operators only unary operators ,conditional operators and assignment operators are having associativity from right to left.

8.What is the value of following expression?
 i = 2 * 5 / 2
Ans. Since * and / are having same priority then according to their associativity left to right * operation is performed first.

hence i=2*5/2=10/2=5

if expression would be like this i = 2 * (5/2) then answer will be i=2*2=4 

9. In what general category do the #define and #include statements fall?

Ans. Preprocessor Statement