C programming output specifications for counting answers - c

I'm taking a basic programming class and we can do practice programs as we go to better ourselves. Right now, I'm trying to write a program that uses a while loop to ask for inputs from a user then the program decides if those inputs meets a certain value or not. The trouble I'm having with is the output.
For example, "You have met this certain number X times out of Y times."
What do you use to keep track of how many inputs was put in and how many met the criteria?

Typically you'd use a pair of int variables for that. Initialize both to zero, then increment one each time through the loop that reads the input (so it counts how many inputs there were), and increment the other within an if statement that checks whether the input meets the criteria (so it counts how many inputs met the criteria). At the end of the loop, the two variables hold the numbers that you want to print.

Related

constructing a non deterministic turing machine

Draw the diagram of a two tape Non deterministic Turing Machine M that decides the language
L={w∈Σ* | w=uuu ∈Σ* }
if i could get help explaining the steps how to construct the NDTM (linguistically), I believe I could draw the diagram but I couldnt come out with an answer..
thank you
By u*u*u (viewed in the edit history), I presume what you intend is the language of all words of the form u^3 (u repeated three times) where u is any string over the alphabet.
Our NDTM needs to accept strings in the language in at least one way, and it must never accept anything not in the language. In particular, the key is that an NDTM can reject strings in the language, as long as some path through the NDTM does accept every string in the language.
Given that, our first step can be do guess about the length of u. The NDTM can mark three tape symbols (say, by writing versions of the symbols that are underlined) by nondeterministically transitioning from state q0 to q1 then q2 at arbitrary points while scanning right. Then, we can reset the tape head and use a deterministic TM to answer the question: did the split we guessed in the first step result in a string of the form u^3?
This is deterministic since we know the delineation of parts. We can check the first two parts (say, by bouncing back ad forth and marking symbols we've already processed), and then the second two parts (using the same technique, but applied to the 2nd and 3rd parts).
We have reduced the problem to that of checking whether a string is of the form w|w where we know the split. This deterministic TM is easier to come up with. When we put it after the NDTM that guesses about how to split up the initial input, we get a NDTM that can (and for exactly one guess, does) accept any string of the form u^3, but cannot possibly accept anything else. This is what we were after and we are done.

Is printing a char* faster than printing a char one at a time?

I have to write a simple program in C that prints to the standard output triangle with two equal edges for given number n. Meaning that for n=3 the output would be:
x
xx
xxx
Now I'm supposed to do two version of this program:
1. Memory conservative.
2. Time conservative.
Now I'm not entirely sure, but I think that the first version would just print x one at a time, and the second would expand the char table one at a time and then print it.
But is printing a char* faster than printing multiple single chars?
You may not be able to observe but building the entire string in memory and then printing it at once is definitely faster in theory. Reason being you will be making less calls to printf function. Each time you call a function there are multiple things that happen in the background like pushing all the current method variables and current location to stack and popping them back after returning.
However as I mentioned you may not be able to observe this difference for smaller inputs because the time needed for each of these operations are small unless you use a computer from 1960s.

Problems to solve using control instructions in C for practice

Need some good problems which students can think of and apply their own logic to solve them using control instructions only. The topics covered until now are basic, not even arrays are done yet. But, I want students to be perfect before proceeding to higher topics.
I tried searching for some example problems, none were as I expected / they were the ones which I already knew.
Some of which I know:
Write a program to find out the value of a^b without using built in functions.
Write a program to find out Armstrong numbers between a range.
Write a program to print binary equivalent of a number in reverse order (since arrays are not yet done, just simple logic to print the remainder and divide the number further)
Count all -ve, +ve and 0 numbers entered by user until user wishes to terminate the program.
Write a program to display all divisors of a given number.
Write a program to find if the given number is prime or not.
Check if the given number is odd or even.
Need more good logically interesting problems which would help students to build their problem solving capability.
Thanks.
PS: Please forgive me if this question is vague or not to the point coz this question has scope for vast answers and I cannot accept a single answer, I guess?
Check if number is a palindrome (1234554321)
Rewrite a function using write() to print a number in the console (similar to printf("%d", ...))
A function that writes all combinations of 2 digits starting from 12 to 89, not allowing twice the same digit, nor a different order (12, 13, ..., 19, 23, 24... : skipping 21 because it's done with 12)
A function that write all combinations of n digits (n given as a parameter from 1 to 9) with the same rules (without using arrays)
Print first 33 terms of Fibonacci-Series
Write factorial of n being input from keyboard on console.
Find hours,minutes,seconds from given seconds.(305 s = 5m + 5s ....)
Calculate dot-product and cross-product of two 2D vectors.
Find the intersecting point of two lines(m=slope, (x0,y0)=a point for each line)
Calculate sin(pi/4) with using series expansion
Print the minimum of values given from keyboard on screen.
Simulate **and** , **or** and **xor** gates.
Find projection of a vector(3D) on another vector.
Find area of a polygon(2D)
Calculate the integral of x-square between x=0 and x=3 using integration by trapezoidal rule
Find roots of: (x-square) plus (two times x) plus (one) equals (zero)

What should my program do when it sees an integer overflow that does not affect the program run?

There is a small program which takes input from users on a prompt. It takes predefined inputs from the users and executes them.
It also displays a number with the prompt indicating the count of the commands :
myprompt 1) usercommand1
...
myprompt 2) usercommand2
...
...
myprompt 3)
I do not expect the user to give more than 65535 commands at a time, so the count is stored as an unsigned short data.
Problem:
I am not sure how the program should handle the case when the user actually crosses this limit of the number of commands. Should I let the count to roll over to 0 (and keep looping) or to stay put at 65535?
I want the program to still function normally, as in take user inputs and process them just as before. Also, the value of count has no effect at all on the command execution.
I looks like you're tackling a problem that might never occur.
Let's assume your users are quite fast, and it takes them 10 seconds to input a command line. Rollover would happen after 655350 seconds, i.e. approximately seven and a half days.
Let the counter roll over. If that still troubles you, then take the high path and make it an unsigned long. Then it will only roll over after 1361 years (on 32-bit machines).
If you ask yourself this question it means you should go the easy way: make the counter an unsigned int.
How to handle the limit is very dependant on what this counter is used for. My feeling is that it is not used for any really interesting thing so your question is kind of moot. Whichever choice you make it will still work correctly.
On the other hand if this counter as some real use you should ask the user of this counter the correct way to proceed: both have some pros and cons (either counter going back in time or stalling) so your user risk being surprised.
You forgot to mention other alternatives: terminate your program. Or remove the limit and use some form of big integers (GMP lib for example) but this souns overkill.
Note that the DNS choose to wraparound the serial number at 2^32. This makes it usable forever. Users of the counter are supposed to detect the overflow. RFC 1982
To be honest this:
I want the program to still function
normally, as in take user inputs and
process them just as before. Also, the
value of count has no effect at all on
the command execution.
answers your own question, if it has no effect at all then just let it start on 0 again.

