Adak 419 Nearly a Posting Virtuoso

Edit:
=====
The first problem I found with your code was the assignment of low and high to a[0] and a[9]. Low and high, should be index numbers, not values. On your first call, since nothing has been partitioned yet, the low and high should be 0 and array size -1.

I changed a bunch of other variables, simply to save time.

#include<stdio.h>

//int low,high,mid; These should be local, not global variables

void partition(int a[],int low,int high);
void merge(int a[],int low,int high,int mid);

int main()
{
    int a[10];
    int count;
    for(count=0; count<10; count++)
    {
        printf("Enter element number %d\n",count+1);
        scanf("%d" , &a[count]);
    }
    partition(a,0,9);

    for(count=0; count<10; count++)
    {
        printf("%d\n" ,a[count]);
    }
    return 0;
}

/*high is array[SIZE]-1 */
void merge(int a[],int low,int mid,int high)
{
  int i,j,k,l,b[20];
  l=low;
  i=low;
  j=mid+1;
  while((l<=mid)&&(j<=high))
  {
    if(a[l]<=a[j])
    {
      b[i]=a[l];
      l++;
    }
    else
    {
      b[i]=a[j];
      j++;
    }
    i++;
  }
  if(l>mid)
  {
    for(k=j;k<=high;k++)
    {
      b[i]=a[k];
      i++;
    }
  }
  else
  {
    for(k=l;k<=mid;k++)
    {
      b[i]=a[k];
      i++;
    }
  }
  for(k=low;k<=high;k++)
  {
    a[k]=b[k];
  }
}

void partition(int a[],int low,int high)
{
  int mid;
  if(low<high)
  {
    mid=(low+high)/2;
    partition(a,low,mid);
    partition(a,mid+1,high);
    merge(a,low,mid,high);
  }
}
Adak 419 Nearly a Posting Virtuoso

@adak:no....u r wrong.........have a look at the 3rd row over dere it's using 23 as min correctly.....how is dat so.......pls give da corrected code also....

Instead of arguing with me, and asking for the corrected code, please work on your program, and learn more about C. I'm trying to guide you, not do your homework. It's about you learning to program in C, not about how many assignments somebody will do for you, on the net.

Note that I never said that every row has the wrong (previous) row's minimum value. I said the second row had the previous rows minimum value.

I expect *you* to step up and find out why that is. You'll learn something more about C in the process, and troubleshooting code, as well. You *WILL* have to debug lots of code in programming, so it really helps to get good at it, early on.

You received an "absolute gift" of a fixed program, today. You should thank him, and understand that kind of help won't be available, every day.

Adak 419 Nearly a Posting Virtuoso

Well, that's a kicker, for sure!

I would *definitely* use a struct to keep all these bits of data, organized with the employee.

You must be overseas. Some of that English is "French" to me. I understand the words, but what does it mean?

"Use the round function in math.h" ?? There is no round function, in any header.

"... and to calculate the income tax cuts and the minimum number required for a program to make money using the salary payments." ??

Sounds like he wants your program to skim off money illegally, doesn't it?

Well, that's for you to work with. If I can help with your program, you know where to find me.

Adak 419 Nearly a Posting Virtuoso

It's standard, if not for beginners.

Three ampersand (star) programmers are generally mocked a bit, however.

Adak 419 Nearly a Posting Virtuoso

Easy sort is ALMOST the same as a bubble sort, but the inner loop of a bubble sort ONLY compares ADJACENT values in the array. n with n+1, for instance.

Now look at Easy sort's inner loop. It STARTS the inner loop comparing n to n+1, but then it compares n to n+2, then to n+3, and so on. Those are NOT all adjacent values in the array. Only one of them is adjacent, in fact, at the start of each inner loop.

Also, in the bubble sorts that I've seen, they use a flag variable like "sorted", and it's set to zero in the first lines of the bubble sort. When Bubble sort completes a pass, and it has found nothing to sort, it sets the "sorted" variable to 1, and subsequently leaves the outer sort loop.

So Easy sort is definitely in the same sorting class as Bubble sort, but it just doesn't "Bubble", the values up, like Bubble sort does.

Although the number of comparisons may be similar on a particular sort, Selection sort will ALWAYS have the lowest possible number of swaps made - that's what it was designed to do.

Adak 419 Nearly a Posting Virtuoso

HELP???

#include <stdio.h>
#include <math.h>
#include <string.h>

