Wednesday, February 15, 2017

The Linked Lists !!!

Hello there! Today you will learn about inserting the elements in to the linked lists.
But before we begin let me tell you something about he linked list. In arrays we have to first declare the size of the array. After declaring the array we cannot increase its size and further elements in array are arranged in linear fashion or one after the another. But in case of linked list this is not the case. Here you can expand or shrink the size of the linked list as per your requirement so there is no wastage and excess of storage also elements are arranged non linearly.  A Node in the linked list  has the following two parts:

          1) Data Field
          2) Address Field.

Data field stores the data in the node while address field stores the address of the next node.

Now its time to introduce you the basic terminologies.

malloc(): Malloc function is used to allocated/reserve the memory for the next element you are going to add in the linked list. Insertion of the next element in the linked list is done as:

Node *a : (Node *)malloc(sizeof (Node));
Here we have allocated the space for node a.

Now let us begin.

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node      
/*Defining the node*/
{
int data;               
 /*Declaring Nodes data part*/
struct node *next;       
/*Declaring Node's next address part*/
}Node;
void main()
{
clrscr();
Node *a=(Node *)malloc(sizeof (Node)); 
/* Allocates space for node A*/
a->next = NULL;
Node *first = a;
/* Here I used another pointer to the first Node*/
int count = 0;
while(count<100)    
{
int choice;
printf("enter choice 1)insert 2)exit");
/* User has to enter 1 to insert the element 2 to exit*/
scanf("%d",&choice);
if(choice==1)
{
printf("enter the data");
scanf("%d",&a->data);
 /* Scan and store the data in the data field of Node a*/
a->next = (Node *)malloc(sizeof (Node));
/* Allocate space for the next Node */
a=a->next; 
/*Update A by the next Node */
a->data=NULL; 
/* Put data part of Node A as null */
count++; 
}
else if(choice !=1)
break;  
 /* If user doesn't enter 1 than exit */
}
a = first; 
 /* initialize a by the first node */
while(a->data!=NULL)   
/* Continue until the data part of a becomes Null */
{
printf("%d ",a->data); 
/* Print data field of a*/
a = a->next; 
/* Update a by next node */
}
a =first; 
getch();

}



Hope that you enjoyed reading this blog. I will cover other operations in the linked list(insertion at beginning , insertion in middle, deletion etc.) in the next blog. Stay tuned, Stay programmed.

Sunday, February 12, 2017

Solutions to The For Loop #1

Here I begin with solutions to the questions given in The For Loop #1.


#Pro1 : Prime Numbers between 1 to 100.


for(int j= 2;j<=100;j++)   /* Process is same as for check a prime number with some minor changes*/
{
int flag = 0;
for(int i = 2;i<j;i++)
{
if(j % i == 0)  
{
flag = 1;                      
break;
}
}
if(flag ==  0)
printf("%d ",j );
}

#Pro2 : Fibonacci Series.


int n = 10;   /* Say I want to print first 10 numbers in series */
int a = 0;
int b = 1;
int sum = 0;
printf("%d %d ", a, b);
for(int i = 0;i <10;i++)
{
sum = a + b;          /* Here we find what will be the next number */
a = b;                     /* Than we update a by b*/
b = sum;                /*And than b by sum to get the next number*/
printf("%d ", sum);
}



#Pro3 : Tribonacci Series.

/*Process is same as fibonacci series except here I use three variables a, b and c. */
int n = 10;   /* Say I want to print first 10 numbers in series */
int a = 0;
int b = 1;
int c = 1;
int sum = 0;
printf("%d %d  %d", a, b, c);
for(int i = 0;i <10;i++)
{
sum = a+b+c;
a = b;
b = c;
c = sum;
printf("%d ", sum);
}

#Pro 4 : Factorials of all numbers between 1 to 10

/* Here I have used one more for loop so that We may find factorial of all numbers */
for(int i = 1;i<=10;i++)
{
int fact = 1;
for(int j = 1;j<=i;j++)
{
fact = fact * j;
}
printf("% d ", fact);
}

