Programmer? Hell no. I'm a professional figure skater.
Gonbe 32 Newbie Poster
Gonbe 32 Newbie Poster
You can construct the value of any coin, using coins of lower value (if there are any); this makes the problem easier because the smallest amount of coins required is then obtained by repeatedly paying with the highest value coin, until the remaining cost is 0 (it would be diffent if the coins had different values, e.g. 80, 45 and 1. If you'd then want to pay a value of say 90, you don't want to fit the biggest, because that would result in one coin of 80 and 10 coins of 1 instead of the better solution: 2 coins of 45. Relevant reading material: http://en.wikipedia.org/wiki/Knapsack_problem)
Gonbe 32 Newbie Poster
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
/* Just a helper function that prints the contents of the vector, separated by a space */
void print_vector(vector<int> data)
{
for (auto elem : data)
cout << elem << ' ';
}
/* Uses the <algorithm> function to generate permutations */
void print_permutations_cheesy(vector<int> data)
{
/* Permutations are generated in lexicographical order, sort to start with the "smallest" value */
sort(data.begin(), data.end());
do /* For every permutation.. */
{
/* Print the vector */
print_vector(data);
/* End the line */
cout << endl;
}
/* Calculate the next permutation */
while (next_permutation(data.begin(), data.end()));
}
/* The function that actually generates the permutations, and releases the "f" function on each one of them */
void permute(vector<int> data, const unsigned begin, const unsigned end, function<void(const vector<int>&)> f)
{
/* If begin equals end, it means we only look at a single element; there is nothing left to permute */
if (begin == end)
{
f(data);
}
else
{
/* Go past every element in the range [begin,end] */
for (unsigned i = begin; i <= end; i++)
{
/* Swap the first element with the i-th element */
swap(data[i], data[begin]);
/* Recursively permute the rest of the range */
permute(data, begin + 1, end, f);
/* Restore the array to it's original (as in: how it was supplied to this function) state */
swap(data[i], data[begin]);
}
}
}
/* Generate the permutations ourselves, this is just a wrapper function …
Gonbe 32 Newbie Poster
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <cctype>
using namespace std;
int main()
{
/* Assumption: substring may overlap. E.g: "aaa" contains "aa" two times. */
const string HAYSTACK = "abbaabbaabb";
const string NEEDLE = "abba";
int counter = 0;
/* A custom compare function for case-insensitive comparing */
function<bool(const char, const char)> compare_fun = [](const char l, const char r)
{ return toupper(l) == toupper(r); };
string::const_iterator h_it(HAYSTACK.begin()), h_end(HAYSTACK.end());
string::const_iterator n_it(NEEDLE .begin()), n_end(NEEDLE .end());
h_it = search(h_it, h_end, n_it, n_end, compare_fun);
while (h_it != h_end)
{
/* Perform tasks here, just a counter in this case */
counter++;
/* If assuming that substrings may not overlap, you'd do something like */
/* advance(h_it, distance(n_it, n_end)); */
h_it = search(h_it + 1, h_end, n_it, n_end, compare_fun);
}
cout << "\"" << HAYSTACK << "\" contains \"" << NEEDLE << "\" " << counter << " times.\n";
return 0;
}
Gonbe 32 Newbie Poster
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
/* Looks like you want something like a bimap, which isn't in the STL */
/* so using a single map here, and swapping the key / value pairs */
/* later to avoid redundancyto some extend. */
map < string, int > map_word_to_num
{ { "One" , 1 }, { "Two" , 2 }, { "Three", 3 }
, { "Four" , 4 }, { "Five ", 5 }, { "Six" , 6 }
, { "Seven", 7 }, { "Eight", 8 }, { "Nine" , 9 } };
map < int, string > map_num_to_word;
/* fill map_num_to_word with the values from map_word_to_num, but the */
/* keys become values and vice versa. */
for (auto& e : map_word_to_num)
{
/* Use emplace() if your compiler supports it.. */
map_num_to_word.emplace(e.second, e.first);
}
/* The string where we will store the user's input in */
string line;
/* Read a line of input from stdin */
cout << "Input: ";
if (!getline(cin, line))
{
cerr << "I/O error on getline()\n";
return 0;
}
/* Remove all whitespaces from the input */
line.erase(remove_if(line.begin(), line.end(), isspace), line.end());
/* The variable in which we will store potential following characters */
size_t pos = 0;
try
{
/* The integer representation of the read line */
/* Throws an invalid_argument exception if it cannot convert to int */
int int_val = stoi(line, &pos);
/* There was more content on …
Gonbe 32 Newbie Poster
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/******** Stack *********/
const unsigned STACK_INTIAL_ALLOC_SZ = 8;
typedef struct {
void* elems; /* The elements that are stored in the stack. */
unsigned elem_sz; /* The size in bytes of the elements stored in the stack. */
unsigned size; /* The amount of elements stored in the stack. */
unsigned capacity; /* The capacity of the stack. */
} Stack;
void stack_create (Stack* const s, const unsigned elem_size);
void stack_delete (const Stack* const s);
bool stack_empty (const Stack* const s);
void stack_push (Stack* const s, const void* const elem_addr);
void stack_pop (Stack* const s, void* const elem_addr);
void stack_create (Stack* const s, const unsigned elem_size)
{
assert(elem_size > 0);
s->elems = malloc(STACK_INTIAL_ALLOC_SZ * elem_size);
s->elem_sz = elem_size;
s->size = 0;
s->capacity = STACK_INTIAL_ALLOC_SZ;
assert(s->elems != NULL);
}
void stack_delete (const Stack* const s)
{
free(s->elems);
}
bool stack_empty (const Stack* const s)
{
return (s->size == 0);
}
void stack_push (Stack* const s, const void* const elem_addr)
{
void* dest_addr = NULL;
/* Double the size once the stack's capacity is reached. */
if (s->size >= s->capacity)
{
s->capacity *= 2;
s->elems = realloc(s->elems, s->capacity * s->elem_sz);
assert(s->elems != NULL);
}
/* Store the element */
dest_addr = (char*) s->elems + s->size * s->elem_sz;
memcpy (dest_addr, elem_addr, s->elem_sz);
s->size++;
}
void stack_pop (Stack* const s, void* const elem_addr)
{
const void* src_addr = NULL;
assert(!stack_empty(s));
s->size--;
src_addr = (const char*) s->elems + s->size * s->elem_sz;
memcpy(elem_addr, src_addr, s->elem_sz); …
Gonbe 32 Newbie Poster
For C-Strings you could take a look at the cstring library, which contains a function named strlen. While you're not looking for a user-defined function, you could also define it yourself as it's quite straight forward. It'd look similar to this:
constexpr size_t strlen (const char text[])
{
// Note: text[0] checks text[0] != '\0'
return (text[0]) ? 1 + strlen(text + 1) : 0;
}
For string objects you would use the length member function.
Gonbe 32 Newbie Poster
After its standardization , array size can be specified with a variable.
While C supports VLAs since the C99 standard, C++ does not support them as can be read in the standard (8.3.4.1).
Gonbe 32 Newbie Poster
Do you mean to do something like this?
#include <stdio.h>
#include <windows.h>
static HHOOK _hook;
static BOOL _control_pressed = FALSE;
static const char _clipboard_text[] = "Hello world!";
static unsigned _clipboard_text_sz = sizeof(_clipboard_text);
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
PKBDLLHOOKSTRUCT kb = (PKBDLLHOOKSTRUCT) lParam;
HGLOBAL hGlobal;
char* pGlobal;
if (nCode >= 0)
{
if (wParam == WM_KEYDOWN)
{
switch(kb->vkCode)
{
case VK_ESCAPE:
PostThreadMessage(GetCurrentThreadId(), WM_QUIT, 0, 0);
break;
case VK_LCONTROL:
case VK_RCONTROL:
case VK_CONTROL:
_control_pressed = TRUE;
break;
case 0x43: // 'C'
if (_control_pressed)
{
printf("CTRL+C detected. Setting clipboard data to \"%s\".\n", _clipboard_text);
// Allocate memory for the clipboard data.
hGlobal = GlobalAlloc(GHND | GMEM_DDESHARE, _clipboard_text_sz);
if (hGlobal)
{
// Obtain a pointer to the buffer by locking.
pGlobal = GlobalLock(hGlobal) ;
// Copy the string. (NULL termination not really needed due to GHND)
memcpy(pGlobal, _clipboard_text, _clipboard_text_sz);
GlobalUnlock(hGlobal);
if (OpenClipboard(NULL))
{
EmptyClipboard();
if (!SetClipboardData(CF_TEXT, hGlobal))
printf("Could not set clipboard data: %u.\n", (unsigned int)GetLastError());
CloseClipboard();
}
else
printf("Error on opening clipboard.\n");
}
else
printf("Error on GlobalAlloc: %u\n", (unsigned int)GetLastError());
}
break;
default:
break;
}
}
else if (wParam == WM_KEYUP && kb->vkCode == VK_CONTROL)
_control_pressed = FALSE;
}
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
int main(void)
{
MSG msg;
if(!SetConsoleCtrlHandler(NULL, TRUE))
printf( "Error on SetConsoleCtrlHandler: %u.\n", (unsigned int) GetLastError());
else
{
_hook = SetWindowsHookEx(WH_KEYBOARD_LL,
LowLevelKeyboardProc,
GetModuleHandle(NULL),
0);
if (_hook)
{
printf("Obtained handle to hook procedure.\n");
printf("Intercepting Ctrl+C commands. Press ESC to quit.\n");
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (UnhookWindowsHookEx(_hook))
printf("Removed hook procedure from …
Gonbe 32 Newbie Poster
Right, so you have this figure of a certain height. When looking at the provided example you can clearly see there's some logic behind it; when asked to draw this figure of height 5 you'd be able to do it.
So let's start with gathering information. We know how the figure grows, and because of this we can also determine how wide it will become for a given height. If we state a height of 0
it's easy, the width would also be 0
. If we define a height > 0
the width would be equal to (2 * height) - 1
. Why? Every line makes the figure 2 symbols wider except for the very first line which has a width of 1.
So we now know how high and how wide the figure will be. That seems like something we could code using a nestes for loop:
const unsigned int WIDTH = (2 * height) - 1;
for (unsigned int row = 0; row < height; row++)
{
for (unsigned int column = 0; column < WIDTH; column++)
{
// Something should go here!
}
cout << endl;
}
So this would go through every row/column combination until we've gone over the entire figure. We haven't defined how we should determine which symbol (*
or ) goes where though. As with the previous there's multiple ways to do this, but seeing the figure you can see the figure is mirrored through the middle: If you'd split …
Gonbe 32 Newbie Poster
for loop. Is this loop supposed to have a body? Effectively, all it does is set x to 0. But since x = 0, when the program reaches the switch blocks nothing happens.
The next for loop forms the body of this loop.1) Line 15 is a standalone for loop. Is this loop supposed to have a body? Effectively, all it does is set x to 0. But since x = 0, when the program reaches the switch blocks nothing happens.
try to put "break;" statement after each "case" ends. and then try to run your code again. hope it helps.
You want the fallthrough in this case.
@OP, I think you're looking for something like this:
#include <iostream>
using namespace std;
int main()
{
const int DAYS_OF_CHRISTMAS = 12;
const string DAY_NUMERALS[DAYS_OF_CHRISTMAS] =
{"first" , "second", "third", "fourth", "fifth" , "sixth",
"seventh", "eight" , "ninth", "tenth" , "eleventh", "twelfth"};
// Print the result for every day. If you want it for a single day just replace
// the loop with alternative code that determines the say. (e.g. user input)
for (int day = 0; day < DAYS_OF_CHRISTMAS; day++)
{
cout<< "On the " << DAY_NUMERALS[day] << " day of Christmas\n"
<< "My true love sent to me...\n";
switch (day)
{
case 11: cout << "12 drummers drumming,\n";
case 10: cout << "11 Pipers piping, \n";
case 9: cout << "10 Lords a leaping,\n";
case 8: cout << "9 Ladies dancing,\n";
case 7: cout << …
Gonbe 32 Newbie Poster
Does this code satisfy the conditions of the question?
Note: You can use only one loop for your logic.
No.
Gonbe 32 Newbie Poster
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
#define LINE_WIDTH (15)
#define BUFFER_SIZE (1024)
char* word_wrap (
char* buffer,
const unsigned int buffer_sz,
const char* string,
const unsigned int string_len,
const unsigned int max_line_width)
{
assert(buffer != NULL &&
buffer_sz > 0 &&
string != NULL &&
string_len > 0 &&
max_line_width > 0);
unsigned int i = 0,
cur_line_width = 0;
int last_space = -1;
// Go past every character of the string, as long as
// we'd have buffer space to store it in.
for (i = 0; i < string_len && i < buffer_sz - 1; i++)
{
buffer[i] = string[i]; // Copy the character to our buffer.
cur_line_width++; // Our line just grew by one.
if (isspace(buffer[i])) // Keep track of our last whitespace.
last_space = i;
// The max line length is reached, and we've found a whitespace up until this point.
if (cur_line_width > max_line_width && last_space >= 0)
{
buffer[last_space] = '\n'; // Replace the space with a newline.
cur_line_width = i - last_space; // And update the length of the new line.
}
}
// The string was copied. Terminate the buffer with a NULL character.
buffer[i] = '\0';
return buffer;
}
int main(void)
{
char* test = "This function takes a string and an output buffer and a desired width. It then copies the string to the buffer, inserting a new line character when a certain line length is reached. If the end of the line is in the middle …
Gonbe 32 Newbie Poster
I understand the concern and I've had discussions about it before. I (still) think that people don't really learn anything if you have to force them to do it. Sure, I think it's stupid to just copy paste code from the internet and I'm sure that'll come back to bite them in the ass, but that's not my problem. I like doing these kind of small simple problems just as a distraction between working on more complex things.. But I'll try to meet somewhere in the middle :<
And can you code that in Lisp, Fortran, ADA, Go, Rust, Scheme, Python, Perl, and Brain####, for me?
Don't challenge me :P
Gonbe 32 Newbie Poster
Atleast the trolls are working as intended...
Gonbe 32 Newbie Poster
what is the code to display "*" as pyramid?
#include <stdio.h>
static void print_n(const char symbol, unsigned int n)
{
while (n --> 0)
printf("%c", symbol);
}
void print_pyramid(const unsigned int height)
{
int i = 0,
width = 0;
const int WIDTH_TOTAL = (2 * height) - 1;
for (i = 1; i <= height; i++)
{
width = (2 * i) - 1;
print_n(' ' , (WIDTH_TOTAL - width) / 2);
print_n('*' , width);
print_n('\n', 1);
}
}
int main(void)
{
print_pyramid(10);
return 0;
}
iamthwee commented: -1 for being an idiot -3
Gonbe 32 Newbie Poster
std bool is not working
I believe it's a C99 thing.. Compile with the C99 compiler flag or just replace every bool
with unsigned char
, every true
with 1
and every false
with 0.
Or replace #include <stdbool.h>
with
#define true (1)
#define false (0)
#define bool unsigned char
Gonbe 32 Newbie Poster
Something like this?
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#define LOWER_BOUND (0)
#define UPPER_BOUND (1000000) // Not inclusive.
typedef void (*prime_callback)(unsigned int);
static unsigned int digit_prime_count = 0;
static const unsigned int M = 10; // Starting from 1.
bool is_prime(const unsigned int n)
{
int i;
if (n >= 2)
{
for (i = 2; i <= (unsigned int) sqrt(n); i++)
if (n % i == 0) return false;
return true;
}
return false;
}
bool is_digit_prime(unsigned int n)
{
char digit_sum = 0;
if (is_prime(n))
{
while (n > 0)
{
digit_sum += n % 10;
n = n / 10;
}
return is_prime(digit_sum);
}
return false;
}
void process_digit_primes( unsigned int lower_bound,
const unsigned int upper_bound,
const prime_callback f)
{
while(lower_bound < upper_bound)
{
if (is_digit_prime(lower_bound))
f(lower_bound);
lower_bound++;
}
}
void print_prime(unsigned int n)
{
digit_prime_count++;
if (digit_prime_count == M)
printf("%dth digit prime: %u.\n", M, n);
}
int main(void)
{
process_digit_primes(LOWER_BOUND, UPPER_BOUND, print_prime);
printf("The amount of digit primes in the interval [%u,%u): %u\n",
LOWER_BOUND, UPPER_BOUND, digit_prime_count);
return 0;
}
Gonbe 32 Newbie Poster
Got bored and did another one..
#include <stdio.h>
#include <assert.h>
#define ARRAY_SIZE (5)
/**
* Spiral matrix
* Given a square matrix(n is odd) , print the elements
* in spiral order starting from the center till a[0][0]
* A=
* 1 2 3
* 4 5 6
* 7 8 9
* o/p 5 4 7 8 9 6 3 2 1
*/
void print_as_spiral(const int data[][ARRAY_SIZE], const unsigned int size)
{
assert (size % 2 != 0);
int i = 0;
if (size == 1) {
printf("%d ", data[0][0]);
} else {
print_as_spiral(data[1] + 1, size - 2);
for(i = 1; i <= size - 1; i++) printf("%d ", data[i] [0]);
for(i = 1; i < size - 1; i++) printf("%d ", data[size - 1][i]);
for(i = size - 1; i > 0; i--) printf("%d ", data[i] [size - 1]);
for(i = size - 1; i >= 0; i--) printf("%d ", data[0] [i]);
}
}
int main(void)
{
const int data[][ARRAY_SIZE] ={{ 1, 2, 3, 4, 5},
{16, 17, 18, 19, 6},
{15, 24, 25, 20, 7},
{14, 23, 22, 21, 8},
{13, 12, 11, 10, 9}};
print_as_spiral(data, ARRAY_SIZE);
return 0;
}
Gonbe 32 Newbie Poster
If a
is an integer it doesn't (really) make much sense to do it.
Gonbe 32 Newbie Poster
What is there to explain? malloc
(attempts to) allocate a given amount of memory on the heap. It doesn't really know (or cares) what you're going to put there so it returns a void pointer so you'll have to cast it to a pointer matching the data you're putting in it. (atleast if you want to dereference it for example)
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int* heap_int = NULL;
// Allocate memory for a single integer.
heap_int = (int*) malloc(sizeof(int));
if (heap_int == NULL)
printf("Memory allocation failed.\n");
else
{
printf("Memory was successfully allocated.\n");
// Free the memory again.
free(heap_int);
}
return 0;
}
Gonbe 32 Newbie Poster
Attempted the things others attempted..
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
void remove_even (int data[], const unsigned int size);
void print_spiral (const unsigned int size);
static void print_spiral_line (const unsigned int n, const unsigned int line);
bool can_be_palindrome (char text[], const unsigned int size, const bool middle_found);
/**
* Write a C program to Remove even numbers and fill it with zeros.
* Note: You can use only one loop for your logic.
*/
void remove_even(int data[], const unsigned int size)
{
int i = 0,
pivot = size - 1;
while (i < size && i <= pivot)
{
// This number is even.
if (data[i] % 2 == 0)
{
// Switch it with the last.
data[i] = data[pivot];
data[pivot] = 0;
// An element was added to "the zero section".
pivot--;
}
else {
i++;
}
}
}
/**
* Print the pattern
*
* N=4
* 4444444
* 4333334
* 4322234
* 4321234
* 4322234
* 4333334
* 4444444
*/
void print_spiral(const unsigned int size)
{
int i = 0;
const int SPIRAL_WIDTH = (2 * size) - 1;
if (size > 0)
{
// Print all lines of the spiral.
for (i = 0; i < SPIRAL_WIDTH; i++)
{
print_spiral_line(size, i);
printf("\n");
}
}
}
static void print_spiral_line(const unsigned int n, const unsigned int line)
{
int i = 0;
const int SPIRAL_WIDTH = (2* n) - 1;
// The first and the last line of a spiral are easy.
if (line == 0 …
Gonbe 32 Newbie Poster
int can never have 8 bits. The C standard defines the minimal range of int and unsigned int, such that at least 16 bits are required to represent them.
Hmm I was pretty sure it was 8 bits when I used it, although it's quite some time ago.. If the standard says it can't be so (too lazy to check) I'm probably mixing things up.
Gonbe 32 Newbie Poster
Not having a compiler handy, so treat the following as kind-of pseudo code, but if performance is no requirement you could define it as
bool isMono(const tNode* t)
{
if (t == NULL)
return true;
else
return tsearch(t->info, t->left) == NULL && tsearch(t->info, r->right) == NULL && isMono(t->left) && isMono(r->right);
}
(assuming tsearch on an empty tree results in a NULL pointer)
Gonbe 32 Newbie Poster
try adding more elements in array and try to run it
I don't see anything in your post that you could be not "not wrong" about. All I see is output of the given code on your system followed by a question. So I'm not sure what you mean, unless you and ss125 are the same person, in that case I understand what you mean but you're then answering your own question.
Gonbe 32 Newbie Poster
That's some shady company asking their candidates questions like that..
Gonbe 32 Newbie Poster
I wouldn't say it that way (you yourself refer to arr's address a couple of times in your post). Its address just happens to be the same as that of its first element.
I wanted to make clear that arr
does not contain the memory address of the array (because it would be a pointer then and &arr
would be different from &arr[0]
) but instead it is the memory address of the array (so that arr
is the same as &arr[0]
result-wise), if that makes sense. Terminology kind of gets confusing easily.. :< I helped some people in the past and it seemed to be an common thing that was misunderstood; arrays and pointers were used as the same thing. Often it doesn't lead to errors despite the misunderstanding, but sometimes it does. (I'd provide an example of it, but I don't have one handy right now)
Or to make the mechanics a bit more obvious: the address of arr plus 1 * sizeof(int[2]). That is writing p + i where p is a T pointer (or array) always increments by i * sizeof(T) bytes - T in this case being int[2] and sizeof(Foo[N]) being equal to sizeof(Foo)*N for all types Foo.
Hmm, that was kind of what I was trying to say but this makes it more clear I think yeah!
Gonbe 32 Newbie Poster
normally an integer datatype hold 2 byes of memory.If Int is declared it holds 2 bytes by default.
This is not true. The amount of bytes an integer takes up depends on the supported word size of the used CPU and there is no "default" specified in the specification. 32-bit or 64-bit are most common on desktops and I've personally only encounter 8 and 16 bit integers on embedded systems.
&arr
This is a pretty common misconception. &arr
represents the memory address of the first element in arr
. (More precisely the memory address of the array, which is the memory address of the first element) and in this case that expression would be of type int(*)[2]. arr
itself does not have a memory address. When used in an expression it is implicitly converted to a pointer type however, so int*
in this case, representing the memory address of the first element in arr
. Hence arr == &arr == &arr[0]
. (the resulting memory addresses, the types of the expressions differ)
arr + 1 which means 2 bytes
As stated earlier arr
would be implicitly converted to type int*
so doing arr + 1
yields the memory address of the first element in arr
(represented by arr
) plus 1 time sizeof(int)
amount of bytes. (represented by + 1
) In this case this would be the memory address of the second element in arr
.
&arr +1 means arr[]=> 2 bytes for arr and 2 bytes for …
Gonbe 32 Newbie Poster
what could we do if theirare more than 10000000000 words?
We could then ask this on Daniweb by bumping a 6 year old thread after which we could demolish our computer never to touch one ever again.
Gonbe 32 Newbie Poster
p
is an array of pointers. *(p+i)
could be written as p[i]
and *(p[i] + j)
could likewise be written as p[i][j]
. (So *(*(p+i)+j)
could be written as p[i][j]
) (and the contents of p
are offsets off a
which is 2-dimensional)
So you could write that printf
as: printf("%d %d %d %d \n", p[i][j], p[j][i], p[i][j], p[j][i]);
.
You could also declare the array a
as static int a[4]={1,2,3,4};
.
You could seep[0]
as {1, 2, 3, 4}
p[1]
as {2, 3, 4}
p[2]
as {3, 4}
p[3]
as {4}
You loops request
p[0][0]
, p[0][0]
, p[0][0]
, p[0][0]
,p[0][1]
, p[1][0]
, p[0][1]
, p[1][0]
,p[1][0]
, p[0][1]
, p[1][0]
, p[0][1]
,p[1][1]
, p[1][1]
, p[1][1]
, p[1][1]
which results in:
1, 1, 1, 1
2, 2, 2, 2
2, 2, 2, 2
3, 3, 3, 3
Gonbe 32 Newbie Poster
'Hello'
should be "Hello"
.
Gonbe 32 Newbie Poster
Or meh, question is poor and no effort is shown, but can't say I care for a task this small. Empower me with your downvotes, mortals! :<
#include <stdio.h>
int main(void)
{
char string[] = "f a1 2 5 ffffffde 23 fffffff1 4 b0";
const char* remove = "ffffff";
const int remove_len = strlen(remove);
char* offset = NULL;
while (offset = strstr(string, remove)) {
strcpy(offset, offset + remove_len);
}
printf("Result: \"%s\".\n", string);
return 0;
}
rubberman commented: No mortals here! :-) +12
Gonbe 32 Newbie Poster
#include <stdio.h>
int main(void)
{
const char* string_before = "f a1 2 5 ffffffde 23 fffffff1 4 b0";
const char* string_after = "f a1 2 5 de 23 f1 4 b0";
printf("The C-code resulted in: \"%s\".\n", string_after);
return 0;
}
Gonbe 32 Newbie Poster
And as to why your program does what it does: I think it is because you are opening the file in text mode instead of binary mode:
For streams open in text mode, offset shall either be zero or a value returned by a previous call to ftell, and origin shall necessarily be SEEK_SET.
So replace fopen("tanc.TXT", "r");
with fopen("tanc.TXT", "rb");
and it should work. (Although output might be wrong because you're mixing cout/cin with printf) (But it doesn't skip over newlines yet, but the code above shows how to do that, if that is what you want) You could remove the seek part altogether though as you're seeking to where you ended the previous iteration anyway. You could also rewrite your loop because going from i to i+n-1 takes the same amount of iterations as going from 0 to n-1. Which is (in my opinion) more readable.
Gonbe 32 Newbie Poster
Your code is a mixture of C and C++ conventions, you should choose one or the other. As you posted this in the C section I assume you want C code. What do you want to do with newlines? Do you want to skip them entirely? You also don't have to seek all the time. Something like this should work:
#include <stdio.h>
#include <errno.h>
int main(void)
{
FILE *stream = NULL;
char c = 0;
unsigned int i = 0,
n = 0;
stream = fopen("tanc.TXT", "r");
if (stream != NULL)
{
printf("Dati numarul de caractere: ");
if (scanf(" %u", &n) == 1)
{
while((c = fgetc(stream)) != EOF)
{
if (i == n) {
printf("#");
i = 0;
}
if (c != '\n')
{
printf("%c", c);
i++;
}
}
printf("#");
}
else {
fprintf(stderr, "Invalid input.\n");
}
if (fclose(stream) == EOF) {
fprintf(stderr, "Error on closing the input file: %s\n", strerror(errno));
}
} else {
fprintf(stderr, "Error on opening the input file: %s\n", strerror(errno));
}
return 0;
}
Gonbe 32 Newbie Poster
Relevant fragements from the C(99) specification (http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf):
6.2.4 Storage durations of objects
-----------------------------------
The lifetime of an object is the portion of program execution during which storage is
guaranteed to be reserved for it. An object exists, has a constant address,25) and retains
its last-stored value throughout its lifetime.26) If an object is referred to outside of its
lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when
the object it points to reaches the end of its lifetime.
6.3.2.3 Pointers (Point 6)
--------------------------
Any pointer type may be converted to an integer type. Except as previously specified, the
result is implementation-defined. If the result cannot be represented in the integer type,
the behavior is undefined. The result need not be in the range of values of any integer
type.
7.1.4 Use of library functions
-------------------------------
Each of the following statements applies unless explicitly stated otherwise in the detailed
descriptions that follow: If an argument to a function has an invalid value (such as a value
outside the domain of the function, or a pointer outside the address space of the program,
or a null pointer, orapointer to non-modifiable storage when the corresponding
parameter is not const-qualified) or a type (after promotion) not expected by a function
with variable number of arguments, the behavior is undefined.
Gonbe 32 Newbie Poster
I don't think the new code gives the desired output. Mainly:
while (s[j] != ' ' && j < l) {
++j;
if (j == foldHere)
putchar('\n');
}
You may print a newline here before having print anything that comes before it. For example, take a FOLDLENGTH of 1 with the string you posted in the first post.
Gonbe 32 Newbie Poster
You are comparing indexes to string values. In addition there seemed to be some logic mistakes. Here's an attempt to fix them for you:
void fold(char s[], int l)
{
int i, j, foldHere;
i = j = 0;
foldHere = FOLDLENGTH;
while (i < l)
{
// We are currently on a non-space symbol.
if (s[i] != ' ')
{
// Copy our index to 'j'.
j = i;
// Go to the next space-symbol (or to the end of the string)
while (s[j] != ' ' && j < l) {
putchar(s[j]);
++j;
}
// We're not at the end of the string and the fold marker was passed.
// This means there are words following, print the newline now.
// Future improvement: check if the following characters are non-whitespace characters.
if (j < l)
{
if (j >= foldHere) {
putchar('\n');
} else {
putchar(s[j]);
}
}
// Continue after the marker.
i = j + 1;
}
else
{
if (i == foldHere)
putchar('\n');
else
putchar(s[i]);
++i;
}
}
}
I wasn't fully sure what you were trying to do however. Here's another approach that might be easier to read:
void fold(char str[], int length, int fold_index)
{
// Assuming the parameters are "correct".
int i;
// Everything up until fold_index can 'safely' be printed.
for (i = 0; i < fold_index; i++)
putchar(str[i]);
// Would you want to check for other whitespace characters too?
while(str[i] != ' ' && i < length) …
Gonbe 32 Newbie Poster
@gonebe your output is wrong
No it's not. Using gcc I get \nefd
as output when printing \nab\bcd\refd
and the output is \nefg
when printing \nab\bcd\refdg
. The newline doesn't overwrite the 'd' which I also edited in my last post, unsure why it didn't went through.
the web output is not correct.
plz check it on windows or linux system creating a .c file
Based on what knowledge? As stated in the other thread about this it seems pretty likely compilers deal with this in different ways. Aside from it being a "puzzle" I don't see much practical use for this by the way..
Gonbe 32 Newbie Poster
You print \n
. Then you print ab\bcd
on the second line. \b
is the backspace leaving acd
. Then you print \r
which results in going to the start of the current line. Then you print ef
. The lin already contained bcd
so it will now contain efd
with the position being on the d
. If you add a printf("\n");
it would overwrite the d
so the second line would contain bc
then.
I'm not sure why the posted fragment prints efd
for you. Maybe I'm wrong here. (Can't compile at the moment..)
Gonbe 32 Newbie Poster
What's up with all the garbage questions lately..
Gonbe 32 Newbie Poster
The factorial of a positive integer n, n!, is 1 * 2 * 3 * ... * n
for n > 0 and 1 for n = 0. Would take you about 1 second to find on google.
The simple case is when n = 0, you simply return 1.
if (n == 0)
return 1;
Then for other cases we want to express the problem of calculating the factorial using a smaller version of the same problem so we can solve it recursively. It's easy to see that fac(n) = n * fac(n - 1)
.
else
return n * fac(n - 1);
Gonbe 32 Newbie Poster
Replace your printf with printf("%f %f",*p,*q);
Gonbe 32 Newbie Poster
Thanks man! but can I do by using Pass by Reference? not Pass by Pointers?
Not in C, that's a C++ feature. Closest thing you could do is make the pointers you pass const. (e.g float* const res
)
Gonbe 32 Newbie Poster
#include <stdio.h>
void A(float* res)
{
float a, b;
printf("Enter Numbers A: \n");
scanf(" %f %f",&a,&b);
(*res) = a+b;
}
void B(float* res)
{
float a, b;
printf("Enter Numbers B: \n");
scanf(" %f %f", &a, &b);
(*res) = a + b;
}
int main(void)
{
float total,Ares,Bres;
A(&Ares);
B(&Bres);
total= Ares + Bres;
printf("A + B = %.2f \n",total);
return 0;
}
jandanielsaclolo commented: Thanks! +0
Gonbe 32 Newbie Poster
By the way is there any reason that someone should use an iterator for this? Would it be more secure or fast?
The main benefit (as far as I know) is that the use of iterators makes your code generic because most (if not all) containers in the STL support it. Performance differences seem to vary, never really tested it myself.
Gonbe 32 Newbie Poster
Hmm, so you want to count the amount of times an integer is present in a matrix without knowing upfront what integers can be in there? I don't think there's a very beginner-friendly solution for this. I'd probably use a map for it. Below an example:
#include <iostream>
#include <map>
#include <iomanip>
using namespace std;
int main()
{
const unsigned int DIMENSION = 6;
int M[][DIMENSION]= {{3,14,4,10,3,6},
{5,10,3,8,3,3},
{8,3,3,8,-3,3},
{10,10,-3,3,6,-3},
{-3,-3,6,8,5,5},
{6,5,5,8,5,5}};
map<int, unsigned int> occurrences;
// Process the matrix.
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
occurrences[M[i][j]]++;
}
}
// Show the results:
for (map<int, unsigned int>::iterator it = occurrences.begin(); it != occurrences.end(); ++it)
{
cout << setw(3) << (*it).first << " ---> " << (*it).second << endl;
}
return 0;
}