Problems to solve using control instructions in C for practice - c

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)

Related

fscanf til EOF to save contents of file word by word

Hi I'm trying to make a code to read in a file through fscanf to find all the separate words in the file and save it in an array but it's not working. Could you please tell me what's currently wrong in my code?
char data[300][45];
char words[100];
char garbage[10];
#include <stdio.h>
int main(void)
{
int i=0,j;
FILE* file=fopen("week4_data1.in","r");
while((fscanf(file,"%[a-zA-Z]s",data[i++]))!=EOF && (fscanf(file,"%[^a-zA- Z]s",garbage))!=EOF);
for(j=0;j<i;j++)
printf("%s",data[j]);
return 0;
}
I'm running it on macs terminal and it compiles well but when I run it I get Bus error: 10.
Oh and this is the contents of the file:
What are algorithms? Why is the study of algorithms worthwhile? What is the role of algorithms relative to other technologies used in computers? In this chapter, we will answer these questions. We can also view an algorithm as a tool for solving a well-specified computational problem. The statement of the problem specifies in general terms the desired input/output relationship. The algorithm describes a specific computational procedure for achieving that input, output relationship. For example, one might need to sort a sequence of numbers into nondecreasing order. This problem arises frequently in practice and provides fertile ground for introducing many standard design techniques and analysis tools. For example, given the input sequence 31, 41, 59, 26, 41, 58, a sorting algorithm returns as output the sequence 26, 31, 41, 41, 58, 59. Such an input sequence is called an instance of the sorting problem. In general, an instance of a problem consists of the input satisfying whatever constraints are imposed in the problem statement needed to compute a solution to the problem. Sorting is a fundamental operation in computer science many programs use it as an intermediate step, and as a result a large number of good sorting algorithms have been developed. Which algorithm is best for a given application depends on-among other factors the number of items to be sorted, the extent to which the items are already somewhat sorted, possible restrictions on the item values, and the kind of storage device to be used: main memory, disks, or tapes. An algorithm is said to be correct if, for every input instance, it halts with the correct output. We say that a correct algorithm solves the given computational problem. An incorrect algorithm might not halt at all on some input instances, or it might halt with an answer other than the desired one. Contrary to what one might expect, incorrect algorithms can sometimes be useful, if their error rate can be controlled. We shall see an example of this in Chapter 31 when we study algorithms for finding large prime numbers. Ordinarily, however, we shall be concerned only with correct algorithms. An algorithm can be specified in English, as a computer program, or even as a hardware design. The only requirement is that the specification must provide a precise description of the computational procedure to be followed.
You can follow the below approach to get things done.
Open the file. Help : fopen()
Check for successful opening. Hint: Return value.
Read a line from the file. Check for the success. Help : fgets() and Return value.
Start tokenizing the read line and store into the array one by one. Help : strtok()
Continue until token is NULL.
Continue until fgets() is NULL.
The format strings "%[a-zA-Z]s" and "%^[a-zA-Z]s" are not right. You don't need the s in those format strings. Use "%[a-zA-Z]" and "%^[a-zA-Z]".
I have a feeling that will fix your problem.
To make your code robust, you should specify the maximum number of characters in the format strings and make sure that i does not exceed the valid limit.
while( i < 300 &&
fscanf(file,"%44[a-zA-Z]",data[i++]) != EOF &&
fscanf(file,"%9[^a-zA-Z]",garbage) != EOF );

C programming output specifications for counting answers

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.

Prime Number List Program

first of all i want to prove that this is not a homework http://computer.atlas4e.com/
i really need to understand this with an explanation, because I'm trying to understand the basic of the computer by my self thanks for the help
`Prime Number List Program
Write a main program that generates a list of prime numbers. The program should use the PrimeTest subroutine to test whether each of the numbers 2, 3, 4, 5, 6…, 255 & 256 is a prime. Each number that is found to be a prime should be added to a list in memory. The list of primes should be stored in consecutive memory locations. Use a location named StartPrimeList to point to the start address of the prime number list. Use a pointer called PrimeListPtr to point to the (current) end of the list, PrimeListPtr will be incremented every time a prime number is appended to the list.
Use a location named PrN to store the number that you are checking. Start by storing a 2 in PrN. In a loop, you should call PrimeTest to determine whether PrN is a prime. If PrN is a prime, then append it to the list. Then add 1 to PrN and jump back to the start of the loop to test the next value of PrN.`
The output of the program should appear starting at location StartPrimeList as follows:-
Address Contents
[StartPrimeList] 2
[StartPrimeList+1] 3
[StartPrimeList+2] 5
[StartPrimeList+3] 7
…
…
[StartPrimeList+?] Largest Prime <= 256
(251 - 54th prime number starting from 2 <=256)
(257 - 55th prime number >256)
`
Mark Allocations for Program 2
• A program header in the program listing explaining how the program works.
• Sensible/Relevant program comments on sections of assembler language.
• Relevant labelling of loops and data items. [4]
• Program runs successfully on xComputer and produces correct output for given input.
`
"Write a main program that generates a list of prime numbers." This is your basic question. further details are given later to help you answer it.
"The program should use the PrimeTest subroutine to test whether each of the numbers 2, 3, 4, 5, 6…, 255 & 256 is a prime." Can you do this part? If not, then write the best code you can to do it and ask here again with a specific question.
"Each number that is found to be a prime should be added to a list in memory." Can you do this part? If not, then write the best code you can to do it and ask here again with a specific question.
"The list of primes should be stored in consecutive memory locations." Can you do this part? If not, then write the best code you can to do it and ask here again with a specific question.
"Use a location named StartPrimeList to point to the start address of the prime number list." You should have got the message by now. Use the excellent advice given in the question itself to help you. Write your code. If it works, then fine. If it doesn't then post it here, explaining what it should do and what you think the problem might be. Tell us what you have tried, and what didn't fix the problem. That will help us having to repeat your work.
We won't write your program for you. You have to write it; we will help you write it.

