D33wakar 36 Posting Whiz in Training

Similar to echoserver, but this one handles multiple clients by forking the process.

D33wakar 36 Posting Whiz in Training

This is a simple echo server that I've written while learning sockets programming.
Compile the server and run it. You can connect to it using telnet like this:

telnet localhost 1337

Disconnect the client by typing "/quit" without quotes.

D33wakar 36 Posting Whiz in Training

You are doing strange chain of action from init return through each methods return, which is very bizare for me. why not just do the sequence of calls in main program?

This is the same program without the class.

#!/usr/bin/env python

import random 
import cPickle

#path of the dump file
filepath = '/home/deewakar/python/hangman/wordsdict.pkl'

#inset some random hints for the player
def insert_hints(length, keylist, secret_word):
    randint = random.randint
    #if the word contains 7 or more letters, you'll get 3 hints
    if length >= 7: hints = 3
    else: hints = 1
    for x in xrange(hints):
        a = randint(1, length - 1)
        keylist[a-1] = secret_word[a-1]

    return hints, keylist

def test_input(guess, secret_word, keylist, mistakes, used_keys ):
    #if the guessed letter matches
    if guess in secret_word:
        indexes = [i for i, item in enumerate(secret_word) if item == guess]
        for index in indexes:
            keylist[index] = guess
            used_keys.append(guess)

    #if the guessed letter didn't match
    else:
        used_keys.append(guess)
        mistakes += 1
    print "used letters ",set(used_keys),'\n'


    return keylist, mistakes


#load the pickled word dictionary
def load_dict():
    try :
        dumpfile = open(filepath, "r")
    except IOError:
        print "Couldn't open the dictionary file 'wordsdict.pkl'"
        quit()

    dictionary = cPickle.load(dumpfile)
    words = dictionary.keys()
    return dumpfile, dictionary, words

#randomly choose a word for the challenge
def prepare_word(words):
    secret_word = random.choice(words)
    #don't count trailing spaces
    length = len(secret_word.rstrip())
    keylist = ['_' for x in xrange(length)]
    hints, keylist = insert_hints(length, keylist, secret_word)
    return secret_word, keylist, hints

#display the challenge
def ask(keylist, secret_word, dictionary):
    print ' '.join(keylist), ":", dictionary[secret_word] 

#take input from the player
def …
D33wakar 36 Posting Whiz in Training

Without the picled dictionary I can not run the program so that is how far I can comment now (zipped and attached File would help).

That was a serious mistake on my part.

D33wakar 36 Posting Whiz in Training

This is a simple hangman game that I wrote using my beginner python skills. Though this game is playable, there must be lots of things I must've been doing wrong or the methods I'm using here may be not so pythonic. So I want some suggestions on how to improve this game.
The 'wordsdict.pkl' file contains a pickled dict with words as keys and meanings as their values.

e.g. {'word': 'its meaning'}
D33wakar 36 Posting Whiz in Training

And here's how you use strtok (you know... for future references).

#include <stdio.h>
#include <string.h>
int main(void){
    char line[20] = "Process0 12 1"; // suppose this is the first line read by fgets
    char* delim=" ";
    char* result = NULL;
    result=strtok(line,delim);
    if(result != NULL)
        printf("process:%s\n",result);//store process in an array
    result=strtok(NULL,delim);//first argument NULL except first call to strtok
    printf("quanta:%s\n",result);//store quanta in another array,you can use atoi to change
                                 //quanta to integer type

    result=strtok(NULL,delim);//first argument NULL except first call to strtok
    printf("priority:%s\n",result);//store priority in another array
return 0;
}
D33wakar 36 Posting Whiz in Training

If you want to use s, write

s = [x for x in s if x!= 'r']
# or
s = list(x for x in s if x!= 'r')

there is a small difference with s[:] because this code create a new list for the name s. With s[:] it only fills the same list object with new elements. For example try this

a = ['b','a','r','r','i','s','t','e','r']
b = a
c = a
b = [x for x in b if x != 'r']
print a
c[:] = [x for x in c if x != 'r']
print a

print id(a), id(b), id(c)