int main()
{
	FILE *inputfile, *infile;
	
	double mark;
	int grade;
???	int avg = 0.0;  
	int i = 0;
	char student[30];
	char filename[30];
	char *first, *last, *middle;

	printf ("Enter Name of Data File: \n");
	scanf ("%s", filename);

	inputfile = fopen( filename , "r");

Not "student". You will create "student" string. You need to take in %s %s %s for last
name, first name and middle initial. Also, last ) should go before "!".

???	while ((fscanf (inputfile, "%s", student) != EOF))<-Two } before !, one } here
	{
		for (i = 0;i>=0;i++)
		{
??? Move upward ^^			fscanf(inputfile, "%s %s %c", last, first, middle);

?? create student string, slightly better, imo.
	infile = fopen( strcat(first,last).dat, "r");

??? grade=0; grade != 0 ??? loop will never loop! Use another while loop, not 
a for loop if that helps your thinking. I would use a while loop.

???		for (grade = 0; grade != 0; grade++)
		{
			fscanf (infile, "%d", &mark);
??? You can't keep a sum building, when you're replacing the value with fscanf(),
each time through the loop. Use a sum variable: sum += mark;

???			mark = mark + mark;
			avg = mark/grade;
		}
		}
	}
	return 0;
}

If you type your own code tags, the slash on the closing tag is a / not a \.

Good start, but a few rough edges.

Adak 419 Nearly a Posting Virtuoso

Excuse my earlier post, when you start talking about a new sorting algorithm, I easily get a new focus.

Yes, Selection sort is stated as an O(n^2) algo. This has NOTHING to do with your own hybrid algorithm, however efficient it may be. The Wikipedia article that you referred to spells out the reason why -- I can certainly do no better.

Where Selection sort shines, is when you have a situation like this:

Say you have a sorting job where the comparisons are quickly made, but the swaps are incredibly time-consuming due to network constraints. Selection sort is the algo you want to use, in that case. It ALWAYS makes the fewest swaps of any sorting algorithm.

In everyday life, it's the sorting algo you would use if you had a job of sorting out a huge yard of vehicles, according to type, and currently they were all mixed up. Any other algorithm would have you moving cars FOREVER, to get things right. But using Selection sort, it would be as easy as it can be. Because the comparisons are cheap (you can tell just be looking), but the time and effort to swap vehicle parking spaces, is very high comparatively.

Aside from this huge efficiency with minimal swapping, Selection sort has nothing to recommend it, imo.

To judge it accurately, be sure you're using the REAL Selection sort, and not a hybrid algorithm. Just for fun, count the number of comparisons made …

srinivasan106 commented: very nice adak.. thank u for good explanation. +1
Adak 419 Nearly a Posting Virtuoso

The first problem I found is the while loop in main(). It has some nice bits of logic, but the overall program flow is flawed.


This is your while loop, with just a few changes:
1) The newline char is now removed from line[], right away
2) The FILE pointer you called "file", I changed immediately to "fp". Although C is case sensitive, I won't put up with that kind of name confusion.
3) I added the int variable j, and moved i and j declarations, to the top of the function.

The problem is that word[] was being sent to Palindrome(), and word[] had only one valid letter in it.

while((fgets(line,MAX,fp))){					//for some reason, this produces
		//int i;										//line of second mixed with first
		printf("%s\n",line);
		fflush(stdout);
		for(i = 0; line[i] != '\n'; i++){
			c = line[i];  //why assign an int, a char from the array of line?
      //remove the newline char:
      j = strlen(line);
      if((line[j-1])=='\n')
        line[j-1]='\0';

			if(isalpha(c)){
				word[wl] = c;
				wl++;
			}else{
				if(wl>0){
					word[wl] = '\0';
					printf("%s",word);			//for testing
					fflush(stdout);
					words++;
				}else{
					continue;					//if it's a single non-alpha
				}								//it's not a word
			}

			if(isPalindrome(word) == 0){ //not good here - word holds trash atm.
				new = (struct pal*)malloc(sizeof(struct pal));
				new->word = word;
				new->count = 1;
				if(front->count == -1){
					front = new;
				}else{
					new->next = front;
					front = new;
				}
			}

			wl = 0; //each letter then gets stuffed into word[0]
		}
	}

So Palindrome() is being called WAY too soon. …

mi.mac.rules commented: Great Advice! +1
Adak 419 Nearly a Posting Virtuoso

Your input stream is still holding the newline char. Remove it by adding this:

(void) getchar();

After each time you're looking for a char input (getchar or scanf(%c)).

fflush(stdin) is non-standard, and generally doesn't work, because stdin is an input stream, not an output stream.

And Welcome to the forum, Caeon! ;)

Adak 419 Nearly a Posting Virtuoso

