The output of the program below is 6. I am not able to figure out why. When I trace it out by hand, I am getting 5.
#include<stdio.h>
#include<conio.h>
main()
{
int i,count=0;
char *p1="abcdefghij";
char *p2="alcmenfoip";
for(i=0;i<=strlen(p1);i++) {
if(*p1++ == *p2++)
count+=5;
else
count-=3;
}
printf("count=%d",count);
}
if(*p1++ == *p2++) is reading both p1 and p2 character by character. When the characters are the same, it will increase count by 5, else it will decrement it by 3. But, there is another thing that you didn't pay attention to: strlen(p1) will always be different in each iteration, because p1 will change. So, in each iteration, you also need to check its value.
p1 p2 count i strlen (before entering into the loop body)
a a 5 0 10
b l 2 1 9
c c 7 2 8
d m 4 3 7
e e 9 4 6
f n 6 5 5 <- No more - this is the last one
The trick here is, strlen(p1) changes every iteration. So loop condition goes
0 <= 10 +5
1 <= 9 -3
2 <= 8 +5
3 <= 7 -3
4 <= 6 +5
5 <= 5 -3
So equal characters are a, c, e, shown as +5 above. Total is 6.
Your program stops when i>strlen(p1) because you are changing p1 each time you do *p1++.
When it computes the condition strlen returns the size from the las char.
If you store the value in a variable at the beginning (before your loop) it should work.
Anyway, try to avoid pointer arithmetic...
Related
I am trying to figure out the following code:
#include <stdio.h>
#define TEN 10
int main(void)
{
int n = 0;
while (n++ < TEN)
printf("%5d", n);
return 0;
}
This prints 1 through 10. Isn't it supposed to print 1 to 9 only, since n++ will make it 10, and the condition while (10 < TEN) would fail hence should exit before printing?
When I change it to while (++n < TEN) I get 1 to 9, which makes sense because the addition is made before the check.
My so far understanding is that the n++ will add after the condition has been checked, hence it will print 10 (since ++n checks before, and n++ check after). Is that correct?
Thanks!
With n++ (postfix increment operator), the value of n gets incremented after the while statement, therefore the while condition n++ < TEN is first verified, and only after the value of n is updated.
When the last iteration of your while instruction while (n++ < TEN) is executed, n is still 9 (and gets incremented by 1 right after) that's why it prints 10 as the last value:
1 2 3 4 5 6 7 8 9 10
I am having some trouble having the get opt to identify the flag regardless of what position it's called at in the inputs in. My program takes in 4 inputs as parameters for the program to function.
here is my code
int a= strtol(argv[1],NULL,10);
int b = strtol(argv[2],NULL,10);
double c = strtol(argv[3],NULL,10);
double d = strtol(argv[4],NULL,10);
so for example i would run my program by calling ./test 5 5 5 5
However I need the program to recognize it regardless of position and then set the variables according to where it is positioned at. Currently I am trying to have it figure out when -p(number) is passed in. So for example ./test 5 5 5 5 -p5 or ./test p 5 5 5 5 5 it will recognize the 5 next to the p up to 1 space away and store that number
my getopt that i have right now is as follows
int i ;
int j = 0;
while ( (opt = getopt(argc,argv, "p:") ) != 1){
switch(opt){
case 'p':
cycles = (int) strtol ( optarg, Null,10);
User will give N,S respectively
If the value of N is 3, i.e i have 3 boxes and the input of S is 6.
Then I am coding in such a manner that in the 1st case(n=3), 1 is added to each box,then again(n=2) 1 is added to each box (A,B,C) excluding the last box, again(n=1) 1 is added to each box excluding the last box as well as the second last box.
And the total number of balls left in each box is to displayed after distribution of total value S,
For example :
It looks like this, where a,b,c are the 3 boxes.
n=3 and s=6
A B C
1 1 1
1 1
1
-----
3 2 1 //output to be displayed
again if the input of n ans s are 4 and 9
then output would be,
A B C D
1 1 1 1
1 1 1
1 1
-------
3 3 2 1 //output to be displayed
again if the input of n ans s are 3 and 4
then output would be,
A B C D
1 1 1 1
1
-------
2 1 1 1 //output to be displayed
again if the input of n ans s are 4 and 2
then output would be,
A B C D
1 1
-------
1 1 0 0 //output to be displayed
for n max value of s = n*(n+1)/2
Actually in this case the the complexity of the code cant be O(n^2). SO this was my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,j,s,y,x1;
scanf("%d%d",&n,&s);
int b[n];
memset(b,0,n);
x1=n;
j=0;
while(s>0)
{
y=j%n;
if(j!=n-1)
{
b[y]++;
s--;
j++;
}
else
{
b[y]++;
s--;
j=0;
n--;
}
}
for(i=0;i<x1;++i)
{
printf("%d ",b[i]);
}
return 0;
}
But after executing the code,The output given by my code:
where n = 4 and s = 9
the output is : 3 32631 -747449654 32629
where n = 3 and s = 5
the output is :2 2 4195586
Why is this happening ? I dont want to use nested for loops!
But whats wrong in here ? please help me!
void * memset ( void * ptr, int value, size_t num );
num is the number of bytes, so
memset(b,0,n);
should be
memset(b,0,n*sizeof(int));
Live Demo
The third argument to memset is the number of bytes to set. Since b is an array of int, it has 4*n bytes that need to be cleared, assuming 32-bit ints. The correct code is
memset( b, 0, sizeof(b) );
I have a code which includes a recursive function. I have wasted a lot of time on recursion but I still couldn't get it really:
#include<stdio.h>
void count(int);
int main()
{
int x=10,z;
count(x);
}
void count(int m)
{
if(m>0)
count(m-1);
printf("%d",m);
}
When the 1st time count is called with argument as 10. it fulfills the condition and then here starts the recursive part. what happens really when a function calls itself? I don't get it. Please explain with reference to stacks.
While m is greater than 0, we call count. Here is a representation of the stack calls:
count (m = 10)
count (m = 9)
count (m = 8)
count (m = 7)
count (m = 6)
count (m = 5)
count (m = 4)
count (m = 3)
count (m = 2)
count (m = 1)
count (m = 0)
printf 0
printf 1
printf 2
printf 3
printf 4
printf 5
printf 6
printf 7
printf 8
printf 9
printf 10
next time it calls itself it has a smaller value
count(int m)
{
if(m>0)
count(m-1); // now it is calling the method "count" again, except m is one less
printf("%d",m);
}
So first it will call count with 10, then it will call it with 9, then 8, then 7..... all the way until this if statement isn't true:
if(m>0)
What might be confusing you is the if statement only applies to the next line (printf isn't part of the if statement)
so you have:
count(int m)
{
if(m>0)
{
count(m-1); // now it is calling the method "count" again, except m is one less
}
printf("%d",m);
}
So, the recursive calls will stop once m is not > 0, and then it will call the printf.
After it calls printf for when m is 0, then it will return from that 'count' call, (Back to where m was equal to 1), and then it will call the printf when m is 1, and then when m is 2, .....
So the output should be:
"0 1 2 3 4 5 6 7 8 9 10"
EDIT:
In terms of a stack:
This is what the stack is doing:
count(10) // push count(10)
->
count(9) // push count(9)
count (10)
->
...
->
count(0) // push count(0)
count(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
-> (and then it starts printing and popping the method off the stack)
// pop count(0), and printf(0)
count(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
->
// pop count(1), and printf(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
->
...
->
// pop count(9), and printf(9)
count(10)
->
// pop count(10), and printf(10)
When a function is called the return address (of the next code to execute) is stored on the stack along with its current arguments. Once the function finishes the address and arguments are popped so the cpu will know where to continue its code execution.
Let's write the addresses of the function (for the purpose of this example only)
count(int m)
{
(address = 100) if(m>0)
(address = 101) count(m-1); // now it is calling the method "count" again, except m is one less
(address = 102) printf("%d",m);
}
For m = 1:
The if is fullfield so we execute code at address 101 with m = 1. address 102 and m = 1 are pushed to the stack and the function is executed again from address 100 with m = 0. Since m = 0 we execute address 102 and printing 0 on console. The function ends and the last return address (102) and argument m = 1 are popped and the line at address 102 is executed printing 1 on the screen.
The function count is called with an integer argument of 10.
Since the function argument m which is 10 is greater than 0 the function count calls itself with an integer argument of m which is 10 minus 1 which equals 9.
Step 2 repeats with varying arguments (m-1) until m is not greater than 0 and which point the program prints the value of m.
The recursive function just modifies the parameter given to it and calls itself with that modified value until the desired result is returned (in this case m not being greater than 0).
Each number refers to the line number.
#include<stdio.h>
count(int);
main()
{
1int x=10,z;
2count(x);
}
count(int m)
{
3if(m>0)
4 count(m-1);
5printf("%d",m);
}
The execution happens like this(with x=3) -
line number|value of x
1 3
2 3
3 3
4 2
3 2
4 1
3 1
4 0
5 0
5 1
5 2
5 3
Numbers printed on the screen 0 1 2 3
If you want a more specific answer, then you have to look into how compilers work. But generally speaking the compiler will create machine code for the function that includes a preamble, in this code enough memory is allocated on the stack (by decrementing a stack pointer) that a copy of the functions variables can be placed on the stack (we can store the state of the function).
The function will have values stored in registers and memory and these must be stored on the stack for each (recursive) call, otherwise the new call will overwrite the precious data!. So very basically the machine code looks like this (pseudo code)
//store m on the stack
store m,stack_pntr+m_offset
//put input values in designated register
a0 = m
//allocate memory on the stack
stackPntr -= stack_size_of(count_vars)
//store return address in allocated register
//jump to the first instruction of count
.
.
By changing some data used for computation we can go back and read the same instructions again and get a different result. The abstraction of recursive function allows us to manipulate the data we want to change in a nice "call by value" way so that we don't overwrite it unintentionally.
This is done by the compiler when it stores the state of the calling function on the stack so we don't have to manually store it.
for a programming homework, I'm implementing Prim's algorithm, the format of the input file for test cases is as follows:
The first line of input will be an integer C, which indicates the number of test cases. The first line of each test case contains two integers N and E, where N represents the number of nodes in the graph and E the number of edges, respectively. Then come E lines, each with 3 integers I, J and P, where I and J represent the nodes of an edge (undirected graphs, where 0 ≤ I, J
Although even I'm starting the code (I'm new to programming) i Don´t understand why my code only reads an entry for the test cases, What am I doing wrong?
this is the code reading the file entradaA.in:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv []){
int testCases;
int numberNodes;
int numberEdges;
freopen("entradaA.in", "r", stdin);
int i, j, cont=1;
int total = 0;
int a, b, c;
scanf ("%d", &testCases);
for (i=0; i<testCases; ++i)
{
scanf ("%d %d", &numberNodes, &numberEdges); //Number Nodes & Edges
for (i=0; i<numberEdges; i++)
{
scanf ("%d %d %d", &a,&b,&c);//
printf ("%d %d %d\n", a, b, c);
}
printf ("Caso %d: Total Weight %d\n", cont++, total);
}
return (0);
}
The input file (entradaA.in) look something like this
2
7 11
0 1 17
0 2 10
0 6 14
1 2 6
1 3 1
2 3 4
2 6 3
3 4 7
4 6 10
4 5 2
5 6 9
6 9
0 1 30
0 2 30
1 3 22
1 5 33
2 3 20
2 4 33
3 4 15
3 5 20
5 4 20
You have the loop variable i modified inside the loop, which is generally unwanted. In this case, since i looped to 11 (the number of edges), it caused your program to terminate since 11 is not smaller than 2 (the number of test cases in the input).
You could use temporary variable (if you are using C++, thank you aardvarkk):
for (int i=0; i<testCases; ++i)
{
scanf ("%d %d", &numberNodes, &numberEdges); //Number Nodes & Edges
for (int j=0; j<numberEdges; j++)
Note that the int j could also be int i, but I wouldn't recommend it. Just use a variable with another name would be clearer. Or if you are in C, just drop the two int and use variables that are local to the function.
For more, you could read this.
Your code produced the following output on my machine. The only change I made was to declare the int values i, j etc. before the freopen call to make the code standard C.
0 1 17
0 2 10
0 6 14
1 2 6
1 3 1
2 3 4
2 6 3
3 4 7
4 6 10
4 5 2
5 6 9
Caso 1: Total Weight 0
It's definitely reading more than your test cases, so I'm not sure what the problem is?