If you want to learn more about generator expressions, read about generators and the iterator protocol in the python documentation, but you can postpone this a little if you are new to python.

Thanks for the quick reply, I really appreciate it.

D33wakar 36 Posting Whiz in Training

Conclusion: don't modify the size of a list while iterating on this list, use a copy if necessary.

yes using a copy solves the problem thank you but I have couple of questions about the second method.
If I understood correctly

s[:] = (x for x in s if x != 'r')

means reconstruct the list s from the components of the list s itself (interating through them ) but skip the element 'r' right?
Also why can't we use just s instead of s[:].

s=(x for x in s if x!= 'r')
>>> s
<generator object <genexpr> at 0xa80ff54>
D33wakar 36 Posting Whiz in Training

If there's a list like below

s=['b','a','r','r','i','s','t','e','r']

and if I tried to remove every 'r' from the list like this

>>> for x in s:
    if(x=='r'):
        s.remove(x)

it gives the following result.

>>> s
['b', 'a', 'i', 's', 't', 'e', 'r']

Why isn't the last 'r' removed from the list.

D33wakar 36 Posting Whiz in Training

The program runs and compiles. When I enter the two words, it gives me a bunch of random stuff when printing

That's because scanf is not used like this

scanf(x1,x2,MAXFORTHIS,stdin);

click here

D33wakar 36 Posting Whiz in Training
#include <stdio.h>
#include <string.h>

int main()
{
    int count = 0;
    char *doc;
    FILE *inp;
    
    printf("Enter the file name: ");
    scanf("%s", doc);
    
    inp=fopen(doc, "r");
    
    while((doc = fgetc(doc)) != EOF)
    {
        if (doc == ' ')
            count++;
    }

    fclose(doc);
    
    printf("%s contains %d words\n",doc,count);
    
    return 0;
}

So basically I'm a little bit confused. I believe the logic of my program is correct; file pointer is declared, and I do have a character to store my array, it reads the file, and counts all the words pending a space in front/between/etc. Basically the program should ask the used the used to input the name of the file they're scanning. The file opens and goes through the program and outputs a line that tells the user the # of words in the file that was inputted.

My problem has been compiling it.

I'm getting this:

wordcount.c: In function ‘main’:
wordcount.c:13:5: warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast [enabled by default]
/usr/include/stdio.h:271:14: note: expected ‘const char * __restrict__’ but argument is of type ‘char’
wordcount.c:15:5: warning: passing argument 1 of ‘fgetc’ makes pointer from integer without a cast [enabled by default]
/usr/include/stdio.h:535:12: note: expected ‘struct FILE *’ but argument is of type ‘char’
wordcount.c:21:5: warning: passing argument 1 of ‘fclose’ makes pointer from integer without a cast [enabled by default]
/usr/include/stdio.h:236:12: note: expected ‘struct FILE *’ but argument is of type ‘char’

The root of all problems in your program is this …

D33wakar 36 Posting Whiz in Training

anyone can tell me what this line does?

clearly, it's returning the uppercase of the character given to the function.The first return statement only works if the condition cl>='a'(i.e.97 in decimal) AND cl<='z'(i.e 122 in decimal).If it does so then the second return statement is not executed, but if it does not then the second return statement is executed and returns whatever character was given to the function.So if you give any upper case characters or symbols then they will be returned unchanged.But if you give any lower case characters, let's suppose 'b'
then this line

return ('A' + c1 - 'a');

looks like this

return (65+98-97);
//or
return(0x41+0x62-0x61);

this ascii table might help you further.
have a lovely day!

D33wakar 36 Posting Whiz in Training

The case choices does not run after the input of the integers 0 or 1.

You're missing '&'before 'choice' in your 'scanf' statement .

scanf("%d",&choice);

and another(important!) thing,look at this

int number, integer,choice;
int ArrayN[20];
 
for(i=0;i<20;i++)
{
printf("Enter 20 Integers\n");
scanf("%d", &number);
printf("ArrayN[%d]=%d\n",i,number);//well, that's stupid!
}

You have to assign values to the array

scanf("%d",&Array[i]);//like this
// ..or like this
Array[i]=number

Good Luck! with the rest of the code for searching and all that.