Algoritmus, your code is OK.

Understand that Ancient Dragon is being technically correct and please don't:

1) Get upset. Get comfortable in your skin, and "thicken" it. Don't feel threatened by a critique of your code or pseudo code. That's what we do here!

2) Please stop making excuses. "It's a simple function", "it's pseudo code". Neither invalidates the critique made.

No one is at the top of their form all the time, no one is right 100% of the time. If the creator of C can make errors in his book on C, you and I, and AD, can (and will), make errors as well.

It doesn't mean you're not a good person, or a good programmer. Just PLEASE don't make the mistake that sends the guys away from Mars, heading for Jupiter instead. That's all I ask. << C'mon smile >> ;) ;)

Adak 419 Nearly a Posting Virtuoso

Here's my suggestion:

1) Let's get out of the damn graveyard, looking for something alive. You'll spend more time, and get far less learning done, trying to make a living program, from the bodies of the dead, than if you just wrote a your own program.

The struct part will be about the same. Shit can the rest.

We will assist.

2) Let's use (at least approximate), some good top-down design methodologies. Beats the shit out of trying to resurrect zombie programs.

3) This is the starting point:

You are developing a database of measured meteorological data for use in weather and climate research. Define a structure type measured_data_t (which I have done) with components site_id_num (a four digit integer), wind_speed, day_of_month, and temperature. Each site measures its data daily, at noon local time. Write a program that inputs a file of measured_data_t records and determines the site with the greatest variation in temperature (defined here as teh biggest difference between extrema) and the site with the highest average wind speed for all the days in the file. You may assume that there will be at most ten sites. Test the program on the following July daily data collected over one week at three sites:

ID Day Wind Speed (knots) Temperature (deg C)
2001 10 11 30
2001 11 5 22
2001 12 18 25
2001 13 16 26
2001 14 14 26
2001 15 2 25
2001 …

Adak 419 Nearly a Posting Virtuoso

Pretty much the same way you find your shoes in the morning:

1) scan the floor, find the left shoe
2) scan some more floor, find the right shoe.

Check if the strings are the same, about the same way you see if your shoes are a matching pair:

1) same color
2) same size
3) same style

How would you check if "this string", was the same as "that string"?

1) same letter, in the same place, in two char array's
2) all the way to the end of the string.

strcmp() will do this, but if you want to learn how to program, why not "roll your own" here, and learn a bit.

strchr() will check a string for a left parentheses, and then you can ask it to check a string for a right parentheses.

For both the above, include the string.h file.

Using fgets() to put each row of text to be scanned, into a char array, should be perfect for your purposes.

fgets(NameOfBuffer, sizeof(Buffer), filePointerORstreamName);
Adak 419 Nearly a Posting Virtuoso

Have you tried testing the return from sscanf() ?

When it return anything less than 1, you should be at the end of the file - or at least something stopped sscanf() from working right.

It is frustrating how you have to "dance around" to do such a simple thing.

creeps commented: I love to hate the last sentence :) +1
Adak 419 Nearly a Posting Virtuoso

I have a better idea: You read the Wikipedia article on Sieve of Eratosthenes, and get started on implementing that algorithm, into your program.

Then you post it, when and if you get stuck or have questions - and we will strive to help out.

Because we're not a homework service, and nothing helps your learning more than having you actively engaged in the whole learning process.

And welcome to the forum!

Adak 419 Nearly a Posting Virtuoso

I've thought this through a bit more. You can do this with your current compiler. It's not as easy, but here's how:

Make the bigNum a long double data type. Add #include <math.h> for the floating point packages (doubles and floats both).

Now take the sqrt() of bigNum (800 651 475 143.00), and put that sqrt() into another long double variable. Let's call that variable numbr.

Then an unsigned long int num = numbr / 1; //yes, that's a one

Which will get rid of all the digits after the decimal place, and we'll have the right number we want - 775,146.

That's the highest possible prime number less than bigNum. Now you can deal with a much smaller number, and avoid bigNum, for now. An unsigned long int will handle 775,146 very easily.

All you have to do now, is find the largest prime number below 775,146, that is also evenly divisible into bigNum.

Once we have all the prime numbers, we can use an int array to test those numbers, and just repeatedly subtract to simulate division. (Much easier than doing long division with int arrays).

It won't be blazing fast, or all that easy, but if you can't find other solutions you like, it's a way to do it.

This is a bit muddled, but shows getting to the sqrt() of the bigNum, and putting it into an unsigned long int. This was done on an old 16 …

Adak 419 Nearly a Posting Virtuoso

