Codeblocks compiler not displaying output - c

I am trying to solve this problem below. As far as I know, everything is correct logically and syntax wise. However, when I click run, the black cmd window pops up, it displays the answers to problems 1-4 (those have been omitted because they are irrelevant, and problem 5 has been cropped out), but nothing happens at the problem 6 function, and I never get the "process returned 0 (0x0) execution time: xxxx s". Is there something I am doing wrong, or is it the compiler?
Note: I'm not asking for the answer. I just want to know why it isn't displaying.
/* problem 6 Find the difference between the sum of the squares of the first 100 numbers and the square of the sum*/
void problem6()
{
int sum_of_squares;
int square_of_sums;
int counter;
int answer;
int x;
for(x=1; x=100; x++)
{
sum_of_squares += (x*x);
counter += x;
}
square_of_sums = (counter*counter);
answer = square_of_sums - sum_of_squares;
printf("Problem 6 answer: %d", answer);
}
/* problem5(); */
problem6();

(=) is an assignment operator. Your condition should be (x<=100) or (x!=101). And you have not initialized sum_of_squares,square_of_sums and counter with any value so they contain garbage values.
void problem6()
{
int sum_of_squares=0;
int square_of_sums=0;
int counter=0;
int answer;
int x;
for(x=1; x<=100; x++)
{
sum_of_squares += (x*x);
counter += x;
}
square_of_sums = (counter*counter);
answer = square_of_sums - sum_of_squares;
printf("Problem 6 answer: %d", answer);
}

Related

When printing Arrays in C some numbers print as 0.00

This code asks for 10 simple values to create an array and then prints them. The scanf is correct, you can enter the 10 values normally.
The problem is, when printing, that every single value from 1 to 10 is printed as expected but the 7 & 8 values are printed as 0.00. I thought it could be that the for loop is not running correctly but the other numbers are printed just fine.
Does anyone know whats the problem? Why just 7 & 8? Can I fix it using the same structure?
Appreciate the help, I'm new to this. This is what I have:
#include<stdio.h>
int main()
{
int index;
int size = 10;
float values[index];
for (index=0; index < size; index++)
{
printf("\nEnter value[%1d]: ",index+1);
scanf("%f",&values[index]);
}
for(index=0; index < size; index++)
{
printf("\nvalue[%1d]= ", index+1);
printf("%.2f", values[index]);
}
return 0;
}
Just a simple mix up...
When you create float values[index]; index is uninitialized, which results in undefined behavior.
Change this:
int index;
int size = 10;
float values[index];
^
To this:
int index;
int size = 10;
float values[size];
^

My For-Loop isn't working but not inciting an error message - what could it be?

Hi All,
I'm creating a prime-number checker as a part of a project - I'm using a For-Loop to iterate for each number and another to iterate each number below it to work out if it's prime. However, neither of the loops work. I've checked it against other working For-Loops i've created and with friends and neither have helped at all (sorry friends). Any help given will be appreciated and i'll forever hold you in high praise :)
As just stated, i've checked against other pieces and with my friends. i've also tried running the code within the loops separately and the code does indeed work.
#include <stdio.h>
//int FinalPrimeArray[sizeof(Primes)];
//int FinalNotPrimesArray[sizeof(NotPrimes)];
int main()
{
//int Pos = 0;
int Pos2 = 0;
int i = 3;
int k;
int divider = 2;
int productint;
float productintasfloat;
float productfloat;
int Primes[100];
//int NotPrimes[100];
//Test Block (start)
float i2 = i;
float divider2 = divider;
productfloat = i2 / divider2;
printf("float type is: %f \n", productfloat);
productint = i / divider;
productintasfloat = productint;
printf("integer type is: %d \n", productint);
if(productintasfloat == productfloat)
{
printf("yes");
}
//Test Block (end)
printf("Calculating all prime numbers in 3-100");
for(i = 3; i == 100; i++)
{
printf("1");
k = i - 1;
for(divider = 2; divider == k; divider++)
{
printf("2");
float i2 = i;
float divider2 = divider;
productfloat = i2 / divider2;
printf("float type is: %f \n", productfloat);
productint = i / divider;
productintasfloat = productint;
printf("integer type is: %d \n", productint);
if(productintasfloat == productfloat)
{
Primes[Pos2] = i;
Pos2++;
}
}
}
return 0;
}
I would expect it to iterate 97 times (for the first loop), each main iteration iterating 'i - 1' times in turn. As surely made quite clear by now... this is not the case. When ran I get no error-messages, it prints the two lines of code from the text block and the "3-100" message. Then nothing, no error message or further output. However, the code does terminate (Stop symbol, greys out - usually coloured and clickable when code is running)
Any help would be much appreciated and if no one can help... well i guess i'll have to find another way around it. While I would prefer any fixes to remain close to my intended method (I'm not trying to be a ChoosingBeggar) any fix at all would be much appreciated :)
-> Budding Developer
If i've missed any useful information and you want to help - don't be afraid to ask.
I think you have mixed up how for loops work
The for loop will run as long as the condition is true until it becomes false. What you believe is the for loop will run as long as the condition is false until it becomes true.
So for(i = 3; i == 100; i++) should be for (i = 3; i < 100; i++)
This now says keep incrimenting i while it is less than 100. Your previoius loop said increment i while it is 100. Which it never is