D33wakar 36 Posting Whiz in Training

Can you tell me why use size_t and not int for orig_len and rep_len?

Using size_t instead of just plain int or unsigned int makes your code more portable since the size of int types vary across platforms.
Also the above standard functions expect their third argument to be of size_t type.

char *stpncpy(char *restrict s1, const char *restrict s2, size_t n);
int strncmp(const char *s1, const char *s2, size_t n);
D33wakar 36 Posting Whiz in Training

First of all, use code tags whenever you post any code.See that CODE thingy, click that and paste your well formatted code in between.

There's no use of this #include<conio.h>in your code and why this char studentanswer[30][30+1]; why not just declare it like this

char studentanswer[30][31];

Since you're opening the file 'examdat.txt' for reading, make sure that it is in the same directory as your program is or use the full path.

int status = fgetAnswers(&numberofstudent, ans, inp); You are passing arguments without assigning any values to them.

D33wakar 36 Posting Whiz in Training
fflush(stdin);

Didn't you read my previous post ? How many times do I have to tell you that you should not use fflush() with stdin.In the c standards, it is only defined to use with the output streams.

I have another problem with the following program I have tried which tests if sides form a right angled triangle or not.

First of all, if you have another problem and the current problem is resolved then you should mark this thread URL="http://www.daniweb.com/community-center/daniweb-community-feedback/threads/226710"]"solved"[/URL] and open another thread with the new problem.

First of all, is there any unnecessary repetition?

Actually, that's your job to figure it out since you know your level of expertise and how compact you need your program to be.You can use functions to make it more short and compact.

Is there any simple way by which I can add a reply feature to the program?

That is as simple as you can get.

if(Condition)
    printf("Something");
else
    printf("something else");
D33wakar 36 Posting Whiz in Training

oh I get the point then. So, in other words it fflush can be used instead of always creating a double getchar() in the end of each prog.

No, you don't. I've already said that fflush() should not be used with input streams, it is made to use with output streams only.People usually use getchar() at the end to consume the data that might be left in the input buffer. That could be replaced with this

while (((ch = getchar()) != '\n') && (ch != EOF))//has no body ;

But still at least a character is left in the buffer.

D33wakar 36 Posting Whiz in Training

I see where Diwakar has made several test submissions. Any new idea's you're trying, Diwakar?

No, I just couldn't believe it was showing "time limit exceeded " for the code I submitted.But yes,I tweaked it a little bit,didn't help much.I replaced the multiplications with bit shifts, did a little work to reduce the redundancy during marking off composites and printed the primes at a tab distance rather than one at each line.

void sive(int size) {
    int i,j,k,l;
    char *sieve = calloc(size, 1);
    for (i=2,k=1,l=2; i*i <= size; i=(k<<1)+1,k++,l=i<<1) {
               if (!sieve[i]) {
                       for(j = i*i; j < size; j+=l) {sieve[j]=1; }
               }
     }
    for (i=2,j=0; i<size; i++) {
        if (!sieve[i]) { sieve[j++]=i; }
       }


  free(sieve);
}

But I'm not out of ideas yet.You may have seen guys mentioning Segmented sieve in the forum there.I haven't understood the concept thoroughly, though I have read about it couple of times but you know all those mathematical symbols drive me nuts.I remember someone wrote on one of the other forums that you first produce a list of primes within a small range and use those primes intelligently to produce other larger primes.Hmm, what does that mean?
And also about the Sieve of Eratosthenes, We're now using a whole integer (of the 'sieve' array) to represent a bit that marks composite, instead can we use just a single bit to represent that.
Once, I was very fascinated by the Wheel Factorization, later I came to know that the …

D33wakar 36 Posting Whiz in Training

Am i correct if I understand I/O buffer
as the temporary memory stored/inputted in the variables?

see here.

.but what is its use here?

Just to make sure that everything in the buffer is written immediately after you call printf and not after sometimes when you're taking inputs from the user. Believe me it happens(or may not,it depends on the compiler you're using or the system you're running on), usually when you're trying to take inputs and give outputs subsequently.This happens because buffers are flushed out only when they're full or a newline is encountered or fflush() is called.

D33wakar 36 Posting Whiz in Training