C has functions to print up, or help you print up dates, in a variety of formats.

So free the memory, afterward. As long as you have the right address, what function you free the memory in, won't matter to the OS.

There's no need for the cast you have on the pointer from malloc(). C does that for you correctly, in this case.

for numbers in a field two columns wide, with 0's padding in front as needed:

printf("%02d", number);
Mouche commented: Quick and helpful reply with a simple solution +4
Adak 419 Nearly a Posting Virtuoso

Srinivasan, you should know that we get a lot of students just asking for "the code", to save them having to do any work.

Atomic33 is such a poster, so far. He's put no work into this thread.

If you give out programs to these kinds of posters, the forum will be plagued by more of them, before long.

Make them show some work. Sometimes I'll give an incomplete program if the logic is rather involved.

Ancient Dragon commented: Exactly +33
Adak 419 Nearly a Posting Virtuoso

I'm assuming he's not a brain dead yokel that just fell off the turnip truck yesterday, and will adjust MaxLength to whatever size he needs.

Of course.

Adak 419 Nearly a Posting Virtuoso

ddd ccc eee is not in sorted order, so I'm not sure if you want to sort in ascending or descending order.

You should keep the 2D array, no need to change that.

you can't use temp like you have it in the sort portion. When you assign it to the address for string1, that's fine.

But then you strcpy string2 into string1! Guess what temp is pointing to NOW?

Then you're putting string2 right back into string2 with the final assignment from temp to string2.

Print out your sort when it swaps, and see it. Put in a getchar() to stop it after every swap, if you don't step through it with watches set.

Better to make temp an array, instead of a ptr, imo.

smith32 commented: Thz to u.... ur solution is more suitable to me +2
Adak 419 Nearly a Posting Virtuoso

Welcome to the forum, Priva.t! ;)

A few very solid suggestions for you:

1) For your problems, unless it's EXACTLY the same, always start a new thread
2) You have to be VERY specific about what you are asking about. "Draw nonlinear objects", doesn't tell anyone what you are stumped on doing.

3) With your first post on a subject, post your efforts to solve the problem. This is a forum policy to reduce the "I need the codes for this!" kind of posts.

Adak 419 Nearly a Posting Virtuoso

int width = 7;

Then replace your blank printing loop with:

for(k=width;k>(i*2);k--)
                {
                               printf(" ");                     
                }

Note that the loop above prints just ONE space char, at a time, instead of two space chars, as the current loop you have, does.

Adak 419 Nearly a Posting Virtuoso

continue statement is designed for loops (for or while, or do while). Wouldn't make sense to try and use it in an if/else statement.

You can have a "do nothing" in an if statement, however:

if(numberOfApples > 1)
  ;               //nothing gets done
else
  printf("\nNo apples here yet!");

Good pseudo code is just structured English or language:

for each apple in the bowl {
  if the apple is ripe
    remove the core
    remove the skin
    slice it into 8th's
    roll it in cinnamon and sugar
    put it into the pie
  else
    if the apple is green    
      return it to the bowl
    else
      throw it out
}

Mine is generally a toss up between BASIC, C and Python. The key thing is that the logic has to be understandable. I'm no pseudocode guru, however. ;) I'm sure your teacher will have a preferred way that he/she wants it done. THAT's the way to do it, as least for now. :D

Adak 419 Nearly a Posting Virtuoso

Then you want to sort the words, alphabetically, not according to the length of the word. We can't have things like:

bat
and
the
cow
the
and

for a sorted word list. We need:

and
and
bat
cow
the
the

and looking at the list, you can perhaps see why.

Now we scan through the word array, and if word[0] is equal to word[1], then that word is not unique. strcmp() will make that comparison for us.

If the word is not repeated (and we again need a flag like outside to keep track of that), then we know that word is unique, in the string.

This is the kind of thing I had in mind:

# include <stdio.h>
# include <stdlib.h>  // for "system("cls");" to clear screen
# include <ctype.h>   // for isalpha(), ispunt()

#define ROWS 20
#define COLS 20
 
void distintwords(char s[]);

int main()
{   
  int i;
  char x, n;
  char s[500]={"Night is drawing nigh. Shadows of the evening, steal across the sky."};


  while(1)
  {
    //system("cls");       
    printf("\nEnter the string: ");
    //fgets(s, sizeof(s), stdin); 
    printf("\n%s\n", s);
    distintwords(s);

    printf("\n\nPress ENTER to try again, 'q' to quit : ");
    x = getchar();
    if (x=='q')
      break;
  }
  i = getchar(); ++i;
  return 0;
 }