pass by reference recursive function without initialising the reference

This is a recursive function to find the amount of 2 appearing in a number.
Example Input:
221122
Example Output:
countTwo(): 4
#include <stdio.h>
void countTwo2(int num, int *result);
int main()
{
int number, result;
printf("Enter the number: \n");
scanf("%d", &number);
countTwo2(number, &result);
printf("countTwo2(): %d\n", result);
return 0;
}
void countTwo2(int num, int *result)
{
if(num > 0) {
if((num % 10)/2 == 1) {
*result += 1;
}
countTwo2(num/10, result);
}
}
I can't increment result since it has not been initialised but I also can't initialise result in the recursive function as this will reset the result.
Edit: This is a question given, with all the template written as above except for the code within countTwo. We are supposed to write the code in countTwo such that main() will be able to run.
Edit2: Thanks for the help! This problem has been solved by using static int. I understand that this is not very efficient. I will also ask my teacher pertaining to this question. Once again, Thanks!
The way to keep all the oddities of this code:
it has to be recursive
you cannot change main, so the initial result value will be undefined
is to, as you stated you cannot do, actually reset result inside countTwo2. However, you need to it in the right place, before you start incrementing.
The way to do that is to reorder your function and add the part that resets the value at the right place:
void countTwo2(int num, int* result)
{
if (num > 0)
{
countTwo2(num / 10, result);
if ((num % 10) / 2 == 1)
{
*result += 1;
}
}
else
*result = 0;
}
Notice that I moved the recursive call up above the if-then block that increments the result, and that when num is 0, we reset. This will call recursively down digits of the input until we're at the end, then reset the result, then return back up one digit at a time and optionally increment the value.
This requires no other changes to your code.
As many have stated, in comments and answers, this is obviously not a good implementation or design but if you have a confined context to work in, this is probably as good as it gets.
I can't see any good reason for declaring this as a void function with the result passed back via pointer parameter.
The following would be a lot cleaner, surely?
int countTwo(int num) {
return (num == 0) ? 0 : (num % 10 == 2) + countTwo(num / 10);
}
For reference, the proper way to write such a function is to not use recursion. It isn't obvious that the compiler will be able to unroll the recursion in this case, as the recursive call would be in the middle of the function, and also conditional.
Thus the only thing gained from recursion is slow execution and higher stack peak use. Why would we want slow execution when we can have fast execution? You should ask your teacher this question, so they can tell you why they are teaching it. I would be most curious to hear their rationale.
For a professional, non-academic programmer, the proper way to write the function would be to use a loop:
int count_n (int input, int n)
{
int result = 0;
for(; input>0; input/=10)
{
if(input%10 == n)
{
result++;
}
}
return result;
}
(This version doesn't work with negative numbers.)
As I mentioned before you may use static variables.
You do not need two arguments.
Here is a solution: #Lasse Vågsæther Karlsen
#include <stdio.h>
int countTwo2(long int num)
{
static int m=0; //static variable is initialized only once.
if (num==0)
return m;
else if (num % 10 ==2)
m=m+1;
num=num /10;
countTwo2(num);
}
int main()
{
int result; long int number;
printf("Enter the number: \n");
scanf("%ld", &number);
result=countTwo2(number);
printf("countTwo2(): %d\n", result);
return 0;
}

Algorithm Graph depth - first search

This is graph code, I want to understand Depth-first search algorithm, but I had some problem with this code,
If I input params:
5 5
1 2
1 3
1 5
2 4
3 5
Why cur become return 4 to 2 to 1 in function dfs?
thank your response
#include <stdio.h>
int book[101], sum,e[101][101];
int n,m,a,b;
void dfs(int cur){
int i;
printf("%d ",cur);
sum++;
if(sum==n){
return;
}
//
for(i=1;i<=n;i++){
if( e[cur][i]==1 && book[i]==0 ){
book[i]=1;
dfs(i);
}
}
return;
}
int main(){
int i,j;
scanf("%d %d ", &n,&m);
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
if(i==j){
e[i][j] = 0;
}else{
e[i][j] = 99999999;
}
};
};
for(i=1;i<=m;i++){
scanf("%d %d" ,&a, &b);
e[a][b] = 1;
e[b][a] = 1;
}
book[1] = 1;
dfs(1);
getchar();
getchar();
return 0;
}
I assume you're asking why your DFS is first exploring 1, then 2, then 4? Well, that's how a DFS works: It greedily goes to the next unvisited vertex. What output would you expect?
Some remarks regarding your code:
To improve the answers that you get, I'd suggest posting code that is a lot cleaner than the code in your question:
Please use variable names that tell your readers what they mean. For example: Use something like bool visited[] instead of int book[].
Use the correct data type! If you want to store whether an edge is there or not, or whether a vertex was visited or not, use bool, not some magic int values.
Global variables are usually not the right thing. There is no reason why all your variables should be global.
Neither is there a reason why the arrays should have the constant size 101.