This is a piece of code from some book.

Is that the same book Narue told you to burn ?

int fun (const union employee *e);
union employee
{
char name[15];
int age;
float salary;
};

You should declare the union first and then the function 'fun'.

union employee{
char name[15];
int age;
float salary;
};
int fun (const union employee* );//in function prototypes, you only mention the argument type
void main()//so wrong

According to the standards, main() returns an int type

int main(void)

but this code is running on turbo C giving just a error message of const to * conversion ????? please tell me whether this code is right ??????

How could that be?If the compiler issues an error message then the code should not have compiled in the first place.And yes the code is wrong!If you have used 'const' Type qualifiers then that means that you're declaring them as constants and they should not be modified during runtime.
Quote drom c-faq.com

A const value is one you promise not to modify. The compiler may therefore be able to make certain optimizations, such as placing a const-qualified variable in read-only memory. However, a const-qualified variable is not a true constant; that is, it does not qualify as a constant expression which C requires in certain situations, such as array dimensions, case labels (see section 18.3.1 below), and initializers for variables with static duration (globals and static locals).

Quote from …

D33wakar 36 Posting Whiz in Training

'fflush(stdout)' forces the data (if any)in the I/O buffer to be written to the screen .Including a '\n' character(if suitable) in the 'printf' itself also does the same thing.

printf("incorrect value\n");

Remember that fflush is only used with output streams.Calling fflush with NULL argument flushes all the opened streams.

D33wakar 36 Posting Whiz in Training

Every call to printf() incurs a small expense, because printf() can decode a boatload of formats, etc.

Yeah,I couldn't agree with you more.

Second topic:

Just an idea, completely untested.

What if we took in ALL the queries from the tester, into an array, and quickly sorted them (time: maybe 0.2-1.0 seconds). Then we start the prime finding loop, and as soon as we find one, (in Sieve loop), that matches the next request, we print it solo, just that one number and newline.***

Now we're talking! That's a brilliant idea. I wondered, why would you need the number of queries in the input at first, since you're given all the numbers for which you have to find the primes for.Now I know, you're supposed to use that in your code, it's like a hint right?

Maybe print out 512 numbers with each call to printf()?

Hmm, interesting!

@Diwakar, I inserted part of your sieve loop (the nested for loop at the bottom of it), and found I wasn't getting all the prime numbers - lots of them, but not all. You may want to check it (but it could be just the interaction between my loop logic, and yours, in the top half of the larger loop).

It may be possible since i haven't tested it for all five million! But until now it has been giving correct answers.I'll check that and inform you later.
By the way, your quicksort looks fast, I'll give that a try too.

D33wakar 36 Posting Whiz in Training

I guess it just adds ret statement and pops whatever is in the eax register.

Sorry, there was a typo in the above line. I mean,pops whatever is in the stack to the eax register(i.e.last pushed value).

D33wakar 36 Posting Whiz in Training

I guess it just adds ret statement and pops whatever is in the eax register.

D33wakar 36 Posting Whiz in Training

Then why it is not giving any warning with

gcc -o test_cal test_cal.c

Well that's not mine (or gcc's) problem, it's your job to follow good programming practices.

D33wakar 36 Posting Whiz in Training

The answer is in your error message

cc1: warnings being treated as errors
test_cal.c: In function ‘calsum’:
test_cal.c:20: error: control reaches end of non-void function

Since function calsum is non-void(means returns something), so you should add a return statement.

return d;
D33wakar 36 Posting Whiz in Training

It's a very , very messy code.Here are few things that I saw, that could be potentially causing the problem.
1.You have named many things "Information".First the struct for book data

/*Structure for book information */
typedef struct Information
{
char subject [MAXIMUM_TITLE];
char author [MAXIMUM_AUTHOR];
int edition;
int year;
float price;
} Book;

and then this

static Book *Information;

I don't know what's that for.And finally a pointer to Book to use with malloc.

Information = (Book *) malloc(book_number * sizeof(Information));

2.you are allocating space dynamically for a pointer variable.

Information = (Book *) malloc(book_number * sizeof(Information));

should be replaced with this:

Information = (Book *) malloc(book_number * sizeof(Book));