What is the Pumping Lemma in Layman's terms?

I saw this question, and was curious as to what the pumping lemma was (Wikipedia didn't help much).
I understand that it's basically a theoretical proof that must be true in order for a language to be in a certain class, but beyond that I don't really get it.
Anyone care to try to explain it at a fairly granular level in a way understandable by non mathematicians/comp sci doctorates?
The pumping lemma is a simple proof to show that a language is not regular, meaning that a Finite State Machine cannot be built for it. The canonical example is the language (a^n)(b^n). This is the simple language which is just any number of as, followed by the same number of bs. So the strings
ab
aabb
aaabbb
aaaabbbb
etc. are in the language, but
aab
bab
aaabbbbbb
etc. are not.
It's simple enough to build a FSM for these examples:
This one will work all the way up to n=4. The problem is that our language didn't put any constraint on n, and Finite State Machines have to be, well, finite. No matter how many states I add to this machine, someone can give me an input where n equals the number of states plus one and my machine will fail. So if there can be a machine built to read this language, there must be a loop somewhere in there to keep the number of states finite. With these loops added:
all of the strings in our language will be accepted, but there is a problem. After the first four as, the machine loses count of how many as have been input because it stays in the same state. That means that after four, I can add as many as as I want to the string, without adding any bs, and still get the same return value. This means that the strings:
aaaa(a*)bbbb
with (a*) representing any number of as, will all be accepted by the machine even though they obviously aren't all in the language. In this context, we would say that the part of the string (a*) can be pumped. The fact that the Finite State Machine is finite and n is not bounded, guarantees that any machine which accepts all strings in the language MUST have this property. The machine must loop at some point, and at the point that it loops the language can be pumped. Therefore no Finite State Machine can be built for this language, and the language is not regular.
Remember that Regular Expressions and Finite State Machines are equivalent, then replace a and b with opening and closing Html tags which can be embedded within each other, and you can see why it is not possible to use regular expressions to parse Html
It's a device intended to prove that a given language cannot be of a certain class.
Let's consider the language of balanced parentheses (meaning symbols '(' and ')', and including all strings that are balanced in the usual meaning, and none that aren't). We can use the pumping lemma to show this isn't regular.
(A language is a set of possible strings. A parser is some sort of mechanism we can use to see if a string is in the language, so it has to be able to tell the difference between a string in the language or a string outside the language. A language is "regular" (or "context-free" or "context-sensitive" or whatever) if there is a regular (or whatever) parser that can recognize it, distinguishing between strings in the language and strings not in the language.)
LFSR Consulting has provided a good description. We can draw a parser for a regular language as a finite collection of boxes and arrows, with the arrows representing characters and the boxes connecting them (acting as "states"). (If it's more complicated than that, it isn't a regular language.) If we can get a string longer than the number of boxes, it means we went through one box more than once. That means we had a loop, and we can go through the loop as many times as we want.
Therefore, for a regular language, if we can create an arbitrarily long string, we can divide it into xyz, where x is the characters we need to get to the start of the loop, y is the actual loop, and z is whatever we need to make the string valid after the loop. The important thing is that the total lengths of x and y are limited. After all, if the length is greater than the number of boxes, we've obviously gone through another box while doing this, and so there's a loop.
So, in our balanced language, we can start by writing any number of left parentheses. In particular, for any given parser, we can write more left parens than there are boxes, and so the parser can't tell how many left parens there are. Therefore, x is some amount of left parens, and this is fixed. y is also some number of left parens, and this can increase indefinitely. We can say that z is some number of right parens.
This means that we might have a string of 43 left parens and 43 right parens recognized by our parser, but the parser can't tell that from a string of 44 left parens and 43 right parens, which isn't in our language, so the parser can't parse our language.
Since any possible regular parser has a fixed number of boxes, we can always write more left parens than that, and by the pumping lemma we can then add more left parens in a way that the parser can't tell. Therefore, the balanced parenthesis language can't be parsed by a regular parser, and therefore isn't a regular expression.
Its a difficult thing to get in layman's terms, but basically regular expressions should have a non-empty substring within it that can be repeated as many times as you wish while the entire new word remains valid for the language.
In practice, pumping lemmas are not sufficient to PROVE a language correct, but rather as a way to do a proof by contradiction and show a language does not fit in the class of languages (Regular or Context-Free) by showing the pumping lemma does not work for it.
Basically, you have a definition of a language (like XML), which is a way to tell whether a given string of characters (a "word") is a member of that language or not.
The pumping lemma establishes a method by which you can pick a "word" from the language, and then apply some changes to it. The theorem states that if the language is regular, these changes should yield a "word" that is still from the same language. If the word you come up with isn't in the language, then the language could not have been regular in the first place.
The simple pumping lemma is the one for regular languages, which are the sets of strings described by finite automata, among other things. The main characteristic of a finite automation is that it only has a finite amount of memory, described by its states.
Now suppose you have a string, which is recognized by a finite automaton, and which is long enough to "exceed" the memory of the automation, i.e. in which states must repeat. Then there is a substring where the state of the automaton at the beginning of the substring is the same as the state at the end of the substring. Since reading the substring doesn't change the state it may be removed or duplicated an arbitrary number of times, without the automaton being the wiser. So these modified strings must also be accepted.
There is also a somewhat more complicated pumping lemma for context-free languages, where you can remove/insert what may intuitively be viewed as matching parentheses at two places in the string.
By definition regular languages are those recognized by a finite state automaton. Think of it as a labyrinth : states are rooms, transitions are one-way corridors between rooms, there's an initial room, and an exit (final) room. As the name 'finite state automaton' says, there is a finite number of rooms. Each time you travel along a corridor, you jot down the letter written on its wall. A word can be recognized if you can find a path from the initial to the final room, going through corridors labelled with its letters, in the correct order.
The pumping lemma says that there is a maximum length (the pumping length) for which you can wander through the labyrinth without ever going back to a room through which you have gone before. The idea is that since there are only so many distinct rooms you can walk in, past a certain point, you have to either exit the labyrinth or cross over your tracks. If you manage to walk a longer path than this pumping length in the labyrinth, then you are taking a detour : you are inserting a(t least one) cycle in your path that could be removed (if you want your crossing of the labyrinth to recognize a smaller word) or repeated (pumped) indefinitely (allowing to recognize a super-long word).
There is a similar lemma for context-free languages. Those languages can be represented as word accepted by pushdown automata, which are finite state automata that can make use of a stack to decide which transitions to perform. Nonetheless, since there is stilla finite number of states, the intuition explained above carries over, even through the formal expression of the property may be slightly more complex.
In laymans terms, I think you have it almost right. It's a proof technique (two actually) for proving that a language is NOT in a certain class.
Fer example, consider a regular language (regexp, automata, etc) with an infinite number of strings in it. At a certain point, as starblue said, you run out of memory because the string is too long for the automaton. This means that there has to be a chunk of the string that the automaton can't tell how many copies of it you have (you're in a loop). So, any number of copies of that substring in the middle of the string, and you still are in the language.
This means that if you have a language that does NOT have this property, ie, there is a sufficiently long string with NO substring that you can repeat any number of times and still be in the language, then the language isn't regular.
For example, take this language L = anbn.
Now try to visualize finite automaton for the above language for some n's.
if n = 1, the string w = ab. Here we can make a finite automaton with out looping
if n = 2, the string w = a2b2. Here we can make a finite automaton with out looping
if n = p, the string w = apbp. Essentially a finite automaton can be assumed with 3 stages.
First stage, it takes a series of inputs and enter second stage. Similarly from stage 2 to stage 3. Let us call these stages as x, y and z.
There are some observations
Definitely x will contain 'a' and z will contain 'b'.
Now we have to be clear about y:
case a: y may contain 'a' only
case b: y may contain 'b' only
case c: y may contain a combination of 'a' and 'b'
So the finite automaton states for stage y should be able to take inputs 'a' and 'b' and also it should not take more a's and b's which cannot be countable.
If stage y is taking only one 'a' and one 'b', then there are two states required
If it is taking two 'a' and one 'b', three states are required with out loops
and so on....
So the design of stage y is purely infinite. We can only make it finite by putting some loops and if we put loops, the finite automaton can accept languages beyond L = anbn. So for this language we can't construct a finite automaton. Hence it is not regular.
This is not an explanation as such but it is simple.
For a^n b^n our FSM should be built in such a way that b must know the number of a's already parsed and will accept the same n number of b's. A FSM can not simply do stuff like that.

Resources