In the Upcoming Blog we will discuss more about for loops. For loops Inside for loops. Hope that you got solutions to problems discussed in the blog: For Loops #1


The For Loop # 1

This blog is dedicated to all those who find the "FOR Loop" to be very difficult. This blog will contain a detailed explanation about for loop with ample of examples for your better understanding.
Here we begin.


The word loop all about something that repeats itself so is the FOR loop. If you wish to print your name thousand times you have to write printf("SRK"); a thousand times or you need to print number from 1 to 100, you gonna need to write printf("1"); printf("2"),....printf("100");. Isn't this method nasty and long.

But here FOR loop comes to your rescue. But before we begin I must tell you the syntax("The method to write the FOR loop")

Here's the syntax:

for( initialization ; testing ; updation )  
{
Body of loop/statements
}

here Initialization means to initialize a variable e.g. int num = 1; Or char x = 'a' etc.
In case of testing, you test the expression. how many times you want to execute the loop.
e.g. num<10
the for loop will execute until the number reaches 9 and when the num reaches 10, The for loop stops because num is not less than 10.
But if I say num<=10
the for loop will execute until the num becomes 10.

In the Updation part we may update the variable by one or by two even by three or whatever.
ex:
++num;
Or
num++;
Or
num = num+1;
Or 
num = num*2;
etc.


Now since we know the syntax. We may dive in the For loop.

ex #1

Print numbers from 1 to 100.


for(int num = 1; num<=100;num=num+1)
printf("%d ",num);

Or
for(int num = 1;num<101;num=num+1)    
printf("%d ",num);

Note the difference in the above two code. In the first expression the test expression is n<=100. It means we will continue to run the for loop until the num reaches 100. But in the second expression the test expression is num<101. Here the for loop will execute until the num reaches 100. when the num reaches 101 the execution of for loop will stop because the num 101 is not less than 101.

ex #2

Print the table of any number


int num = 7;
for(int i = 1;i<11;i++)
printf("%d ",num*i);

Here we multiply the number by i. when i is 1 we get 7 x 1, when i is 2 we get 7 x 2, so on and so forth. 

ex #3

Print characters from a to z.


for(char c = 'a'; c <= 'z' ; c++)
printf("%c ", c);

Here we begin by initialing the character 'a' in the CHARACTER VARIABLE c and we go on increasing the c by one.


ex # 4

Print factorial of a number.


Note : 5 ! = 5*4*3*2*1 = 120.

int num = 5; /* Say we are going to find factorial of 5   */
int fact = 1;  /* The variable fact will store the factorial */
for(int x = 1;x<=num; x=x+1) 
fact = fact * x;

Note: If I would have intialized fact by 0. Then the answer would be zero. Take care to initialize fact by 1.

ex # 5

Find the sum of numbers from 1 to 50.


int sum = 0;
for(int j = 1;j<51;j++)
sum = sum + j;
printf("sum = %d ",sum);

Here we drive the for loop from 1 to 50 and add the number to sum and than update the sum expression.

ex # 6

Find the sum of squares of number from 1 to 10.
i.e. 1*1 + 2*2 + 3*3 + 4*4 .....10*10.


int sum = 0;
for(int k = 1;k<=10;k++)
sum = sum + ( k * k);    
printf("sum = %d ",sum);

Here we drive the for loop from 1 to 50 and  add the number square  to sum and than update the sum expression.

ex # 7

Find the sum of the given expression
1*1 + 3*3 + 5*5 +7*7 .....51*51.


int sum = 0;
for(int i = 1;i<=51;i = i +2 )
sum = sum + (i*i);
printf(" sum = %d ",sum);

Here you must note that we update i by 2 and not by 1 as usual.

ex # 8

Print only even numbers between 1 and 25.


for(int i = 1;i<=25;i++)
{
if(i%2==0)         /* check if i is divisible by two. */
printf("%d ", i);
}

