I can't fix the logical error because I don't know what is wrong in this code. Every input, it shows "element not found". I would really appreciate it if someone can help me in this. Also in this code, I have assumed we'll be taking the size of the array as an odd number, what to do if we decide to take an even number as size?
#include<stdio.h>
int main(){
int size;
printf("Enter the number of elemets(odd number) : ");
scanf("%d",&size);
int arr[size];
printf("Enter the elements in ascending order : ");
for(int i=0;i<size;i++){
scanf("%d",&arr[i]);
}
int element;
int flag=0;
printf("Enter element to be found : ");
scanf("%d",&element);
int low=0;
int high=size-1;
while(low<high){
int mid=(low+high)/2;
if(element<arr[mid]){
high=mid-1;
}
else if(element>arr[mid]){
low=mid+1;
}
else if(element==arr[mid]){
printf("Element %d found at pos %d ",element,mid);
flag=1;
break;
}
}
if(flag==0){
printf("Element not found");
}
return 0;
}
The problem is your while test. You have:
while(low<high) {
...
}
This will fail when low == high if the desired value is at that position. It is easily fixed by changing the test to:
while(low <= high) {
...
}
This is all that's needed to fix it. You don't need to add any special cases to "fix it up". Just make sure your array is in ascending order and it should work.
EDIT: Refer to the better answer by #TomKarzes
My old answer is:
You missed a boundary case of high==low
#include<stdio.h>
int main(){
int size;
printf("Enter the number of elements(odd number) : ");
scanf("%d",&size);
int arr[size];
printf("Enter the elements in ascending order : ");
for(int i=0;i<size;i++){
scanf("%d",&arr[i]);
}
int element;
int flag=0;
printf("Enter element to be found : ");
scanf("%d",&element);
int low=0;
int high=size-1;
while(low<high){
int mid=(low+high)/2;
if(element<arr[mid]){
high=mid-1;
}
else if(element>arr[mid]){
low=mid+1;
}
else if(element==arr[mid]){
printf("Element %d found at pos %d ",element,mid);
flag=1;
break;
}
}
if(low==high && arr[low]==element) //Added 1 extra condition check that you missed
{
printf("Element %d found at pos %d ",element,low);
flag=1;
}
if(flag==0){
printf("Element not found");
}
return 0;
}
For starters for the number of elements of the array you shell use the type size_t. An object of the type int can be small to accommodate the number of elements in an array.
This condition of the loop
int high=size-1;
while(low<high){
//...
is incorrect. For example let's assume that the array has only one element. In this case high will be equal to 0 and hence equal to left due to its initialization
int high=size-1;
So the the loop will not iterate and you will get that the entered number is not found in the array though the first and single element fo the array actually will be equal to the number.
You need change the condition like
while ( !( high < low ) )
//...
This if statement within the else statement
else if(element==arr[mid]){
is redundant. You could just write
else // if(element==arr[mid]){
It would be better if the code that performs the binary search will be placed in a separate function.
Here is a demonstrative program that shows how such a function can be written.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int binary_search( const int a[], size_t n, int value )
{
size_t left = 0, right = n;
int found = 0;
while ( !found && left != right )
{
size_t middle = left + ( right - left ) / 2;
if ( value < a[middle] )
{
right = middle;
}
else if ( a[middle] < value )
{
left = middle + 1;
}
else
{
found = 1;
}
}
return found;
}
int cmp( const void *a, const void *b )
{
int left = *( const int * )a;
int right = *( const int * )b;
return ( right < left ) - ( left < right );
}
int main(void)
{
const size_t N = 15;
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < N; i++ )
{
size_t n = rand() % N + 1;
int a[n];
for ( size_t j = 0; j < n; j++ ) a[j] = rand() % N;
qsort( a, n, sizeof( int ), cmp );
for ( size_t j = 0; j < n; j++ )
{
printf( "%d ", a[j] );
}
putchar( '\n' );
int value = rand() % N;
printf( "The value %d is %sfound in the array\n",
value, binary_search( a, n, value ) == 1 ? "" : "not " );
}
return 0;
}
Its output might look for example the following way
0 2 2 3 4 5 7 7 8 9 10 12 13 13
The value 5 is found in the array
4 8 12
The value 10 is not found in the array
1 2 6 8 8 8 9 9 9 12 12 13
The value 10 is not found in the array
2 3 5 5 7 7 7 9 10 14
The value 11 is not found in the array
0 1 1 5 6 10 11 13 13 13
The value 7 is not found in the array
0 3 3 3 4 8 8 10 11 12 14 14 14 14
The value 3 is found in the array
0 5 5 10 11 11 12 13 13 14 14
The value 12 is found in the array
3 4 5 7 10 13 14 14 14
The value 14 is found in the array
0 3 3 7
The value 2 is not found in the array
1 6 9
The value 10 is not found in the array
2 2 3 3 4 4 4 5 5 6 8 8 9 13 13
The value 11 is not found in the array
11 11 13
The value 11 is found in the array
0 0 0 1 2 5 5 5 7 7 8 9 12 12 14
The value 6 is not found in the array
8 8 13
The value 1 is not found in the array
2 2 4 4 5 9 9 10 12 12 13 13 14 14
The value 14 is found in the array
Related
Have tried few basic pattern
trying to get pattern
1
2 4
3 6 12
4 8 16 32
SO far trying to find the proper sequence, my idea is that need another variable lets say num, and need to create a sequence for num to print num eventually
#include <stdio.h>
int main()
{
int rows = 0 , i, j , num,num2;
do{
printf("please enter the number of rows: ");
scanf("%d",&rows);
}while(rows <=2 );
printf("printing a half pyramid of %d rows", rows);
printf("\n");
for( i = 1; i <=rows; ++i) {
for (j = 1; j <= i; ++j ) {
printf("%d ", );
}
printf("\n");
}
return 0;
}
Not being able to figure out a sequence
The code you were given literally contains all the parts necessary. All that remains for you is to fill out this line inside the nested loop:
printf("%d ", ‹what goes here?›);
To find the answer you need to find how the value relates to the current row and column (give by i and j, respectively).
You don’t need an additional variable num (to be clear, you can create one, but it’s not necessary to solve this problem).
We, beginners, should help each other.:)
Here you are.
#include <stdio.h>
int main(void)
{
while ( 1 )
{
const unsigned int Base = 10;
printf( "Enter the height of a pyramid (0 - exit): " );
unsigned int n;
if ( ( scanf( "%u", &n ) != 1 ) || ( n == 0 ) ) break;
int width = 0;
unsigned int tmp = n * n;
do { ++width; } while ( tmp /= Base );
putchar( '\n' );
for ( unsigned int i = 0; i < n; i++ )
{
unsigned int value = i + 1;
for ( unsigned int j = 0; j++ <= i; )
{
printf( "%*u ", width, value * j );
}
putchar( '\n' );
}
putchar( '\n' );
}
return 0;
}
The program output might look like
Enter the height of a pyramid (0 - exit): 1
1
Enter the height of a pyramid (0 - exit): 2
1
2 4
Enter the height of a pyramid (0 - exit): 3
1
2 4
3 6 9
Enter the height of a pyramid (0 - exit): 4
1
2 4
3 6 9
4 8 12 16
Enter the height of a pyramid (0 - exit): 5
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
Enter the height of a pyramid (0 - exit): 6
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
Enter the height of a pyramid (0 - exit): 7
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
Enter the height of a pyramid (0 - exit): 8
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
Enter the height of a pyramid (0 - exit): 9
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
Enter the height of a pyramid (0 - exit): 0
The loops in the program can also look like
for ( unsigned int i = 0; i++ < n; )
{
unsigned int value = i;
for ( unsigned int j = 0; j < i; j++ )
{
printf( "%*u ", width, value );
value += i;
}
putchar( '\n' );
}
or without introducing the intermediate variable value like
for ( unsigned int i = 0; i < n; i++ )
{
for ( unsigned int j = 0; j++ <= i; )
{
printf( "%*u ", width, j * ( i + 1 ) );
}
putchar( '\n' );
}
You yourself can add a check to the program that n * n is not greater than UINT_MAX.
Edit: As you changed the displayed values in the pattern then the program can look for example the following way
#include <stdio.h>
#include <math.h>
int main(void)
{
while ( 1 )
{
const unsigned int Base = 10;
printf( "Enter the height of a pyramid (0 - exit): " );
unsigned int n;
if ( ( scanf( "%u", &n ) != 1 ) || ( n == 0 ) ) break;
int width = 0;
unsigned long long int tmp = n * ( long long unsigned )pow( 2, ( n - 1 ) );
do { ++width; } while ( tmp /= Base );
putchar( '\n' );
for ( unsigned int i = 0; i++ < n; )
{
unsigned int value = i;
for ( unsigned int j = 0; j < i; j++ )
{
printf( "%*u ", width, value );
value *= 2;
}
putchar( '\n' );
}
putchar( '\n' );
}
return 0;
}
The program output might look like
Enter the height of a pyramid (0 - exit): 10
1
2 4
3 6 12
4 8 16 32
5 10 20 40 80
6 12 24 48 96 192
7 14 28 56 112 224 448
8 16 32 64 128 256 512 1024
9 18 36 72 144 288 576 1152 2304
10 20 40 80 160 320 640 1280 2560 5120
Enter the height of a pyramid (0 - exit): 0
Tricky Pattern. Here, is a logic for that pattern with implementation.
'n' is the number of rows.
#include <stdio.h>
int main(void) {
int n = 4;
for(int i=1; i<=n; i++) {
int k=i;
printf("%d%s",k," ");
for(int j=1; j<i; j++) {
k = k*2;
printf("%d%s",k," ");
}
printf("\n");
}
return 0;
}
i am working on a program where the input is an ID of 9 numbers :
program checks if the id is correct or not by :-
checking if the string is formed by numbers only .
every number has a weight of 1 or 2 so it should be 1 2 1 2 1 2 1 2
1
multiply the weight and the number
if the number is bigger than 9 then add the numbers forming it .
if the number is from multiplication of 10 then the ID is correct ..
example :-
1 7 9 3 7 9 2 5 0-ID
1 2 1 2 1 2 1 2 1-Weight
1 14 9 6 7 18 2 10 0-num x weight
1 5 9 6 7 9 2 1 0-(4)
sum = 40 then it is a correct ID.
I wrote most of it but then i noticed that it has to be a string . so my questions are :
is there a way to put a string into an array?as doing it with an
array is way easier.
how do i locate a place in a string ? like if i want the third
character in a string how do i locate it?.
and here is the code that i did it does not work yet and it needs alot of changes but i guess i will put it anyways :-
#include<stdio.h>
#define N 9
void input(int num[N]);
int check(int num[N]);
int main()
{
int num[N],a;
input(num);
a = check(num);
if (a = 1)
printf("ID is correct");
else printf("ID is NOT correct");
}
void input(int num[N])
{
int i;
printf("Enter your ID (9digits) :-");
for (i = 0;i < N;i++)
scanf("%d",num[i]);
}
int check(int num[N])
{
int w[N] = { 1,2,1,2,1,2,1,2,1 },wxnum[N],i,tota[N],sum,g;
for (i = 0;i < N;i++)
wxnum[i] = num[i] * w[i];
for (i = 0;i < N;i++)
{
if (wxnum[i] > 9)
tota[i] = wxnum[i] / 10 + wxnum[i] % 10;
else tota[i] = wxnum[i];
}
sum = tota[0] + tota[1] + tota[2] + tota[3] + tota[4] + tota[5] + tota[6] + tota[7] + tota[8];
g = sum % 10;
if (g = 0)
return 1;
else
return 0;
}
Thanks everyone for your help.
You can get a string by doing
/*N is defined as 9 in your code.*/
/*Considering there is always a '\0' in every string, we should allocat N + 1 slot for your nine numbers and the extra '\0'.*/
char chStr[N + 1];
scanf("%s", chStr);
After you got the string, you can take advantage of the values of charactor '0' - '9' (their values are from 48 to 57 correspondingly) in ASCII table, and easily transfer the charactors into integers by doing:
int i = 0;
for (i = 0; i < N; i++)
{
chStr[i] = chStr[i] - '0';
}
If you are restrict on the type, you can transfer these char values into int values by adding extra two lines:
int num[N];
int i = 0;
for (i = 0; i < N; i++)
{
chStr[i] = chStr[i] - '0';
num[i] = (int) chStr[i];
}
Please note that my code didn't check the validation of user input. To make it more secure, you can use
scanf("%9s", chStr);
to declare the maximum length that the user can input.
I am working on a pattern that prints the following code using for loop
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
code is as follows, which results in slightly wrong output.
main(){
int i,j,k,n,num;
printf("\n Enter no of rows: ");
scanf("%d",&num);
for(i=1;i<=num;i++,k=num){
for(j=1,n=i;j<=i;j++,n+=k){
printf("%d ",n);
}
printf("\n");
}
}
And the code gives me this .
which is wrong from the output i wanted
1
2 6
3 7 11
4 8 12 16
5 9 13 17 21
The key to this is how you update n in the inner loop. You need it to take into account not just num but also i as you descend through each iteration. I've fixed num at 5 here and placed the assignment to k at the start of the outer loop as this will always be constant:
#include <stdio.h>
int main(void) {
int i, j, k, n, num;
num = 5;
for(i = 1, k = num; i <= num; i++){
for(j = 1, n = i; j <= i; n += k - j, j++){
printf("%d ", n);
}
printf("\n");
}
}
Gives:
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
I have to read in a text file with names and numbers. The names represent candidates in a dummy election (7 in total) and the numbers represent the voters. If the voter number is not in the range of the 7 candidates it gets thrown out but still stored. Finally, I have to print out the results of who won the election and how many spoilt votes there were.
This is my text file:
Robert Bloom
John Brown
Michelle Dawn
Michael Hall
Sean O’Rielly
Arthur Smith
Carl White
3 8 1 3 1 6 12 9 6 5 0 2 8 4
6 6 8 3 2 8 0 12 6 1 8 3 2 2
3 2 5 7 4 11 8 6 11 12 11 7 5 5
8 9 10 12 1 3 12 12 9 11 7 9 3 1
2 10 12 7 11 9 6 6 0 1 10 7 11 2
8 0 12 8 10 11 2 2 8 4 2 12 3 2
9 1 4 8 8 7 7 4 12 2 10 10 9 4
12 9 3 12 0 4 8 0 6 5 9 0 5 3
11 6 0 3 0
This is where I am stuck about how to scan these in properly
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
FILE * data;
int spoilt=0;
typedef struct
{
int votes;
char name[20];
}candidates;
void initialize( candidates *electionCandidates, FILE *data )
{
int i;
for( i=0; i<7; i++ )
{
fscanf( data, "%[^\n]%*c", electionCandidates[i].name );
printf( "%s\n", electionCandidates[i].name );
electionCandidates[i].votes=0;
}
}
int processVotes( candidates *electionCandidates, FILE *data )
{
int i; //tallying votes
int voter;
for ( i = 0; i< 365; i++ )
{
fscanf( data, "%d", voter );
if ( voter <= 7&& voter > 0 )
electionCandidates[voter-1].votes++;
else
spoilt++;
}
//catcher to grab winner
int maxValue, winner=0;
maxValue = electionCandidates[0].votes;
for( i = 0; i < 7; i++ )
{
if( maxValue < electionCandidates[i].votes )
{
maxValue = electionCandidates[i].votes;
electionCandidates[winner] = electionCandidates[i];
}
}
return electionCandidates[winner], maxValue;
}
void printResults( candidates *electionCandidates )
{
printf("%s won the election with a total of %d votes.\n There was a total of %d spoilt"
electionCandidates[winner].name, maxValue, spoilt);
}
int main() {
data = fopen( "elections.txt","r" );
candidates electionCandidates[7];
initialize( electionCandidates, data );
processVotes( electionCandidates, data );
printResults( electionCandidates );
fclose( data );
return 0;
}
When using scanf, you must provide the address of the variable that you want to scan the result into. Provide the address by using the & operator. Also, it is a good idea to check the result of scanf to ensure that it successfully scanned what you asked for. scanf will always return the number of elements successfully scanned, unless an I/O error occurred, in which case it will return a negative number.
Here's an fixed, annotated version of your program:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct
{
int votes;
char name[20];
}candidates;
// specify a new type to hold the election result data
typedef struct
{
int winner;
int maxVotes;
int spoilt;
} electionResult;
void initialize( candidates *electionCandidates, FILE *data )
{
int i;
for( i=0; i<7; i++ )
{
fscanf( data, "%[^\n]%*c", electionCandidates[i].name );
printf( "%s\n", electionCandidates[i].name );
electionCandidates[i].votes=0;
}
}
// This function can now return more than one value, because we've wrapped
// the relevant info into a structure called "electionResult"
electionResult processVotes( candidates *electionCandidates, FILE *data )
{
// declare the election result struct here (which we fill with data)
// we initially set all values to 0
electionResult er = {0, 0, 0};
int i; //tallying votes
int voter;
for ( i = 0; i< 365; i++ )
{
// scan the vote by providing the address of voter (using &)
int result = fscanf( data, "%d", &voter );
if (result == 1)
{
if ( voter <= 7&& voter > 0 )
electionCandidates[voter-1].votes++;
else
er.spoilt++;
}
}
er.maxVotes = electionCandidates[0].votes;
for( i = 0; i < 7; i++ )
{
if( er.maxVotes < electionCandidates[i].votes )
{
// update the values in the election result struct
er.maxVotes = electionCandidates[i].votes;
er.winner = i;
}
}
return er;
}
// this function now prints the result of the election by accepting an "electionResult" struct
void printResults( candidates *electionCandidates, electionResult er )
{
printf("%s won the election with a total of %d votes.\n There was a total of %d spoilt",
electionCandidates[er.winner].name, er.maxVotes, er.spoilt);
}
int main() {
FILE *data = fopen( "elections.txt","r" );
candidates electionCandidates[7];
electionResult er;
initialize( electionCandidates, data );
er = processVotes( electionCandidates, data );
printResults( electionCandidates, er );
fclose( data );
return 0;
}
Some tips:
You can't access variables declared in other functions. You must return the data you want from one function and provide it to the other function.
Avoid having variables declared at file scope if you can. For simple programs like this, it isn't much of an issue, but in general, using global variables tends to get messy fast.
You can't return more than one value from a function unless you wrap up the values in a struct, like the above, or alternatively, have your function accept pointers to the objects that will hold the result, similar to how fscanf accepts &voter and subsequently fills the voter variable with the appropriate data (if it can).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I was trying to print the last digits of the numbers from 1 till 100 in this format
1
2
.
.
9 9
1 0 0
The code i had written in is
#include<stdio.h>
int main(void)
{
int last_digit,i;
for(i=1;i<=100;i++)
{
while(i!=0)
{
last_digit=i%10;
printf("Last_digit=>%d\t",last_digit);
i=i/10;
}
printf("\n");
}
return 0;
}
But this runs into a infinite loop whenever i try to execute it. Could you tell me where the problem lies ?
Your inner while loop decreases i by dividing it by 10, so it never reaches 100. Try using another variable for the inner loop.
int last_digit,i,j;
for(i=1;i<=100;i++)
{
j = i;
while(j!=0)
{
last_digit=j%10;
printf("Last_digit=>%d\t",last_digit);
j=j/10;
}
printf("\n");
}
return 0;
You are decreasing i in every iteration in this line of the inner while loop
i=i/10;
The condition of the inner while loop explicitly states that after the loop, (i != 0) == false in other words, the inner while loop enforces i == 0 after the loop. Therefore, i remains smaller than 100 and your loop never finishes.
To solve your problem, use another iteration variable in the inner loop.
If I have understood your assignment correctly then what you need is the following
#include <stdio.h>
int main( void )
{
const int Base = 10;
int i;
for ( i = 1; i <= 100; i++ )
{
int x = i;
int n = 1;
while ( x / ( n * Base ) != 0 ) n *= Base;
do
{
printf( "%d ", x / n );
x %= n;
n /= Base;
} while ( n != 0 );
printf( "\n" );
}
return 0;
}
The output is
1
2
3
4
5
6
7
8
9
1 0
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
2 0
//...
9 0
9 1
9 2
9 3
9 4
9 5
9 6
9 7
9 8
9 9
1 0 0
If you are trying to print only last digit of number, you can print num%10
#include<stdio.h>
int main(void)
{
int i;
for(i=1;i<=100;i++)
{
printf("Last_digit=>%d\t",i%10);
}
printf("\n");
return 0;
}
If you are trying to print each digit of number then:
#include<stdio.h>
int main(void)
{
int i;
int j;
for(i=1;i<=100;i++)
{
j=i;
while(j>0)
{
printf("digit=>%d\n",j%10);
j/=10;
}
}
printf("\n");
return 0;
}
Please try to be clear in your questions.
At the end of the while loop i id zero gets incremented by the for loop I.e one. Then the for loop test is applied. Hence infinite loop