I guess, you have to replace all the 'Information's with 'Book's in the code that follows.
3.At least the code should be syntactically correct, then it will be easy to find the bugs that aren't caught by the compiler. for e.g. see this declaration

Book getBookInformation(int inventory);//if returns nothing, return 'void'

But see the definition of the function 'getBookInformation', it returns nothing.
I hope above things will help you fix your code,and in addition don't ignore compiler warning messages, they could be very helpful while debugging your code.
P.S. may be compiling them as a single source at first, may be less tiresome and less time consuming and then you can distribute them in multiple files afterwards.

D33wakar 36 Posting Whiz in Training

CSE, do you submit code or is it an executable file that gets tested?

No,you just have to submit your code.
I compiled and ran your both programs and it took about 16 seconds for the version with direct numbers and about 13 seconds for the version with char array( intel core 2 duo, 2.22 GHz).The chars version was not accepted by my ide, so I had to build it in the command line.
Then I submitted the program I was working on( after editing a little bit),

#include <stdio.h>
#include <stdlib.h>

#define SIZE 86028122
int arr[5000000]={0};

void sieve(int size) {
       int i,j,k;
       char *sieve = calloc(size, 1);
       for (i=2,k=1; i*i <= size; i=k*2+1,k++) {
               if (!sieve[i]) {
                       for(j = i*i; j < size; j=j+i) {sieve[j]=1; }
               }
       }
       for (i=2,j=0; i<size; i++) {
           if (!sieve[i]) { arr[j++]=i; }
       }


       free(sieve);
}
int main(void) {
	
    sieve(SIZE);

	char number[15],*file=NULL;
	int n,flag=0;
	while((file = fgets(number,sizeof(number),stdin)) !=NULL && flag!=1){
		n=atoi(number);
		if(!flag){
			flag=n;continue;}


		 printf("%d\n",arr[n-1]);
		 flag--;

	}
	

       return 0;
}

I submitted it because, it was taking about 4.79 seconds on my PC and only 2.26 seconds on ideone which the site recommends to test your code.But it shows time limit exceeded whenever I submit it to the site itself.Frustrating, isn't it?

2)Take 1 as test case it will not take any input.
that's why its giving wrong answer.

But I was reading the input from a file, otherwise how else would you give this kind of input:

D33wakar 36 Posting Whiz in Training

The code compiles

That totally amazes me.

but when I run the program it stops responding once it enters the while loop

So there's a strong possibility that the problem lies on your while loop statement.

while (fgetc(inFile) != EOF) != NULL) {

'fgetc' returns EOF when read error occurs or the EOF is reached.So this is enough

while(fgetc(inFile)!=EOF)

But wait a minute, the file pointer you declared has a name 'inputFile'.Also that you're using fgetc just to detect the EOF seems a bad idea to me.Instead just read the whole line at a time and extract the information you need one by one.

D33wakar 36 Posting Whiz in Training

Alright guys, I registered in to that site and submitted the following code, but it didn't accept the code as a valid answer.The time taken by the code I submitted was 1.23 as shown in the site.

#include <stdio.h>
#include <stdlib.h>
#define SIZE 50000000
int arr[SIZE]={0};

void sieve(int size) {
       int i,j,k;
       char *sieve = calloc(size, 1);
       for (i=2,k=1; i*i <= size; i=k*2+1,k++) {
               if (!sieve[i]) {
                       for(j = i*i; j < size; j=j+i) {sieve[j]=1; }
               }
       }
       for (i=2,j=0,k=1; i<size; i++) {

       if (!sieve[i]) { arr[j++]=i; }
       }
       free(sieve);
}
int main() {

    sieve(SIZE);

	char number[15],*file;
	int n,flag=0;
	while((file = fgets(number,sizeof(number),stdin)) !=NULL && flag!=1){
		n=atoi(number);
		if(!flag){
			flag=n;continue;}


		 printf("%d\n",arr[n-1]);
		 flag--;

	}

       return 0;
}

That means my interpretation of the challenge was wrong.But what else could it be?

D33wakar 36 Posting Whiz in Training

Yeah, I'm wondering about the 10 seconds, handling 50K queries? This may not have anything to do with generating primes at all, but be about efficient bit packing and probing to get the answers.

Yeah I think so, 'cause the time taken to generate the primes(up to 50000000)and store them in an array is taking a lot less(less than 4 seconds with the program I'm working on), but displaying them all will take a lot of time.I guess the same is with the cse's code.What about your 'Sieve of Atkin'? So according to the challenge,