Or

for(int i = 2;i<25;i=i+2)   /* Here i update i by two */
printf("%d ", i);

ex # 9

Check if the given number is prime or not.


/* Lets say the given number is 13 */
/* Logic here is we will test by dividing the number 13 from 2 to 12 i.e. (13-1) If the number is divisible we will say the number is not prime */

int number = 13;
int flag = 0; /* Say we will show flag is equal to zero if the number 13 is not divisible by any number between 2 to 12 */ 
/* If the number is divisible we will turn flag equal to 1 */

for(int i = 2;i<number;i++)
{
if(number % i == 0)    /* If the number 13 is divisible by any number between 1 to 12  */
{
flag = 1;                       /* WE will turn flag is equal to 0 and break the execution of the for loop */
break;
}
}
if(flag ==  0)
printf("the number is prime ");
else
printf("the number is not prime ");



Questions you may try:
#1 print all prime numbers between 1 to 100
#2 print the Fibonacci series i.e. 0 1 1 2 3 5 8 .... (sum of next num is equal to sum of previous 2 num)
#3 print the Tribonacci series i.e. 0 1 1 2 4 7 13 .... (sum of next num is equal to sum of previous three numbers )
#4 print the factorials of all numbers between 1 to 10.

Next blog will contain solutions to these questions. Hope that this blog helped you understand the basics of the for loop. In the upcoming blog I will cover for loop inside the for loop.


Saturday, February 11, 2017

Program to Convert Infix Expression to Post Fix Expression

Hello there in this post you will learn how to write a program to convert an Infix expression to Post Fix expression. To know about algorithm or methodology please refer to my first blog : http://a2cprogramming.blogspot.in/2017/02/stacks.html

Note1: Use proper braces so that the program will run correctly.
Note2: It is illegal to publish this program or use it in your online content. This program is made by improving and shortening the code. This program is written solely by the blogger using his own intellect. However you can use it for compiling your program.

Here is the code:

#include<stdio.h>         
#include<conio.h>
char stack[30];        /* consider the maximum size in the stack to be 30 */
char ex[30];            /*consider the maximum size in the  post fix expression  to be 30 */
int pointerstack=-1;   /* set pointer to the stack at -1 */
int pointerexp = -1;   /* set pointer to the stack at -1 */
void push(char ch);   /* declare a function to push a character to the stack*/
void pop();                /* declare a function which pops a character from stack and adds it to the postfix                                   expression*/
int priority(char);
void main()
{
char input[30];     /* take a input array to the input expression */
printf("enter the infix expression");
gets(input);        /*read the character input and store it in input array */
for(int i = 0;i<30;i++)    /now run a loop from 0 to input size -1/
{
if(input[i]=='(')           /* if '(' is found push it to the stack */
push(input[i]);
else if((input[i]>='A' && input[i]<='Z')||(input[i]>='a' && input[i]<='z'))
ex[++pointerexp]=input[i];     /* If operand is found add it to the postfix expression */
else if(input[i]=='+' ||input[i]=='-' || input[i]=='/' ||input[i]=='*')
{             /* If operand +-/* is found */


while(priority(stack[pointerstack]) >= priority(input[i]))
pop();
   
push(input[i]);
}
/* Note that  here I have used a switch case without break statement*/
/* We begin from - symbol so all the symbol above it are removed from the stack  and like wise*/
else if(input[i]==')')
{          /* If we find a ')' symbol than remove all elements till '('is found and add them to the postfix             expression */
while(stack[pointerstack]!='(')
{
pop();
}
stack[pointerstack]=' ';    /* Here I removed the '(' symbol also which was not removed in the while                                          loop*/
pointerstack--;
}
}
puts(ex);     /Here We print the final Post Fix Expression/
getch();
}
void push(char ch)
{
stack[++pointerstack]=ch;
}
void pop()
{
char x = stack[pointerstack];
ex[++pointerexp] = x;
stack[pointerstack]= ' ';
--pointerstack;
}
int priority(char ch)
{
if(ch=='(')
return 0;
else if(ch=='+' || ch =='-')
return 1;
else if(ch=='*'|| ch=='/')
return 2;
}
/* Upload Date : 11th Feb 2017.
    Upload Time : 6:29PM */