void sort(char words[ROWS][COLS], int row) { 
  int i, j;
  char temp[COLS];

  for(i=0;i<row-1;i++) {
    for(j=i+1;j<row;j++) {
      if(strcmp(words[i], words[j]) > 0) {
        strcpy(temp, words[i]);
        strcpy(words[i], words[j]);
        strcpy(words[j], temp);
      }
    }
  }
  //for(i=0;i<row;i++) …
Adak 419 Nearly a Posting Virtuoso

Let's look at some logic for distintwords():

here, I've added
#define ROWS 20 //and
#define COLS 20 //as well, right below the include files.

I removed conio.h, string.h, and added #include <ctype.h>. Removed some other variables, as well. notes in the code for most of it.

str1[][] I renamed words[][], because variable names beyond k that have no particular
meaning to me, drive me bonkers.


an N appended to the end of a variable name, means it's a Number. row and col inside the function, are not related at all, to ROWS or COLS, of course.

void distintwords(char s[])
{
  int i,j,col,row,wordsN=0,pnctsN=0,spacesN=0,breaksN=0; //no k, etc.
  int count, n, outside;     //no len or arr[20], added outside
  char words[ROWS][COLS];
                             //len = strlen(s)-1;
   
  for(i=0;i<ROWS;i++) //sets the words[] to empty - a precaution
    words[i][0]='\0';

  //this loop scans the entire string s, initial state is outside
  outside=1; row=i=j=0;
  while(s[i]!='\0')
  {
    if(isalpha(s[i])) {     //it's a letter in the range of a-z and A-Z
      words[row][j]=s[i];   
      if(outside) {         //new word
        wordsN++;       
        outside=0;          //not outside any more
      }
      ++j;                  //j is the col of the words[row][col] 
    }
    else if(s[i]==' ' || ispunct(s[i]) || s[i]=='\n') { //end of a word
      words[row][j]='\0';      //add end of string marker 
      outside=1;               //we're outside 
      if(s[i] ==' ')
        spacesN++;             //count it, if it's a space
      else if(ispunct(s[i]))   //must come after test for space char
        pnctsN++;              //or it will count spaces, also.

      j=0;                     //reset column for new word
      ++row;                   //start a new word, on a new row …
Adak 419 Nearly a Posting Virtuoso

You already have divided the sentence into each word! When you counted it, remember?

When you find the first letter of a word, you start putting all letters into a row of the wrds array. Keep going until you hit the next space or punctuation char.

Then go to the next row. :)

You'll want a loop for that:

for(i=0;i<ROWS;i++)
  if(word[i] && OUTSIDE) { //add && !punctuation to this
    //it's the start of a new word
    OUTSIDE= 0;
    col=0; //row value is carried into this loop
    wrds[row][col]= word[i];
    col++;     
  }
  else if( //code to handle char's when you are already inside a word ) {
    //col variable is not reset to zero
    wrds[row][col]= word[i]; 
    col++;
    
  }
  //etc.

That kind of thing. Have an errand or two to run, back in 2 hours.

Adak 419 Nearly a Posting Virtuoso

If you can't do this, almost without thinking, then it's time you learned how. Really, this is the most basic logic and syntax to learn, after "Hello World".

Get in there! ;)

Anybody who'd do it for you, is doing you NO favors.

Adak 419 Nearly a Posting Virtuoso

It's dicey to overwrite data in a file - any error, even a disk error, can ruin the entire file, until the file is rebuilt. That is a time consuming process, which may not fix all the data, anyway.

So what to do?

Most programs do it this way: When a record should be deleted, you don't actually delete it, you just mark the record ID number field (or maybe a name field), with a 0 (zero). The record space is still there, but it won't be shown on any searches or print outs. You make adjustments in those functions to ensure that is the case.

Also, your program should have logic to let it know to look for a zero'ed out record, when it needs to add a record. If the program detects too many empty records, (it counts them on start up each time), then it will compress them, at a convenient time (maybe the middle of the night, or when you try to close it down, next time). The idea is that instead of shifting all these records "in place", it will simply write all the good records into a new file, and then re-name that file, to it's current file name.

Do you see the difference? Instead of 25 overwriting operations, each involving moving say, half the records in the data file each time, you will have *maybe* one re-writing operation, which can take place at a time of your choosing.

Ancient Dragon commented: Excellent :) +31
Adak 419 Nearly a Posting Virtuoso

dos.h functions work fine in WindowsXP and Windows2000 (both 32 bit), but the compiler has to support those functions. It appears that Dev-C++ does not do that.

Turbo C supports all the dos.h functions that I've tried, over the years. (I have Turbo C/C++, ver. 1.01). It's a free download at the legacy Borland download site - you may want to use it, instead of Dev-C++, to get those functions working. It has conio.h included, so you don't need to worry about using curses at all.

Adak 419 Nearly a Posting Virtuoso

I wouldn't go that way with your logic. Don't use ascii numbers for your letters, unless you really need to. Use char's for letters, and stick with 'A', 'B', etc., instead - much easier to read and intuitively understand.

A couple things to get figured out:

1) You need to find the largest char to set as your remove char, in case the instructor (or you), wants to do this with a larger string that goes up to 'G' or beyond.