Check whether or not a number is the sum of two squares in C

I need your help on this problem , I've been trying to solve it all day but I can't reach a solution.
I just started studying C so I apologize if it is a stupid question, however
I am only allowed to use:
if
for
do-while
while
statements to solve the problem.
I need to check whether or not a given number can be written as the sum of two squares, I do not need to know which are these two squares, and I do not need to analyze cases when the number is 0 or 1. What I've managed to build till now is:
unsigned int x;
unsigned int q = 1;
printf("Enter a number : \n");
scanf("%u", &x);
unsigned int j = sqrt(x - (q*q));
if (x != 1 && x != 0)
for (q; (q*q) <= (x/2); q++)
if ((x - (q*q)) == (j*j))
printf("Given number is sum of two squares");
This one sometimes works and sometimes doesn't, for example it does work for 65 (8^2+1^2) and 90 (9^2+3^2) but wouldn't work when I put 181 (10^2+9^2) and so on..
Do you have any idea how I can fix this?
Ok, so here's pseudo code for a possible solution:
Input x;
int a;
int b;
for(a=0; a <= x; a++){
for(b=a; b <= x; b++){
if((a*a + b*b) == x){
Output is_solution;
}
}
}
In the nested loop, b is assigned the value of a to avoid checking the same sum of squares more than once.
Converting this to C, should look like this:
unsigned int x;
unsigned int a;
unsigned int b;
printf("Enter a number : \n");
scanf("%u", &x);
for(a=0; a<=x; a++){
for(b=a; b<=x; b++){
if((a*a + b*b) == x){
printf("Given number is sum of two squares");
}
}
}
I'm a bit rusted in C, hopefully it doesn't have any nasty errors.
You need to put the calculation of j inside the for loop. Currently, you only calculate j for q=1.
I recommend putting the blocks of the loops and the if into braces. I.e.,
if(condition)
{
// statements
}

Resources