Calculating input.

I tried to make a code that calculates the values of the formulas the user inputs. I.e , if user inputs "10+5" , the program would print "The sum is 15" etc. At first, i thought this is a easy thing to do, but if realized that just using scanf orsth wouldn't do the trick. Then i messed around with arrays and loops to see if the loop encounters "-" or "+" signs in input and then saving the character before "-" or "+" and after it and then calculating it, but i couldnt make this work either.
Could you please lead me in the right direction on how to get this done.
Thank you very much!
This can be quite complicated, especially when you get to operator precedence and you need to correctly calculate, for example, 2 + 5 * 6, which needs to be treated as 2 + (5 * 6). The correct way to approach this is to construct an expression tree (just like a compiler would). e.g.
+
/ \
2 *
/ \
5 6
You do this by creating binary tree. Each nodes holds an operation and (up to) two subnodes. Then you evaluate your expression by traversing the expression tree.
What you are trying to do is to parse arithmetic expressions, then evaluate them. There is a ton of stuff on this on the internet so, since this is your homework, I'll leave you to Google. Your first thought, that this would be easy to do, is probably a naive thought, though it's not a terribly difficult problem if you don't get too ambitious too quickly.
This might be a little over your head, but what you can do is use a grammer engine for c and a lexical analyzer.
I believe it is called "BISON" and "YYLEX"
From what I remember in school, it is how we made our pascal compiler.
http://en.wikipedia.org/wiki/GNU_bison
After creating a tree. you then can analyze sub trees and then the root node will be the sum of the sub trees.
These might be some steps that you might want to consider
get the input using getline() or fgets()
start reading the string from the beginning
do two passes, use one queue for operators and another for operands (numbers)
during the first pass, you reach an * or /, read the next number, perform the operation on the next number and the number you read before, and insert the result in a queue
also during the first pass, if you read a + or -, silently push the operator and operands into their respective queues
during the second phase handle + and -... using queues will help you properly handle successive minuses e.g. 4-3-3
These are not EXACT steps, but it's a heuristic worth looking into - try to work through these, change them according to what makes sense to you etc.

How can I find all possible combinations of a string? Using CUDA

I am trying to speed up my algorithm by using CUDA to find all possible combination of a string. What is the best way I can achieve this?
example:
abc
gives:
a
b
c
ab
ac
bc
i have nothing so far. i am not asking for code. i am just asking for the best way to do it? an algorithm? a pseudocode? maybe a discussion?
The advantage to using CUDA is massive parallelism with potentially thousands of threads with little overhead. To that end, you have to figure out a way to divide the problem into small chunks without relying too much on communication between the threads. In this problem you have n characters and each can be either present or absent in each output string. This yields 2^n total output strings. (You've left off the empty string and the original string from your list...if that's the desired result then you have 2^n - 2 total output strings.)
In any event, one way you can divide up the work of creating the strings is to assign each potential output string a number and have each thread compute the output strings for a certain range of numbers. The mapping from number to output string is easy if you look at the binary representation of each number. Each binary digit in an n-bit number corresponds to a character in the string of length n. Thus, for your example, the number 5 or 101 in binary maps to the string "ac". The strings you listed would be created by computing the mappings for numbers from 1 to 6 as follows:
1 c
2 b
3 bc
4 a
5 ac
6 ab
You could compute 7 to get abc or 0 to get the empty string if desired.
Unless you're doing this for words longer than a dozen or so characters, I'm not sure this will be that much faster though. If you're doing it for words longer than 25 or so characters you might start running into memory constraints since you'll be wrangling hundreds of megabytes.
I will be very, very surprised if CUDA is the right solution to this problem.
However, I would write a kernel to find all substrings of length n, and launch the kernel in a loop for each value of n from 0 to the length of the string. Thus, each thread in a kernel will have exactly the same instructions (no threads will sit around idle while others finish).
Each thread will "find" one substring, so you might as well have thread i find the substring starting at index i in the string. Note that each substring length requires a different number of threads.
so, for n=1:
thread 0: a
thread 1: b
thread 2: c
and for n=2:
thread 0: ab
thread 1: bc

Resources