The problem statement is really simple. There are some queries. You are to give the answers.
Input

An integer stating the number of queries Q(equal to 50000), and Q lines follow, each containing one integer K between 1 and 5000000 inclusive.
Output Q lines with the answer of each query: the Kth prime number.
Example

Input:
8
1
10
100
1000
10000
100000
1000000

Output:
2
29
541
7919
104729
1299709
15485863

We have to display only those primes which are in the query. Is that the correct interpretation of the challenge?

Why are Zombies so creepy?

They aren't! I think they are nice creatures just longing for human flesh and often forget to brush their teeth.And aw there little walk, so cute!

D33wakar 36 Posting Whiz in Training

I studied the fast program that Diwakar linked to and any optimizations are easily made.

In that particular program, I changed the following line:

for (i=2; i*i <= size; i++) {

to

int k;
for (i=2,k=1; i*i <= size; i=k*2+1,k++)

so that 'i' would only be an odd value(ignoring all evens), but it didn't affect the prime generation time much.So, I guess that wouldn't be an optimization(as the definition goes).Also I'm thinking, in the second loop statement

for(j = i+i; j < size; j+=i)

how about initializing as 'j=i*i' .
And also ignoring multiples of previous values of i.

for e.g. 
when i=2,j becomes4,6,8,10,12,14,16,18...< size
when i=3,j becomes 6,9,12,15,18,21,24...<size
when i=5,j become 10,15,20,25,30,35,40,45..<size
when i=7,j becomes 14,21,28,35,42,56...<size
Did you see the redundancy? I have not yet figured out how to solve that, but will that make a difference in the speed of the program?

What were your optimizations on that code Adak?

D33wakar 36 Posting Whiz in Training

I ran it and it showed the very same result as was printed in the book.

Which compiler are you using?

But I am not able to find the logic.

me too.

D33wakar 36 Posting Whiz in Training
BYTE PTR [BX+SI]

What does this do exactly though?

Si is an index register, though in the above code SI always remains zero since you had only one character (to access) in the string.While using instructions like CMP and ADD, you need to use the pointer directive 'BYTE PTR' to tell the assembler that the pointer contains a 8-bit value(or you want to access a byte). Similarly, there are other directives like 'WORD PTR','DWORD PTR' etc.So the above code is equivalent to

char *ptr="A";//BX points to the character in the buffer just like ptr here
int i=0;//SI is similar to this i
printf("%c\n",*(ptr+i));//prints the character
D33wakar 36 Posting Whiz in Training

Tell me why the compare always goes to my error message please.

See line 42 in your code.

LEA	    AX, DATASTR ;Move the character into the AX register

It is actually copying the offset address of 'DATASTR' to AX, not the character itself.Instead do like this:

LEA	    BX,DATASTR ;load the addr of character into the BX register
MOV         SI,0       ;SI=0
CMP	   BYTE PTR [BX+SI],'A'	;Compare the character to 'A'
JB	    ERRORMSG	;If the character is below 'A' then go to error message
CMP	    BYTE PTR[BX+SI],'a'	;Compare the input character to lowercase 'a'
JB	    TESTCAPITAL	;Jump below if the character is less than 'a'

Here, BX is used to load the offset address, because it's the only general purpose register allowed to do so in real mode assembly.
Similarly, your 'TESTCAPITAL' will look like this:

TESTCAPITAL:
CMP	    BYTE PTR [BX+SI],'Z';Compare the input character to uppercase 'Z'
JA	    ERRORMSG	;If the character is in the no-man-land part of the chart, display error.
JB	    CONLOW      ;If it's between capital 'A' and 'Z' then convert to lower!

and your CONLOW

CONLOW:
ADD	    BYTE PTR[BX+SI], 20H;CONVERT from upper to lowercase!
mov         AH,06h              ;DOS function to print a character
mov	    DL,[BX+SI]          ;Print the character
INT	    21H

If you want to use

MOV AH,09H
LEA DX,DATASTR
INT 21H

then, you have to setup your buffer like this:

MAX DB 2 ;maximum input length
ACTUAL DB ?
DATASTR DB 1 DUP(' ') ;size is inputlength+2
        DB '$'        ;end of string(required to use AH=09H function)

Do that and …

D33wakar 36 Posting Whiz in Training

What the ..? I mean, How the ...?

can anyone please tell me whats actually happening in this code.
Seems to be as if incremented pointer is pointing to the next bit of same int.

Why don't you try it in your compiler.did you?

Answer is 2,0

So you did try it and it actually compiled and ran?

D33wakar 36 Posting Whiz in Training

no. it is not the expression is wrong. but the program enter the input itself. blank input. and it direct tell to input the correct answer before i get to input anything.

This is a very common problem.I hope this will make things clear. If not, try to Google it yourself.

D33wakar 36 Posting Whiz in Training

you forgot to use '&' in your scanf statement.

scanf("%d",&n);

but what's the point of this

for(m=1;m<n;m++)
for(t=1;t<=m;t++)
{
n=m*t;
printf("%d,%d",m,n);
}
D33wakar 36 Posting Whiz in Training

We have to use other testing for primality, and I believe cse.avinash has explored using the Sieve of Eratosthenes, which I take it were also unsuccessful.

You guys should take a look at this.The second one is much more powerful than the first one(I'm totally amazed by the results).

D33wakar 36 Posting Whiz in Training

Would I loop until the user presses the enter key with no input?

I'm assuming that your program takes in a character(a-z or A-Z) and displays a character as output(and your c++ sample is doing the same thing). Here's the pseudocode(well.., kind of.)

-take user input
-if input==10(i.e.'\n'), then exit the program.
-if 65 <= input <= 90 then change it to lower case and print it and then jump back to take another input
-if 97<= input >= 122 then change it to upper case and print it and then jump back to take another input
-else then print the warning message, and again loopback to take the input.

The ascii table might come in handy.

How would I test that condition using the proper syntax?

here's an example :

mov ah,8 ;dos function to get a character, the character is stored in 'al'
int 21h  ;most important interrupt in dos,executes a system call to perform the above function
cmp al,10d  ; check if user pressed <enter> key
je warning  ;then print the warning message
;je means 'jump if equal' and 'warning is a label'

Here's the intel x86 jmp instruction reference for you.

D33wakar 36 Posting Whiz in Training

just use

char* bus
char* dest
.../*and later*/
bus="single-decker"
dest="taiping"
D33wakar 36 Posting Whiz in Training

Now, if anyone would be willing to assist me I would greatly appreciate it!

I don't know what you need help with, since you have it all figured out.If you want us to write(or translate) your code for you, the forum rules wouldn't allow it.

You have to use software interrupts to get input from keyboard and to print output to the screen. See Ralph Brown's Interrupt List.
Do some research on how to do your assignment and write your code.Post your code here even if it's broken, we'll help you to fix it.
Cheers and happy coding!

D33wakar 36 Posting Whiz in Training
for(c_5=1; c_5<=10;c_5++)
          {
            for(c_6=c_5;c_6>=1;c_6--)
              printf(" ");
              for(c_6=10;c_6>=c_5;c_6--)
             printf("*");
             printf("\n");
            }
            printf("\n");
          getch();

initialize c_5 to 0 instead of 1.

for(c_5=0; c_5<=10;c_5++)
D33wakar 36 Posting Whiz in Training

.for some reason sorting resets all entries to blank.Why is it doing that? I compare two entries, swap if necessary. Trying to figure out where that's failing.

I compiled and ran your program, It works fine.
In my opinion, in your 'DeleteEntry' function, try matching only the user's phone number, because even if I entered a correct firstname with incorrect surname(which is not in the phonebook), then the entry for which the first name matched will be deleted.As there may be some users whose surname or firstname or both matches with each other.But that's only my opinion.

D33wakar 36 Posting Whiz in Training
fflush(stdin); //clear the buffer???!

Don't use 'fflush' with 'stdin' ,see why.also thismight be helpful.
Either use getchar after each call to scanf to discard the '\n' from the input buffer or don't use scanf at all.There are other solutions for interactive inputs.

D33wakar 36 Posting Whiz in Training
int main( int argc, char **argv[] ) {//Wrong
int main( int argc, char *argv[] ) {//right
D33wakar 36 Posting Whiz in Training

If you're using the variable val just to do this:

mov [val], ax
add si,val

then there's no need to do so,just do it directly

add si,ax

It's quite difficult to understand what you're trying to do, the information provided here is too little(not enough) and as far as your sample code is concerned, syntactically it's fine.
Here's an example, I hope this will help .
suppose there's a string defined as

string    db "ABCDEFGH",'$'

and it's characters can be accessed like this

mov bx,offset string
mov al,[bx+si];al = "A"
add si,02
mov al,[bx+si];al="C"

or like this

mov al,[string+si];al="A"
add si,02
mov al,[string+si];al="C"
D33wakar 36 Posting Whiz in Training

It shows the same prompt multiple times

That's because the 'printf' statement is inside the loop and you don't need to pass that 'i'.You can do like this:

int main (void)//this is more readable, isn't it?
{
    int n, smallest=0, i=0;
    printf ("Enter a list of positive integars:\n");//printf outside the loop
    while (scanf("%d", &n)!=EOF){//press ctrl+Z to break out of the loop
		if(n==-1)
		    break;
		if (n<=smallest)
		    smallest=n;
		i++;
	}

	printf("The smallest among the %d integars is %d.\n ",i,smallest);

	return (0);

}
D33wakar 36 Posting Whiz in Training

I was playing with the code provided by 'hkdani' and the mere idea that 'stdin' uses a char pointer '_ptr' to point to the data in the buffer, I tried to compile the following code(just for fun, cause it's been itching me):

#include <stdio.h>
#include <string.h>
int main(void)
{
    FILE *pFile ;
    int i;
	char name[5];

    pFile = stdin ;
    i = strlen (pFile->_ptr) ;//_ptr is char buffer in struct _iobuf
    printf("%d bytes in stdin\n",i) ;
	printf("enter your name\n");
    scanf("%5[1234]",&name);

   while((i = strlen (pFile->_ptr))>=1){
	   printf("%d bytes in stdin\n",i) ;
	   if(i==1)//atleast 1 character needed for getchar
		   break;
	   printf("removing \'%c\' from the buffer\n",getchar());

	}


    return 0 ;
}

first shows

0 bytes in stdin
enter your name

input:

rakawid

after pressing enter shows:

9 bytes in stdin
removing 'r' from the buffer
8 bytes in stdin
removing 'a' from the buffer
7 bytes in stdin
removing 'k' from the buffer
6 bytes in stdin
removing 'a' from the buffer
5 bytes in stdin
removing 'w' from the buffer
4 bytes in stdin
removing 'i' from the buffer
3 bytes in stdin
removing 'd' from the buffer
2 bytes in stdin
removing '
' from the buffer
1 bytes in stdin

"9 bytes in stdin", what's that extra byte? does anyone know?

vedro-compota commented: +++ +3
hkdani commented: A willing and inquisitive mind that probes the depths to add knowledge. Gems of wisdom will be gleaned from this source. +6
D33wakar 36 Posting Whiz in Training
void print_triangle_info(int area(), int perimeter());
void print_square_info(int area(), int perimeter());

Are 'area' and 'perimeter' functions? If not, why give parentheses after them.the correct form of prototyping will be:

void print_triangle_info(int, int);
void print_square_info(int,int);//takes two integers as arguments and return nothing(void)

and then their definitions

void print_triangle_info(int area, int perimeter) {//no parentheses after area and perimeter
//Now make use of the area and perimeter to print "triangle info"
}

and then call them from 'main'

int main(void) {
//calculate area and perimeter here or create functions to calculate them outside the 'main'

print_triangle_info(area, perimeter);
print_square_info(area, perimeter);
}

edit:
@ WaltP- Wow, that was quick!

minimi commented: Thank you for the heads up! +2