Showing posts with label c program. Show all posts
Showing posts with label c program. Show all posts

Saturday, June 6, 2020

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

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;
}