2) You'll need to print up strlen(c)/2+1 rows. So there's an outer for loop.

3) Your inner for loop

#include <stdio.h>


int main() {
  int i, j, len; 
  char c[15] = { "ABCDEFGFEDCBA" };
  char remove = 'A';

  printf("\n\n%s", c);
  len = strlen(c);

  for(i=0;i<len;i++) {   //find the greatest char
    if(c[i] > remove)
      remove = c[i];     //set it as the remove char
  }
  for(i=0;i<len/2+1;i++) { //for each row to be printed
    for(j=0;j<len;j++) {   //check each char in c[]
      if(c[j] == remove)   //and if it's the remove char
        c[j]=' ';          //replace it with a space
    }
    --remove;              //decrement the remove char
    printf("\n%s", c);
    
  }
  
  printf("\n\n\t\t\t     press enter when ready");

  i = getchar(); ++i;
  return 0;
}

;)

Shikhin commented: Thanks +0
Adak 419 Nearly a Posting Virtuoso

If you have your pseudo code written out, then post it up. Of course, I know you didn't do it, and you're bull-shitting me, but that's OK. Everyone will try the "I'll lie and he'll buy it maybe, what have I got to lose?", tactic.

I've been around far too long to believe it, but I'm hoping you'll say "damn that Adak, I'll write down some pseudo code, and post it, just to prove he's wrong", and that will be fine. ;)

Veracity may be scarce here, but believe this - I will *not* post so much as one semi-colon of code, until I see you post up some pseudo code or actual code. Doesn't matter which one.

Put some "skin" into this effort. Don't post up "still having a problem", post up your attempt, and state clearly and specifically WHAT the problem(s) is/are.

I want to help you, and I want to believe you. You're just not making that possible, so far.

jonsca commented: Very direct +4
Adak 419 Nearly a Posting Virtuoso

Get to know the problem - really analyze it, in this case, by doing it by hand with paper and pencil.

After you get the steps down into small steps which you can readily identify, then write down those steps -- That's your pseudo code.

Check your pseudo code, that it's correct, and then put one small step onto one line, and see if you can make that logic, into actual C code.

Don't worry the details, for now. Get the "flow" of the program working. A function (or block of code), for input, for output, for processing, is common.

After you get the major logic code working, add in the details you put off, earlier.

And welcome to Top Down Design, and the forum. ;)

Post up your attempt at the above, and I'll show you a slick trick for programming the above. The reason is that programming is, after you get past the basics, a lot of problem solving. You have to get used to solving problems like this one, and the sooner you get into that, the better.

So, no code will I give you, right now. Work with it, and show what you come up with.

Adak 419 Nearly a Posting Virtuoso

Use fgets in a while loop. When fgets() returns NULL, then you have reached the end of the text file. Aha!

Inside that while loop, fgets() will put each line into your char array, which must be large enough to fit all the names into for ONE line. (for even the longest row, plus 1 for the end of string char which it adds).

Then, you use strstr() to search for the target name, within your char array. If it returns a valid pointer (instead of NULL), then your name is in the char array.

The char array can be just one dimension, since each line from the file, will be handled sequentially.

If you want show - so do I. Put some skin into this assignment, and post your code to try this, and tell us what your problem is.

DON'T just say "Please fix this, it doesn't work". Because that doesn't work for us. We want to help, not be your homework bitch. ;)

Adak 419 Nearly a Posting Virtuoso

ok ! suppose i entered values for num : 2, 5 , 7, 9, 3
the program first check every value with the value inside the loop j ? which means it will check with the next value of num ?
for example,
here first value for num is 2 so the first value of num[j] would be 5 ?
am i right ?

Yes!

No sense comparing 2 with 2! ;)

Adak 419 Nearly a Posting Virtuoso

Depends (and I hate to go "Clinton" on ya) ;) what your definition of "merge" is.

Joey's post showed an interleaving of char's, so if your arrays were thus:

