Given an sorted array: {1,5,6,10,19,31,72}
Solution:
Binary search only works on sorted array.
Calculate middle location of array and check the element which element to be searched.
Since array is sorted, if mid element is less then search item, then element is bound to be in the second half of list. In next steps, search within the respective part of the list
Start marker of array become middle +1 location, end remains same.
start= mid+1
Otherwise if the mid element is greater than search item, then element will be in the first half of list.
End marker of array become middle -1 location, start remains same.
Complexity: O(N/2)
#include <stdio.h>
int binarySearch(int array[],int start,int end,int search) {
if( start > end) {
// A base condition
// Happens when list does not contain value
return -1;
}
int mid = (int) ((start + end)/2);
if( array[mid] > search) {
binarySearch(array, start, mid-1, search);
}
else if ( array[mid] < search) {
binarySearch(array, mid+1, end, search);
}
else {
// A Base condition
// Element found, return its position
return mid+1;
}
}
int main() {
int arr[] = {1,5,6,10,19,31,72};
int size = sizeof(arr)/sizeof(arr[0]);
int pos = -1;
int searchItem = 1;
pos = binarySearch(arr, 0, 5,searchItem);
if(pos == -1) {
printf("%d not found in list",searchItem);
}
else {
printf("%d found at location %d",searchItem,pos);
}
return 0;
}
Output:
1 found at location 1
Sunday, June 7, 2020
Factorial Using recursion
Factorial of number n (n!) is 1* 2 * ... (n-1) * n
5! = 5*4*3*2*1 = 120
Checkout: Factorial without recursion
Solution:
Recursion is the process in which functions calls itself until some base condition is met. Recursion helps in writing shorter functions by dividing a problem into small parts and then solving that problem using a same function again.
We know that n! = 1 for n = 0, n! = n * (n-1)! for n > 0
For writing a recursive method we can use base condition when n become 1 and call the recursive method with (n-1) at each call.
#include<stdio.h>
int factorial(int n) {
if(n>0) {
return n * factorial(n-1);
}
else {
return 1;
}
}
int main()
{
int num =5;
printf("Factorial of %d : %d", num, factorial(num));
}
Output:
5! = 5*4*3*2*1 = 120
Checkout: Factorial without recursion
Solution:
Recursion is the process in which functions calls itself until some base condition is met. Recursion helps in writing shorter functions by dividing a problem into small parts and then solving that problem using a same function again.
We know that n! = 1 for n = 0, n! = n * (n-1)! for n > 0
For writing a recursive method we can use base condition when n become 1 and call the recursive method with (n-1) at each call.
#include<stdio.h>
int factorial(int n) {
if(n>0) {
return n * factorial(n-1);
}
else {
return 1;
}
}
int main()
{
int num =5;
printf("Factorial of %d : %d", num, factorial(num));
}
Output:
Factorial of 5 : 120
Saturday, June 6, 2020
Finding whether a number exists as sum of two array elements in a sorted array
Given the array{-5,-2,7,8,9,10,12}
Find whether sum 8 is possible
As element no.2 (-2) and element no.7(10) are present the sum of the two is 8
Solution: As the array is sorted, we can leverage this property and come up with an approach which is similar to binary searching
Start with two markers at start and end of the array
Sum the two numbers at start and end marker
if sum is greater than given number, decrease the end marker
if sum is less than given number, advance the start marker
Break if desired sum is found or start becomes greater than or equal to end
Complexity: O(n)
#include <stdio.h>
int main()
{
int a[] = {-5,-2,7,8,9,10,12};
int sum =8;
int found_flag = 0;
int size = sizeof a / sizeof a[0];
printf("\nSize of array %d", size);
int start = 0;
int end = size-1;
while(start<=end) {
if((a[start]+a[end])<sum) {
start++;
}
else if ((a[start]+a[end]>sum)) {
end--;
}
else {
found_flag++;
break;
}
}
if(found_flag) {
printf("\nElement at location(%d):%d and location(%d):%d has sum:%d", start+1,a[start],end+1,a[end],sum);
}
else {
printf("\nNot found !!");
}
return 0;
}
Output:
Size of array 7
Element at location(2):-2 and location(6):10 has sum:8
Finding whether a number exists as sum of two array elements in an unsorted array
Given the array{2, 10,9,7,8 ,-2}
Find whether sum 8 is possible
As element no.2 (10) and element no.6(-2) are present the sum of the two is 8
Solution: Taking an Sum minus the fixed element, we scan through rest of the array to find another element matching
Complexity: O(n^2)
#include <stdio.h>
int main()
{
int a[6] = {2, 10,9,7,8 ,-2};
int sum = 8;
int flag = 0;
int size = sizeof a / sizeof a[0];
printf("\nSize of array %d", size);
int i=0;
int j =0;
for (i= 0; i<size-1; i++) {
for(j=i+1; j <size;j++) {
if(sum-a[i] == a[j]) {
flag++;
break;
}
}
if(flag==1) {
break;
}
}
if(flag) {
printf("\n Element at location(%d):%d and location(%d):%d has sum:%d", i+1,a[i],j+1,a[j],sum);
}
else {
printf("Not found !!");
}
return 0;
}
Output:
Size of array 6
Element at location(2):10 and location(6):-2 has sum:8
Thursday, May 1, 2014
Frequency of number in an array
Program to find number of times a given integer value has occurred in an array of integers.
let array a[]= {6,1,6,3,5,6,2,2,1,3,6,2}
output:
1 -- 2
2 -- 3
3 -- 2
5 -- 1
6 -- 4
The simple solution to the problem is to increment array value at a particular index where index value is equal to the number.
Program
#include<stdio.h>
int main()
{
int a[]={6,1,2,5,6,3,2,2,2,1,4,2,8,4,3}; // size of a =15
int b[10]; // size 10 is sufficient because maximum number in above array is 9
int i;
//assigning all elements of array b to 0
for(i=0;i<10;i++)
b[i]=0;
for(i=0;i<15;i++)
b[a[i]]++;
for(i=0;i<10;i++)
{
if(b[i]!=0)
printf("%d -- %d\n",i,b[i]);
}
return 0;
}
let array a[]= {6,1,6,3,5,6,2,2,1,3,6,2}
output:
1 -- 2
2 -- 3
3 -- 2
5 -- 1
6 -- 4
The simple solution to the problem is to increment array value at a particular index where index value is equal to the number.
Program
#include<stdio.h>
int main()
{
int a[]={6,1,2,5,6,3,2,2,2,1,4,2,8,4,3}; // size of a =15
int b[10]; // size 10 is sufficient because maximum number in above array is 9
int i;
//assigning all elements of array b to 0
for(i=0;i<10;i++)
b[i]=0;
for(i=0;i<15;i++)
b[a[i]]++;
for(i=0;i<10;i++)
{
if(b[i]!=0)
printf("%d -- %d\n",i,b[i]);
}
return 0;
}
Wednesday, April 30, 2014
histogram printing
Program to print a histogram pattern for a given array.
For example
Array = 4 5 3 2
pattern
4 5 3 2
*
* *
* * *
* * * *
* * * *
Outer loop: depends on the maximum element in the array.
The very basic technique to find the maximum element is to assign first element of array as maximum and then subsequently checking it with other array elements and changing the maximum element appropriately.
Inner loop: controls the printing and also depends on maximum element. Find the maximum element and compare it with elements. If the given element is greater than the max element than print "*" otherwise print a space. Decrement the maximum element for a full completion of inner loop.
Program:
#include<stdio.h>
int main()
{
int a[]={5,7,3,6,4,8,2};
int size=7;
int max=a[0];
int i,j,temp;
for(i=1;i<size;i++)
{
if(max<a[i])
max=a[i];
}
for(i=0;i<size;i++)
printf("%d ",a[i]);
printf("\n");
temp=max;
for(i=0;i<max;i++)
{
for(j=0;j<size;j++)
{
if(a[j]>=temp)
printf("* ");
else
printf(" ");
}
temp--;
printf("\n");
}
return 0;
}
Wednesday, March 5, 2014
Printing Pattern 10
1
121
12321
1234321
------------- for n values
The above pattern can be divided into two parts
1
12 1
123 + 21
1234 321
outer loop i should run n times.
inner loop comprises of 2 loop variable for printing 1st and 2nd half of the pattern.
Number of spaces printed depends on number of values in that line
Maximum value in a line is the line number.
Outer loop
for(i=1;i<=n;i++)
{ ... }
Inner loop for spaces
Number of spaces = max lines in pattern - Values printed in that line
for(j=1;j<=n-i;j++)
printf(" ");
here 'n' number of lines in pattern which user enters and also the maximum value that appears in the pattern.
'i' is the line number of that line or number of values printed in that line.
Inner loop for 1st pattern
starts with 1 and goes till line number value for that line or max value of that line.
for(k=1;k<=i;k++)
printf("%d",k);
Inner loop for 2nd pattern
start with maximum value of that line -1 and decrements down to 1.
for(t=i-1;t>=1;t--)
printf("%d",t);
Program
#include<stdio.h>
int main()
{
int i,j,k,t,n;
//ask user to enter number of lines
printf("\nEnter the number of lines in the pattern:");
scanf("%d",&n);
//outer loop
for(i=1;i<=n;i++)
{
//loop for spaces
for(j=1;j<=n-i;j++)
printf(" ");
//loop for 1st part of pattern
for(k=1;k<=i;k++)
printf("%d",k);
//loop for 2nd part of pattern
for(t=i-1;t>=1;t--)
printf("%d",l);
//move to next line
printf("\n");
}
return 0;
}
121
12321
1234321
------------- for n values
The above pattern can be divided into two parts
1
12 1
123 + 21
1234 321
outer loop i should run n times.
inner loop comprises of 2 loop variable for printing 1st and 2nd half of the pattern.
Number of spaces printed depends on number of values in that line
Maximum value in a line is the line number.
Outer loop
for(i=1;i<=n;i++)
{ ... }
Inner loop for spaces
Number of spaces = max lines in pattern - Values printed in that line
for(j=1;j<=n-i;j++)
printf(" ");
here 'n' number of lines in pattern which user enters and also the maximum value that appears in the pattern.
'i' is the line number of that line or number of values printed in that line.
Inner loop for 1st pattern
starts with 1 and goes till line number value for that line or max value of that line.
for(k=1;k<=i;k++)
printf("%d",k);
Inner loop for 2nd pattern
start with maximum value of that line -1 and decrements down to 1.
for(t=i-1;t>=1;t--)
printf("%d",t);
Program
#include<stdio.h>
int main()
{
int i,j,k,t,n;
//ask user to enter number of lines
printf("\nEnter the number of lines in the pattern:");
scanf("%d",&n);
//outer loop
for(i=1;i<=n;i++)
{
//loop for spaces
for(j=1;j<=n-i;j++)
printf(" ");
//loop for 1st part of pattern
for(k=1;k<=i;k++)
printf("%d",k);
//loop for 2nd part of pattern
for(t=i-1;t>=1;t--)
printf("%d",l);
//move to next line
printf("\n");
}
return 0;
}
Thursday, January 23, 2014
Printing Pattern 9
1
01
101
0101
10101
Alternating between 1 and 0. Hmm! We can use number%2 that will always be 1 or 0. % means remainder division(or modular division) and gives remainder when number is divided by another number. When a number is divided by number 'n', remainder is always between 0 and n-1. So in case of division with 2, remainder is between 0 to 1 (n-1).
0 and 1 keeps on alternating in each line as well as for the next line. How about making it dependent on line both i and j say sum of i and j
line 1 element 1 -- i=1,j=1, i+j=2, 2%2=0 but we want a 1 instead. So add 1 to i+j and then mod it will 2.
Then i (outer loop variable) loops 5 times and j (inner loop variable) loops from 1 till i for each line and then goes to the next line.
i j i+j+1 i+j+1%2
1 1 3 1
next line
2 1 4 0
2 2 5 1
next line
3 1 5 1
3 2 6 0
3 3 7 1
next line
and so on.
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf("%d",(i+j+1)%2);
printf("\n");
}
return 0;
}
01
101
0101
10101
Alternating between 1 and 0. Hmm! We can use number%2 that will always be 1 or 0. % means remainder division(or modular division) and gives remainder when number is divided by another number. When a number is divided by number 'n', remainder is always between 0 and n-1. So in case of division with 2, remainder is between 0 to 1 (n-1).
0 and 1 keeps on alternating in each line as well as for the next line. How about making it dependent on line both i and j say sum of i and j
line 1 element 1 -- i=1,j=1, i+j=2, 2%2=0 but we want a 1 instead. So add 1 to i+j and then mod it will 2.
Then i (outer loop variable) loops 5 times and j (inner loop variable) loops from 1 till i for each line and then goes to the next line.
i j i+j+1 i+j+1%2
1 1 3 1
next line
2 1 4 0
2 2 5 1
next line
3 1 5 1
3 2 6 0
3 3 7 1
next line
and so on.
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf("%d",(i+j+1)%2);
printf("\n");
}
return 0;
}
Printing pattern 8
1
2 7
3 8 12
4 9 13 16
5 10 14 17 19
6 11 15 18 20 21
Seeing the pattern we can figure our that 1st element of each line is the value of line no. that is dependent on i (outer loop variable)
Some further look into the pattern reveals the following
1
2 7(2+5)
3 8(3+5) 12(8+4)
4 9(4+5) 13(9+4) 16(13+3)
5 10(5+5) 14 (10+4) 17(14+3) 19(17+2)
and so on.
#include<stdio.h>
int main()
{
int i,j,fix,curval=0;
for(i=1;i<=6;i++)
{
fix=5;
curval=i+fix;
for(j=1;j<=i;j++)
{
if(j==1)
printf("%2d ",i);
if(j>1)
{
printf("%2d ",curval);
fix--;
curval=curval+fix;
}
}
printf("\n");
}
return 0;
}
2 7
3 8 12
4 9 13 16
5 10 14 17 19
6 11 15 18 20 21
Seeing the pattern we can figure our that 1st element of each line is the value of line no. that is dependent on i (outer loop variable)
Some further look into the pattern reveals the following
1
2 7(2+5)
3 8(3+5) 12(8+4)
4 9(4+5) 13(9+4) 16(13+3)
5 10(5+5) 14 (10+4) 17(14+3) 19(17+2)
and so on.
#include<stdio.h>
int main()
{
int i,j,fix,curval=0;
for(i=1;i<=6;i++)
{
fix=5;
curval=i+fix;
for(j=1;j<=i;j++)
{
if(j==1)
printf("%2d ",i);
if(j>1)
{
printf("%2d ",curval);
fix--;
curval=curval+fix;
}
}
printf("\n");
}
return 0;
}
Printing pattern 7
1
1*2
1*2*3
1*2*3*4
i used as outer loop variable for printing no. of lines=4
j used to control printing * and nos. in each line.
In this pattern, we can figure out that star does not get printed when value of i equals value of j.
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
if(i!=j)
printf("*");
}
printf("\n");
}
return 0;
}
1*2
1*2*3
1*2*3*4
i used as outer loop variable for printing no. of lines=4
j used to control printing * and nos. in each line.
In this pattern, we can figure out that star does not get printed when value of i equals value of j.
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
if(i!=j)
printf("*");
}
printf("\n");
}
return 0;
}
Saturday, January 11, 2014
Printing Pattern 6
1
3 2
6 5 4
10 9 8 7
Outer Loop : 4 Times
Inner Loop: depend on value of Outer Loop
Value in each line is maximum that line should print in reverse order
1
2 3
4 5 6
7 8 9 10
If each line is above is reversed we get desired pattern
We must start with a maximum value of the line and then it should then be decremented.
What is the maximum value for the line?
Looking at the pattern --
Maximum value line no. Value of i + previous Max value
1 1 1+ 0 = 1
3 2 1+ 2 =3
6 3 3+ 3 =6
10 4 4+ 6 =10
#include<stdio.h>
int main()
{
int i,j,max_val,print_val;
max_val=0;
for(i=1;i<=4;i++)
{
max_val=max_val+i;
print_val=max_val;
for(j=1;j<=i;j++)
{
printf("%d ",print_val);
print_val--;
}
printf("\n");
}
return 0;
}
3 2
6 5 4
10 9 8 7
Outer Loop : 4 Times
Inner Loop: depend on value of Outer Loop
Value in each line is maximum that line should print in reverse order
1
2 3
4 5 6
7 8 9 10
If each line is above is reversed we get desired pattern
We must start with a maximum value of the line and then it should then be decremented.
What is the maximum value for the line?
Looking at the pattern --
Maximum value line no. Value of i + previous Max value
1 1 1+ 0 = 1
3 2 1+ 2 =3
6 3 3+ 3 =6
10 4 4+ 6 =10
#include<stdio.h>
int main()
{
int i,j,max_val,print_val;
max_val=0;
for(i=1;i<=4;i++)
{
max_val=max_val+i;
print_val=max_val;
for(j=1;j<=i;j++)
{
printf("%d ",print_val);
print_val--;
}
printf("\n");
}
return 0;
}
Printing pattern-5
1
23
456
78910
This pattern is very much similar to the pattern which is earlier discussed.
Outer Loop controls no. of lines to be printed which are 4.
Inner Loop controls the digits printed in each line.
In line no.1 we have only 1 digit printed.
In line no.2 we have 2 digits printed.
and so on.
Next digit is increment of previous digits, so we take a counter to keep count of next digit to be printed.
Outer Loop
for(i=1;i<=4;i++)
Inner Loop
for(j=1;j<=i;j++)
#include<stdio.h>
int main()
{
int i,j count;
count=1;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",count);
count++;
}
printf("\n");
}
return 0;
}
23
456
78910
This pattern is very much similar to the pattern which is earlier discussed.
Outer Loop controls no. of lines to be printed which are 4.
Inner Loop controls the digits printed in each line.
In line no.1 we have only 1 digit printed.
In line no.2 we have 2 digits printed.
and so on.
Next digit is increment of previous digits, so we take a counter to keep count of next digit to be printed.
Outer Loop
for(i=1;i<=4;i++)
Inner Loop
for(j=1;j<=i;j++)
#include<stdio.h>
int main()
{
int i,j count;
count=1;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",count);
count++;
}
printf("\n");
}
return 0;
}
Friday, January 10, 2014
Printing Pattern 4( 2 Right angle triangles )
*
**
***
****
***
**
*
The pattern can seen as two right angle triangles previously discussed in the blog.
Outer loop ( for no. of lines:7) will loop 7 times.
Inner loop should 1st increase the no. of * in pattern up till 4 lines and then decrease them.
Outer loop
for(i=1;i<=7;i++)
1st Inner loop (increasing stars upto line no.4)
for(j=1;j<=i;j++)
printf("*");
For 1st loop (i=1)
j=1 , j<= i yes print *
newline
For 2nd loop(i=2)
j=1, j<=i yes print *
j=2, j<=i yes print *
newline
and so on for i= 3 and 4 prints *** and ****
2nd Inner loop(decreasing stars after line no.4)
for(j=i;j<=7;j++)
printf("*");
For 5th loop (i=5)
j=5(i) , j<= 7 yes print *
j=6(i+1) , j<= 7 yes print *
j=7(i+2), j<=7 yes print *
newline
For 6th loop(i=6)
j=6(i), j<=7 yes print *
j=2(i+1), j<=7 yes print *
newline
for 7th loop (i=7)
j=7(i) , j<=7 yes print *
newline
An if else loop to check the line no.
if(i<=4)
{
1st Inner loop
}
else
{
2nd Inner loop
}
#include<stdio.h>
int main()
{
for(i=1;i<=7;i++)
{
if(i<=4)
{
for(j=1;j<=i;j++)
printf("*");
}
else
{
for(j=i;j<=7;j++)
printf("*");
}
printf("\n");
}
return 0;
}
**
***
****
***
**
*
The pattern can seen as two right angle triangles previously discussed in the blog.
Outer loop ( for no. of lines:7) will loop 7 times.
Inner loop should 1st increase the no. of * in pattern up till 4 lines and then decrease them.
Outer loop
for(i=1;i<=7;i++)
1st Inner loop (increasing stars upto line no.4)
for(j=1;j<=i;j++)
printf("*");
For 1st loop (i=1)
j=1 , j<= i yes print *
newline
For 2nd loop(i=2)
j=1, j<=i yes print *
j=2, j<=i yes print *
newline
and so on for i= 3 and 4 prints *** and ****
2nd Inner loop(decreasing stars after line no.4)
for(j=i;j<=7;j++)
printf("*");
For 5th loop (i=5)
j=5(i) , j<= 7 yes print *
j=6(i+1) , j<= 7 yes print *
j=7(i+2), j<=7 yes print *
newline
For 6th loop(i=6)
j=6(i), j<=7 yes print *
j=2(i+1), j<=7 yes print *
newline
for 7th loop (i=7)
j=7(i) , j<=7 yes print *
newline
An if else loop to check the line no.
if(i<=4)
{
1st Inner loop
}
else
{
2nd Inner loop
}
#include<stdio.h>
int main()
{
for(i=1;i<=7;i++)
{
if(i<=4)
{
for(j=1;j<=i;j++)
printf("*");
}
else
{
for(j=i;j<=7;j++)
printf("*");
}
printf("\n");
}
return 0;
}
Thursday, January 9, 2014
Printing Pattern 3
4
34
234
1234
For this pattern we have to take care about three things
The pattern requires three loops
In line no.1 we need to print 3 spaces and value is 434
234
1234
For this pattern we have to take care about three things
- We need to print 4 lines
- We need to print required spaces in lines
- We need to print the values.
The pattern requires three loops
- An outer loop to loop 4 times.
- An inner loop to control the no. of spaces needed to be printed in each line.
- An inner loop to print certain after spaces in each line.
In line no.2 we need to print 2 spaces and value 3 and 4.
So we see that no. of spaces in each line decrease and finally become zero.
The number of digits in each line increases.
we can also see that spaces + digits in each line are 4 and remain 4 for all the lines
Line No. No. of Spaces No. of Values
1 3 1 (3+1=4)
2 2 2 (2+2=4)
3 1 3 (3+1=4)
4 0 4 (4+0=4)
Outer loop variable i should iterate 4 times. As we need first digit in first line 4 we can start i=4 and then decrement it and make j dependent on i. (although the same pattern can be printed in number of ways)
for(i=4;i>=1;i--)
first inner loop is controlling the number of spaces in each line. Its number of times it iterates should reduces. As we noted that no. of digits + no. of spaces is constant = 4 for this pattern, we can make this loop dependent on i also. As i starts from 4 and number of spaces should be 3 for 1st line space =4-1 each time and decrement till 1 or the other way start from 1 and go upto i-1. For line 2 i's value will become 3 and 3-1 will become 2 and we need tw spaces to be printed as desired.
for(j=i-1;j>=1;j--)
printf(" ");
for printing value we need a another loop. For first line this loop shall only print 4. Then for second line it should print 3 and 4. We can recognize that this loop starts from i's value and go till 4 for each line because each line is printing as its last value.
for(k=i;k<=4;k++)
printf("%d",&k);
#include<stdio.h>
int main()
{
int i, j, k;
for(i=4;i>=1;i--)
{
for(j=i-1;j>=1;j--)
{
printf(" ");
}
for(k=i;k<=4;k++)
{
printf("%d",k);
}
printf("\n");
}
return 0;
}
Printing Pattern-2 (upside down right angle triangle)
1234
123
12
1
Outer loop 4 times
Inner loop decrements
#include<stdio.h>
int main()
{
int i, j;
for(i=4:i<=1;i--)
{
for(j=1;j<=i;j++)
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
Try the following pattern
4321
432
43
4
Outer loop 4 times
inner loop j=4 and decrement to 1 ( for line no.1 , to 2 for line no.2 and so on. Line no. depend on outer loop variable i)
123
12
1
Outer loop 4 times
Inner loop decrements
#include<stdio.h>
int main()
{
int i, j;
for(i=4:i<=1;i--)
{
for(j=1;j<=i;j++)
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
Try the following pattern
4321
432
43
4
Outer loop 4 times
inner loop j=4 and decrement to 1 ( for line no.1 , to 2 for line no.2 and so on. Line no. depend on outer loop variable i)
Printing Pattern-1( Right Angle Triangle 1)
Printing pattern involve using several number of loop. Very basic pattern require two nested for loops.
The outer loop iterates to the number of lines in the pattern.
The inner loop controls the printing of pattern occurring in single line.
Patterns become simple if we relate them to loop number
*
**
***
****
In above pattern,
Line 1 has 1 *
Line 2 has two *
And similarly the pattern remains the same.
Looking at above pattern i can also say
Setting up two loops
need i to print 4 lines and line number 1 to 4
for(i=1;i<=4;i++)
need j to be less than or equal to i's current value i.e if i=2 then j should be 1 and 2 , first printing * (for j=1) and * (for j=2) (total two times) for line no 2
for(j=1; j<=i;j++)
print("*");
after everything is done for that line i.e go to the next line - use \n newline
printf("\n");
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Try Printing
1
12
123
1234
This is very much similar the * pattern that was discussed
Only print value of j instead of printing *.
The outer loop iterates to the number of lines in the pattern.
The inner loop controls the printing of pattern occurring in single line.
Patterns become simple if we relate them to loop number
*
**
***
****
In above pattern,
Line 1 has 1 *
Line 2 has two *
And similarly the pattern remains the same.
Looking at above pattern i can also say
- It prints 4 lines, so outer loop should count to value of 4.
- Inner loop is responsible for printing *.
- Inner loop is dependent on outer loop in a way.
- If Line no. is 1 (line no. depends on outer loop) then inner loop should loop once and print * once
- If Line no. is 2 then inner loop should run twice print ** and so on.
Setting up two loops
need i to print 4 lines and line number 1 to 4
for(i=1;i<=4;i++)
need j to be less than or equal to i's current value i.e if i=2 then j should be 1 and 2 , first printing * (for j=1) and * (for j=2) (total two times) for line no 2
for(j=1; j<=i;j++)
print("*");
after everything is done for that line i.e go to the next line - use \n newline
printf("\n");
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Try Printing
1
12
123
1234
This is very much similar the * pattern that was discussed
Only print value of j instead of printing *.
Formatted Input(scanf) and Output(printf)
scanf() and printf() are the in-built input and output functions in C. They are found in header file <stdio.h>. The f in printf() and scanf() specifies formatted input and output in which we can specify the format - width justification and precision as to where and how the output should be printed on the console.
Format Specifiers
Integer
short signed %d or %l
short unsigned %u
int %d
long signed %ld
long unsigned %lu
unsigned hexadecimal %x
unsigned octal %o
Real
float %f
double %lf
long double %Lf
Character
signed, unsigned char %c
String
%s
Width & Justification
If given number itself require more columns than specified than width value is ignored. If specified value of width is greater, blanks are padded in left side of the value to be printed.
%d - print an integer, 1 column wide.
%2d - print an integer, 2 columns wide
%nd - print an integer, n columns wide
%-nd - print an integer, n columns wide padding cells in right side of the value to be printed.
Precision
Precision value is used when we want a result to having values specifying the result having floating point upto certain number of digits.
a float (%f) originally shows 6 digits of precision
Suppose we want our output to show less digits.
%6.3f - specifies 6 columns wide real value with 3 digits after decimal point. Rest of digits after decimal point will be truncated.
Excape Sequence
Certain defined characters following backslash '\' are excape sequences that convey a special meaning to compiler.
\n - newline
\b - backspace
\' - single quote
\\ - backslash
\t - tab
\r - carriage return
\a - alert
\" - double quotes
\', \" is used because compiler understand anything enclosed in ' ' as a character and anything enclosed in " " as string. They when used without \ convey special meaning. When we have to use them as it is in output, we use backslash with them.
For example
printf("It said , \"I am from Mars.\"");
Output : It said, "I am from Mars."
If we try to print this statement without using \" compiler will give error because it can go crazy with such usage of " ".
Syntax of printf()
printf("Format String including format specifier, justification, precision", list of variable);
For example
int a=200; float b=20.6673;
printf("\nThe Value of Sum =%6d and rate=%4.2f", a,b);
Output
The Value of Sum= 200 and rate=20.66
Syntax of scanf()
scanf("format_specifier",&variable_name);
(&) -the address of operator
&variable_name : return address location ( hexadecimal value) of the variable it precedes
It tells the scanf to store the value input from the keyboard at memory location which variable a corresponds to.
For example
scanf("%d",&a);
stores and integer value in variable a.
Format Specifiers
Integer
short signed %d or %l
short unsigned %u
int %d
long signed %ld
long unsigned %lu
unsigned hexadecimal %x
unsigned octal %o
Real
float %f
double %lf
long double %Lf
Character
signed, unsigned char %c
String
%s
Width & Justification
If given number itself require more columns than specified than width value is ignored. If specified value of width is greater, blanks are padded in left side of the value to be printed.
%d - print an integer, 1 column wide.
%2d - print an integer, 2 columns wide
%nd - print an integer, n columns wide
%-nd - print an integer, n columns wide padding cells in right side of the value to be printed.
Precision
Precision value is used when we want a result to having values specifying the result having floating point upto certain number of digits.
a float (%f) originally shows 6 digits of precision
Suppose we want our output to show less digits.
%6.3f - specifies 6 columns wide real value with 3 digits after decimal point. Rest of digits after decimal point will be truncated.
Excape Sequence
Certain defined characters following backslash '\' are excape sequences that convey a special meaning to compiler.
\n - newline
\b - backspace
\' - single quote
\\ - backslash
\t - tab
\r - carriage return
\a - alert
\" - double quotes
\', \" is used because compiler understand anything enclosed in ' ' as a character and anything enclosed in " " as string. They when used without \ convey special meaning. When we have to use them as it is in output, we use backslash with them.
For example
printf("It said , \"I am from Mars.\"");
Output : It said, "I am from Mars."
If we try to print this statement without using \" compiler will give error because it can go crazy with such usage of " ".
Syntax of printf()
printf("Format String including format specifier, justification, precision", list of variable);
For example
int a=200; float b=20.6673;
printf("\nThe Value of Sum =%6d and rate=%4.2f", a,b);
Output
The Value of Sum= 200 and rate=20.66
Syntax of scanf()
scanf("format_specifier",&variable_name);
(&) -the address of operator
&variable_name : return address location ( hexadecimal value) of the variable it precedes
It tells the scanf to store the value input from the keyboard at memory location which variable a corresponds to.
For example
scanf("%d",&a);
stores and integer value in variable a.
Saturday, January 4, 2014
Right and Left Shift
Right Shift Operator (>>)
The Right shift Operator is represented by (>>) [pointing to direction it shifts the bits]
It requires to operands(on which operator operated). It shifts the bits of operand left to it towards right by places which is specified by the right of the operator.
The blanks created due to shifting are filled by 0s.
Operand to left of (>>) whose bits are shifted >> operand to right of (>>) number of places by which bits are shifted
1010>>3 equals 0001
Significance of Right shift
Lets take 25
Its binary equivalent
25 = 0001 1001
applying right shift
0001 1001>>1 = 0000 1100 = 12
applying a right shift to 12
0000 1100 >>1 = 0000 0110 = 6
applying a right shift to 6
0000 0110 >>1 = 0000 0011 = 3
At each step of right shift, we are actually dividing the given number by 2 (rejecting the decimal part if there is any 25/2 =12.5->we reject 0.5)
Left Shift Operator (<<)
The Left shift Operator is represented by (<<) [pointing to direction it shifts the bits]
It requires to operands(on which operator operated). It shifts the bits of operand left to it towards left by places which is specified by the right of the operator.
For each bit shifted, 0 is added to the right of the number.
0000 1110 << 1 = 0001 1100
Significance of Left Shift
Lets take 3
3 = 0000 0011
applying left shift to 3
0000 0011<<1 = 0000 0110 = 6
applying left shift to 6
0000 0011<<1 = 0000 1100 =12
applying left shift to 12
0000 1100<<1 = 0001 1000 =24
At each step of left shift, we are multiplying the number by 2.
Thursday, January 2, 2014
Constants
Constants: the items whose value do not change during program execution.
The constants include Integer, Real and Character constants.
Rules for constructing Integer Constants
Rules for constructing Real Constants
Rules for constructing Character constant
Examples : 'A', '9', '='
The constants include Integer, Real and Character constants.
|
Constant type
|
Permissible Range
|
|
Integer Constant
|
-2147483648 (231) to 2147483647 (231-1)
|
|
Real Constant
|
-3.4*1038 to 3.4*1038
|
|
Character Constant
|
Can have maximum length of 1
|
Rules for constructing Integer Constants
- Should have at least one digit.
- It must not have a decimal point.
- Can be either positive or negative.
- If no sign precedes a number, it is taken positive.
- No commas or blanks are allowed within the Integer Constant.
Valid Integer Constants
|
Invalid
|
4284
|
4,284
|
-38482
|
4 285
|
+42873
|
792.654
|
Rules for constructing Real Constants
- Should have at least one digit.
- Must have a decimal point.
- Can be either positive or negative.
- Default sign is positive.
- No commas or blanks allowed.
- Big real constants can be expressed in exponential form.
- The mantissa and exponential part is separated by letter e or E.
- Default sign for mantissa and exponent sign is positive.
0.000738 = 7.38
* 10-4
Here 7.38 is
the Mantissa part
And 10-4
is the Exponent part
In exponential
form it can be written as
7.38e-4 Or
7.38E-4
Valid Real Constants
|
Invalid
|
8912.12
|
4284
|
0.1231
|
4 285 . 06
|
-2371.001
|
Five.seven
|
-0.25
|
1,000.7
|
+3.2e5
|
4.3e
|
-4.32e-7
|
2E
|
3.55E-5
|
4,009E
|
-234.01E+6
|
2 e 21
|
Rules for constructing Character constant
1.
Must be enclosed without single quotation marks.
2.
Must be of maximum length 1.
3.
Can be a alphabet, a number or a special symbol.
Examples : 'A', '9', '='
Subscribe to:
Comments (Atom)