Stacks!!!

Some Operations using Stacks!!!!

Infix To Postfix Conversion.

Well Consider the expression  1.  A+B
The Postfix of the above expression will be AB+
Here the operator(+,/,*,-) comes after two operands.

Now before writing a program it is essential to know how we can convert a infix expression to post fix expression.
Here we will be using two arrays. One of them will be our stack and other will contain the post fix expression.

Step 1: Read/Scan the expression from left to right by scanning one character at a time.
Step 2: If you find '(' Symbol push it to the stack.
Step 3: If you find operator( may be A,B...Z) push it in the  post fix expression array.
Step 4: If you find any operator (+,-,/,*) Note its precedence
            /* Note : Precedence of / is greater than *
                           Precedence of * is greater than +
                           Precedence of + is greater than -
                           i.e. Precedence of />*>+>-            */
          If there is any operator in the stack, check the precedence of the scanned operator.
          If the precedence of the scanned operator is less than or equal to the operator which is present in the stack than the operator present in the stack is removed and pushed into the post fix expression array.
         If the precedence of the scanned operator is greater than the operator which is present in the stack than the scanned operator is also pushed into the stack.
Step 5: If the ')' symbol is found than the operator which are present between the previous '(' are removed and pushed in to the postfix expression array.


Example: Convert the following infix expression to post fix expression.

(A+B/C*(D-E))

   Read/Scan           Stack                           Final Post Fix Expression
1.(                           (
/* See step 2, since '(' symbol is found it is pushed in to the stack*/ 
2. A                         (                                  A
/* Since an operand is found it is pushed in to the post fix expression*/
3. +                         (+                                A
/*Since an operator is found and no other operator is currently present in the stack so  the operator is pushed into the stack*/
4.B                          (+                               AB
/* Since an operand is found it is pushed in to the post fix expression*/
5./                            (+/                              AB
/*Since the precedence of / is greater than that of +, so / can be pushed in to the stack.*/
6 C                           (+/                             ABC
/* Since an operand is found it is pushed in to the post fix expression*/
7. *                           (+*                            ABC/
/* Since the precedence of * is less than that of /, so / is removed from the stack and pushed in to the postfix expression and * is pushed in to the stack.*/
8. (                            (+*(                          ABC/
/* See step 2, since '(' symbol is found it is pushed in to the stack*/ 
9. D                           (+*(                         ABC/D
/* Since an operand is found it is pushed in to the post fix expression*/
10. -                           (+*(-                        ABC/D
/*Since an operator is found it is pushed in to the stack*/
11. E                           (+*(-                       ABC/DE
/* Since an operand is found it is pushed in to the post fix expression*/
12.)                             (+*                         ABC/DE-
/* Since a '(' is found the operator which was present between the ( and ) symbol was removed from the stack and pushed in to the post fix expression.*/
13. )                                                          ABC/DE-*+
/* Since again ')' is found the operators which were present between the ( and ) symbol were removed and pushed in to the post fix expression in reverse order and the final post fix expression is obtained.*/

Infix: (A+B/C*(D-E))
Final Post Fix Expression : ABC/DE-*+

Next Blog Post will contain the Program code for Infix to Post Fix conversion.

========================= About The Blogger=============================

The Blogger is Rishi Jain, who is perusing Engineering in Computer Science at Samrat Ashok Technological Institute, Vidisha. The Blogger has a keen interest in programming and would like to accept challenges to code a program. The Blogger has prior knowledge of JAVA Basics and had scored 100/100 in Computer Science Java Programming in ICSE 10th Board and 99/100 in Computer Science Java Programming in ISC 12th Board Examinations.