char a[] = {"acegikmoqsuwy"};
  char b[] = {"bdfhjlnprtvxz -- It's working"};
  char c[80] = {'\0'};

You would wind up with the correct alphabet in c[] + " --It's working"

And of course, you can do this with just integers for indeces, and without using string h.

The whole program I described is 29 lines of code, including the #include line for stdio.h, and explicit lines for ++i and ++j, and the printout at the end. I just wrote it to clear up a nagging thought I had.

Works fine.

Ancient Dragon commented: Yes you are right. I had not noticed that. +28
Adak 419 Nearly a Posting Virtuoso

With nested loops, the comparisons become:
a to a[j]
==========
a[0] to a[1]
a[0] to a[2]
a[0] to a[3]
a[0] to a[4] <<j loop exits, after this comparison
a[1] to a[2]
a[1] to a[3]
a[1] to a[4] << j loop exits again, after this comparison
a[2] to a[3]
a[2] to a[4] << j loop exits again, after this comparison
a[3] to a[4] << last break out from the j loop, because j is no longer < 5
Now, the i loop breaks out because i is no longer < 5
============================================
End of Selection sort of 5 values

I've noticed that you're having trouble with these basic concepts of loops, etc.

Study up, because most posters, will not have the time or the patience, to write up answers like this. That includes me, as well.

Adak 419 Nearly a Posting Virtuoso

An easy way to find duplicates is to sort the list of names, that puts the duplicates right next to each other in the list. Then run through the list and if list == list[i+1], then you have a duplicate. Stop the search at one less than normal, or else list[i+1] will be out of bounds of the size of the array.

If you need to print up other info on these people, then you need to include that info and put it into a struct along with their other pieces of info, (recommended). If you haven't had structs yet, then you can use parallel arrays for this (works, but it's not nearly as elegant).

Let's start a new thread with a better topic, if you want help with structs or parallel arrays. "Binary Search" is misleading, and that problem is solved.

Adak 419 Nearly a Posting Virtuoso

your strcpy parameters are backwards:

strcpy( destination, source).

How are you handling the sort requirements for the names, so Binary search will keep working?

Adak 419 Nearly a Posting Virtuoso

You need to change the file name extension, right off!

Recommendations:

1) Dot cpp is the default file extension for C++, so it can cause much confusion and wasted time. Change it to just dot c, and then we're at least running on the same language compiler

2) gets() is very unsafe, since it makes no check on the length of the string it is getting from the user. Use
fgets(bufferName, sizeof(bufferName), stdin), instead.

3) flushing stdin is non-standard and doesn't always work. Use getchar() to pull the newline off the keyboard buffer, as needed.

4) feof() doesn't act as you suspect or hope.
while((fgets(buff, sizeof(buff), fp)) != NULL) { is much better.

where buff is the name of a char array big enough to receive the line of text (all of it).

You haven't said what your problems with coding up these changes are, so I don't know what else to advise, right now.

Once you know how to find and display one record from the file, there's no difficulty in displaying a page full of records at once, prompting the user to hit enter to continue, and displaying the next page of data, until either the end of the file, or the user presses q to quit the display of records.

Programs involve very explicit code and use very exact logic (good or bad, the program uses it). So the more specific your questions are, the better …

Salem commented: Yes +20
Adak 419 Nearly a Posting Virtuoso

You only need one for loop:

for(i = 0; i < 2; i++)  
{
  Ask for the user to enter a temp
  user enters a temp
  You check the user's entered number to see if it's greater than 
  max  temp
  
  Now print the number user entered

}
print max temp
Xufyan commented: thanks :-) +0
Adak 419 Nearly a Posting Virtuoso

Xufyan, you are going to *have* to learn to indent your code and especially your braces, like you are sane - even if you're not ;)

for(i = 0; i < whatEver; i++)
{
    //other code in here, then:
}

Note how the braces line up with the first line of code - their "parent line". Your eye just flows, right to the major and minor lines of code, and it only gets better as you code more often.

You indent your code like that, and you'll see the answer. You print max temp right after the last closing brace of the for loop.

Why?

Because you're done entering data.

jephthah commented: lol. i agree, that drives me nuts. +7
Adak 419 Nearly a Posting Virtuoso

Maybe the idea was to simply explicitly print the answers, and getting the data columns, lined up.

There is no choice needed, so no if statement is necessary, imo.

Standard practice would be to use a loop to print this table up.

Adak 419 Nearly a Posting Virtuoso

Didn't you forget the rule about "Must not use any cpu cycles"? ;)

Adak 419 Nearly a Posting Virtuoso

Sure! Why not?

Here's the thing -- you have to contribute idea's and sometimes, code into this. I'm not going to just post up a program for you, and I hope you don't want to be a "code leech".

So, what does your instructor say to use for an algorithm to solve this? No sense posting on and on about Depth First Search (DFS), if your instructor wants you to use another type of search.

So what, Arshad and Lucy, does your instructor, require for this assignment? What does he suggest you use?

And post up some code, that shows you have some "skin" in the program.

I use DFS for about everything, (and know very little about other types of searches), but others may be along with a broader knowledge, to match your needs.

Welcome to the forum: Arshad, Aliakseis, and Lucy! :)

Adak 419 Nearly a Posting Virtuoso

There is an easy solution to this. Use Ira Pohl's theorem, on top of Warnsdorff's algorithm.

iirc, it means if you find two squares that evaluate as equal in connectivity, then you extend the search depth another ply until the subsequent moves do not evaluate to even anymore.

If you go to Wikipedia, on Warnsdorff's algorithm, it has a link to a free version of Pohl's paper on it.

I haven't played with it in a program, but it lead me to believe that you could solve the problem much faster, because it stops "blind alleys".

Didn't see any figures for using it on different size boards, etc., however.

Adak 419 Nearly a Posting Virtuoso

Your movies array may not be what you expect. If you have
char *moves[100][5];

Although you've neatly typedef'd it to look different, what you have is a char pointer array that is 100 x 5, and not a char array 100 x 5.

All you need is a flat file database.

Why not put the movie characteristics that you want to record, into a record, with fields? In C you'd use a

typedef struct {
  long id;
  char name[40]; //  (or char *name; and malloc the memory later)
  char lead_man [25];
  char lead_lady[25];
  char cat[25]; //category
  char direct[25]; //director
  char *notes; //malloc memory later)
}movie;

movie movies[100];  //make array of 100 records

Anyway, I'd recommend doing something like that. It groups all your data on a film, all together, and it's pretty simple to code one up.

Adak 419 Nearly a Posting Virtuoso

Take a step back and ask yourself, WHY?

You can use printf() to print out your int array, in a loop, and control just exactly how you want it to appear. So why change the data type, at all?

But let's say you want to really use a char for printing out your int's. What are you going to do when your small range of a char, is exceeded?

I'm just bothered by the choice to go from the direct, to some circuitous route just to print up an array.

Rube Goldberg would love this, but it really bothers me. Google that name if you don't know what it stands for.

jonsca commented: I thought about the Rube Goldberg thing too. +3
Adak 419 Nearly a Posting Virtuoso
fscanf(FilePointer, "%f", &variableName);

All the scanf() family of functions are subject to quitting the first time they receive data that they aren't set up to handle. It's important to check their return value to see if it actually worked or not, (it returns the number of items it has successfully handled), and it should only be used on data that is FORMATTED properly. Data that variies from one week to the next, is not a good candidate for fscanf().

jephthah commented: well said +6
Adak 419 Nearly a Posting Virtuoso

Use fgets(CharArray, sizeof(CharArray), YourFilePointer);

to put each line into the CharArray[80 or so], that you've previously declared.

Now you can use for or while loops, to "walk" through the CharArray[], and pick out the tabs, and spaces, etc.

When you find the line meets your needs, then put the end of string char: '\0', as the very last char. In C, this is NOT a string:

John

THIS is a string:

John'\0'

Even though you don't see the end of string char on your screen, it MUST be there - or it's just a bunch of letters, not a string, to C.

Spaces tabs and blanks will all have a value less than 'A', (hint, hint, hint).

:)

Adak 419 Nearly a Posting Virtuoso

Here's some important things to do:

1) This is predominately an English language board. Translate your program into English, and re-post it.

2) In the advanced edit window, highlight your code and click on the [code/b]/b word at the top of the edit window. That will make your program look like a program.

3) use good indentation. Just two to five spaces between levels of code, is a HUGE help to spot errors, quickly and easily. Tabs are not preferred, but one is OK.

4) delete the 'a' before your first include file, and where is your standard include files, like string.h or stdio.h and maybe stdlib.h?

We can help with your program, but my French is on holiday.

Adak 419 Nearly a Posting Virtuoso

What about using char ch = 'a'; and then ch++; 26 times?

char toCap = 'a';
toCap -= ('a' - 'A');

int integer = 0;
integer += 'a' for lowercase,

Now print it with a %c and with a %d :)

And what would it be to change an integer into uppercase?

Check out toupper() and tolower(), as well.