For loop only executes once, raising a number to another number - c++

New to programming/coding, and couldn't get why my code doesn't work.
It's supposed to show you the result of raising a number to another number. But it only ends up looping once.
Example of error:
Input an integer: 3
Raise integer to what number: 4
3 raised to 4 is 9
My code:
#include <stdio.h>
int raiseToPow(int nNum1, int *nResult) {
*nResult = nNum1 * nNum1;
}
int main() {
int nNum1, nNum2, nResult, i;
printf("Input an integer: ");
scanf("%d", &nNum1);
printf("\n");
printf("Raise integer to what number: ");
scanf("%d", &nNum2);
printf("\n");
for (i = 0; i < nNum2; i++) {
raiseToPow(nNum1, &nResult);
}
printf("%d raised to %d is %d", nNum1, nNum2, nResult);
}

you should initialize nResult by 1 because your variable doesn't have anything inside. Also, replace *nResult = nNum1 * nNum1 by *nResult = *nResult * nNum1

It's looping the right number of times, you just need to put the print inside the loop. Also you should add a newline to the end of your print.
for(i = 0; i < nNum2; i++)
{
raiseToPow(nNum1, &nResult);
printf("%d raised to %d is %d\n", nNum1, nNum2, nResult);
}

Related

Recursive Digit Sum

I was trying to solve this problem on hackerrank. But I got some problem. Specific problem is:
For example:
The sum of digits 9875 will be calculate as: sum(9875) = 9+8+7+5 = 29. sum(29) = 11. sum(11) = 2. (Using recursive function).
In my test case, (n ='9875', k=4) the number p is created by concatenating the string n k times so the initial p = 9875987598759875 ( the string '9875' repeat 4 times ).
But when i code this test case, it doesn't work. Here is my source code:
int SuperDigit(long n){
long sum =0;
if(n==0) return 0;
else{
return sum= sum +(n%10 + SuperDigit(n/10));
}
if(sum>10){
return (sum%10 + SuperDigit(sum/10));
}
}
int main(){
string n;cin>>n;
int T;cin>>T;
string repeat;
for(int i=0; i <T;i++){
repeat += n;
}
cout<<repeat;
long x=0;
stringstream geek(repeat);
geek>>x;
long sum = SuperDigit(x);
printf("\n%ld ",sum);
for(int i=0;i<10;i++){
if(sum>=10){
sum = SuperDigit(sum);
}
else{
break;
}
}
printf("\n%ld ",sum);
}
If i try: n = '123' and k =3 (Expected output: 9)
My output will be correct, here is my output for this test case:
123 3
123123123
18
9
But when i try n = '9875' and k = 4 (Expected output: 8)
My output will be wrong:
9875 4
9875987598759875
46
1
As you can see in this test case, the first sum of all digits must be 116. But mine only show 46. Can anyone explain for me? Thanks a lot!
In your current code you return prematurely in
if(n==0) return 0;
else{
return sum= sum +(n%10 + SuperDigit(n/10));
}
Imagine that n == 89 so n%10 returns 9 and SuperDigit(n/10) returns 8 and you have 17 as an answer (when 8 is expected).
You can put it as
int SuperDigit(long n) {
int result = 0;
/* We compute digital root (sum of digits) */
for (long number = n; number != 0; number /= 10)
result += (int) (number % 10);
/* if result is out of range [-9..9]
we compute digital root again from the answer */
if (result < -9 || result > 9)
result = SuperDigit(result);
return result;
}
You can simplify your program as shown below. Since you want to find the sum recursively, the below program shows one possible way of doing it.
Version 1: Using recursive function
#include <iostream>
int findDigit(int passed_num, int currentSum)
{
int lastDigit;
if (passed_num == 0) {
return currentSum;
}
// find the last didit
lastDigit = passed_num % 10;
currentSum+= lastDigit;
//call findDigit() repeatedly
currentSum = findDigit(passed_num / 10, currentSum);
std::cout<<lastDigit<<" ";
return currentSum;
}
int main()
{
std::cout << "Enter a number: ";
int input_num, sum;
std::cin>>input_num;
sum = findDigit(input_num, 0);
std::cout<<"sum is: "<<sum<<std::endl;
std::cout << "Enter another number: ";
std::cin>>input_num;
sum = findDigit(input_num, 0);
std::cout<<"sum is: "<<sum<<std::endl;
return 0;
}
Note there are simpler(other) ways of finding the sum without recursively. One such way is shown below:
Version 2: Using loop
#include <string>
#include <iostream>
int main()
{
std::cout << "Enter a number: ";
int individual_number = 0, sum = 0;//these are local built in types so initialize them
std::string input_num;
std::cin >> input_num;
for(char c : input_num)
{
individual_number = c -'0';
std::cout<<individual_number<<" ";
sum+= individual_number;
}
std::cout<<"total amount: "<<sum<<std::endl;
// std::cout<<"The sum comes out to be: "<<sum<<std::endl;
return 0;
}

Array prints random symbols

I need to do a program for school that reads few products and their price and then sort them in a list accodring by their price so im using array list to do it but when i print them i get random characters as output
#include <stdlib.h>
#include <stdio.h>
int main(){
int i = 0;
char list1[7];
char list2[7];
char list3[7];
while(i <= 3){
char name;
int price;
printf("Give me the product \n");
scanf("%s", &name);
printf("Give the price \n");
scanf("%d", &price);
if(price == 1){
list1[i] = list1[i] + name;
} else if(price == 2){
list2[i] = list2[i] +name;
} else if(price == 3){
list3[i] = list3[i] +name;
} else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", &name);
("Give the price \n");
scanf("%d", &price);
}
i = i + 1;
}
for (int z = 0; z <= 3; z++){
printf("%s",list1);
printf("\n");
printf("%s",list2);
printf("\n");
printf("%s",list3);
printf("\n");
}
}
#include <stdlib.h>
//Need string.h library to use strcopy
#include <string.h>
#include <stdio.h>
#define MAX_CHAR_SIZE 10
int main(){
//We define the maximum size of an array to be sure it will not overflow so the maximum character that list1,2,3 can contain is 10 including '/0' since you wanna print it as a string
char list1[MAX_CHAR_SIZE];
char list2[MAX_CHAR_SIZE];
char list3[MAX_CHAR_SIZE];
char name[MAX_CHAR_SIZE];
//I prefer unsigned if you know you don't to go in negative value
unsigned int price;
//Prefer for over while if you know how many time you need to loop
for (int i = 0; i < 3; i++){
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
if(price == 1){
//Copy name in list 1, you can't copy an array of x char in a single case of another array, 1 case of an array = 1 char
strcpy(list1, name);
}
else if(price == 2){
strcpy(list2, name);
}
else if(price == 3){
strcpy(list3, name);
}
else {
printf("Invalid number! \n Give us number 1,2 or 3");
printf("Give me the product \n");
scanf("%s", name);
printf("Give the price \n");
scanf("%u", &price);
}
}
//No need to loop over this 3 time only 1 is enough
printf("%s \n",list1);
printf("%s \n",list2);
printf("%s \n",list3);
}
I add comment over things I changed to make the initial objectives, IDK if it's the right goal but at least you got the same character in input and output, there was many things that wasn't right in your code you simply can't add the hexadecimal value of two character together to overwrite, you got to make something like list[I] = name[I].
And in C since we don't have the string type you got to create an array of char to make one AND BE SURE TO GET THE RIGHT SIZE TO FIT '\0'.
If it's your final exam a friendly advice, train a lot.
Looks like you forgot printf in one of your lines. Change ("Give the price\n"); to printf("give the price\n");.
It should work if I understand your question
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 10
int main(){
int n; //no of products
printf("Enter no. of products: ");
scanf("%d", &n);
char name[n][MAX_LENGTH]; //create multidimensional array to store namme
unsigned int price[n]; //array to store price. index will be similar to name
for (int i = 0; i < n; i++){ //Enter details
printf("Enter name: ");
scanf("%s", name[i]);
printf("Enter price: ");
scanf("%u", &price[i]);
}
int N = n;
while (N > 0){ //Run loop until index bigger than zero
char temp_string[MAX_LENGTH]; //create temporary variable
unsigned int temp_price; //to store values
int max_price_index = 0; //Index where max value is stored
for (int i = 1; i < N; i++){ //start loop from till end to search each value
if(price[i] > price[max_price_index]) //If searched value is bigger thar previous one(default at index 0)
max_price_index = i; //the replace it
}
strcpy(temp_string, name[N - 1]); //in next 7 lines name and price at max index is
strcpy(name[N - 1], name[max_price_index]); //swapped with values at index N (which is last of scope)
strcpy(name[max_price_index], temp_string);
temp_price = price[N - 1];
price[N - 1] = price[max_price_index];
price[max_price_index] = temp_price;
N--; //reduce the index by 1 making last value which was preiously maximum out of scope
}
for (int i = 0; i < n; i++){ //print details
printf("Name: %s\nPrice: %u\n", name[i], price[i]);
}
}

Function creating assertion failure

I'm trying to create a function that will delete an item from an array of structs. When I enter a number (scanf("%d", num)), I get a pop-up saying I have an assertion failure and to abort the program. There was a warning on the indicated line below, but it didn't stop the program from compiling. When the program crashes the error appears on the same line:
void delete_stud(Student* s, int lsize)
{
int num = 0;
printf("What number student in the list would you like to delete?\nStudent number: ");
scanf("%d", num);
// This line ^^^
if (num <= lsize) {
for (int i = num; i <= lsize; i++) {
s[i - 1] = s[i];
}
lsize--;
}
else {
printf("Invalid value entered\n");
exit(0);
}
}
I call the function with:
delete_stud(class_list, lsize);
Any help would be greatly appreciated.
scanf("%d", &num);
Note the ampersand.

Implicit declaration of printf

I'm getting implicit declaration error. Please help. I don't know how to explain it in terms of words, I'd appreciate it very much if you could help me with error. It's my assignment at school and I want to resolve the issue. Please help.
#include<stdio.h>
int printmenu(int *size_of_char);
int get_char(int **size_of_char);
int main() {
int choice = 0, size_of_char;
while (choice == 0) {
printf("Enter the size of the array: ");
scanf("%d", &size_of_char);
if (size_of_char <= 0) {
printf("Invalid input\n");
}
else {choice = printmenu(&size_of_char);
}
}
return 0;
}
int printmenu(int *size_of_char) {
int x;
printf("Menu\n\n");
printf("0. Input characters\n");
printf("1. Shift Elements to Right\n");
printf("2. Combinations of 2 digits\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%d", &x);
if (x == 0) {
get_char(&size_of_char);
}
}
int get_char(int **size_of_char) {
char string[**size_of_char];
for(int i = 0; i < **size_of_char; i++){
printf("Enter value: %c ", i+1);
scanf("%c", &string[i]);
for(int i = 0; i < **size_of_char; i++){
printf("Your grade in subject %d is %c.\n", i+1, size_of_char[i]);
//printf("Your grade in subject %d is %f.\n", i+1, *(grades + i));
}
}
}
Thanks
You've correctly included the header which declares printf in the example that you show.
There are other bugs however:
char string[**size_of_char];
This is ill-formed. The size of an array must be a compile time constant. That expression isn't.
int printmenu(int *size_of_char)
printmenu is declared to return int, but there is no return statement. The behaviour of the program is undefined.
// int **size_of_char
printf("Your grade in subject %d is %c.\n", i+1, size_of_char[i]);
You're trying to print a int* with a wrong format specifier. The behaviour of the program is undefined.

CUDA parallel program flow for Dijkstra Algorithm

the code here is a cuda code and is meant to find shortest pair path using Dijkstra's algorithm.
My code logic works perfectly in a c program, not in Cuda. I'm using 1 block with N threads, N being user entered.
First doubt, every thread has their own copy of variables except the shared variable temp. Correct ?
When i print the results I'm storing all values in array d and print its value which is zero for all. This is possible only if the flow of control does not enter loop after s = threadIdx.x.
Please help, have been debugging this since last 24 Hrs.
Given Input is:
Number of vertices: 4
enter the source,destination and cost of the edge\n Enter -1 to end
Input\n Edges start from Zero : 0 1 1
enter the source,destination and cost of the edge\n Enter -1 to end
Input\n Edges start from Zero : 0 2 5
enter the source,destination and cost of the edge\n Enter -1 to end
Input\n Edges start from Zero : 0 3 2
enter the source,destination and cost of the edge\n Enter -1 to end
Input\n Edges start from Zero : 1 3 4
enter the source,destination and cost of the edge\n Enter -1 to end
Input\n Edges start from Zero : 2 3 7
enter the source,destination and cost of the edge\n Enter -1 to end
Input\n Edges start from Zero : -1 -1 -1
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<sys/time.h>
#define nano 1000000L
__global__ void dijkstras(int *a, int *b, int *n)
{
int i;
int d[10],p[10],v[10];
// d stores distnce/cost of each path
// p stores path taken
// v stores the nodes already travelled to
int k,u,s;
int check =0;
// shared memory on cuda device
__shared__ int temp[20];
for(i=0; i < (*n)*(*n); i++)
{
temp[i] = a[i];
}
check = check + 1;
__syncthreads();
// were passing int s -- node from which distances are calculated
s = threadIdx.x;
for(i=0; i<(*n); i++)
{
d[i]=temp[s*(*n)+i];
if(d[i]!=9999)
p[i]=1;
else
p[i]=0;
v[i]=0;
}
p[s]=0;
v[s]=1;
for(i=0; i<((*n)-1); i++)
{
// findmin starts here
int i1,j1,min=0;
for(i1=0;i1<(*n);i1++)
{
if(v[i1]==0)
{
min=i1;
break;
}
}
for(j1=min+1;j1<(*n);j1++)
{
if((v[j1]==0) && (d[j1]<d[min]))
min=j1;
}
k = min;
// findmin ends here
v[k]=1;
for(u=0; u<(*n); u++)
{
if((v[u]==0) && (temp[k*(*n)+u]!=9999))
{
if(d[u]>d[k]+temp[k*(*n)+u])
{
d[u]=d[k]+temp[k*(*n)+u];
p[u]=k;
}
}
}
//storing output
int count = 0;
for(i = (s*(*n)); i< (s+1) * (*n); i++)
{
b[i] = d[count];
count++;
}
}
*n = check;
}
main()
{
int *a, *b, *n;
int *d_a, *d_b, *d_n;
int i,j,c;
int check = 0;
printf("enter the number of vertices.... : ");
n = (int*)malloc(sizeof(int));
scanf("%d",n);
int size = (*n) * (*n) * sizeof(int);
//allocating device memory
cudaMalloc((void **)&d_a, size);
cudaMalloc((void **)&d_b, size);
cudaMalloc((void **)&d_n, sizeof(int));
a = (int*)malloc(size);
b = (int*)malloc(size);
check = check +1;
for(i=0; i<(*n); i++)
for(j=0; j<=i; j++)
if(i==j)
a[(i*(*n) + j)]=0;
else
a[(i*(*n) + j)]=a[(j*(*n) + i)]=9999;
printf("\nInitial matrix is\n");
for(i=0;i<(*n);i++)
{
for(j=0;j<(*n);j++)
{
printf("%d ",a[i*(*n)+j]);
}
printf("\n");
}
while(1)
{
printf("\n enter the source,destination and cost of the edge\n Enter -1 to end Input\n Edges start from Zero : \n");
scanf("%d %d %d",&i,&j,&c);
if(i==-1)
break;
a[(i*(*n) + j)]=a[(j*(*n) + i)]=c;
}
printf("\nInput matrix is\n");
for(i=0;i<(*n);i++)
{
for(j=0;j<(*n);j++)
{
printf("%d ",a[i*(*n)+j]);
}
printf("\n");
}
check = check +1;
// copying input matrix to device
cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_n, n, sizeof(int), cudaMemcpyHostToDevice);
check++;
struct timeval start,stop;
double time;
int N = *n;
gettimeofday(&start,NULL);
dijkstras<<<1,N>>>(d_a, d_b, d_n);
gettimeofday(&stop,NULL);
time=(double)(stop.tv_sec-start.tv_sec)+(double)(stop.tv_usec-start.tv_usec)/(double)nano;
printf("\n TIME TAKEN: %lf\n",time);
check++;
// copying result from device to host
cudaMemcpy(b, d_b, size, cudaMemcpyDeviceToHost);
cudaMemcpy(n, d_n, sizeof(int), cudaMemcpyDeviceToHost);
check++;
// printing result
printf("the shortest paths are....");
for(i=0; i<(N); i++)
{
for(j=0; j<(N); j++)
{
if(i != j)
printf("\n the cost of the path from %d to %d = %d\n",i,j,b[i*(N) + j]);
}
printf("\n\n");
}
printf("your debug value of check in main is %d\n",check); //5
printf("your debug value of check in device is %d\n",*n); // 1+ 7+ 10
free(a); free(b);free(n);
cudaFree(d_a); cudaFree(d_b);cudaFree(d_n);
}
The root cause of this problem was supplying an uninitialised device variable as a kernel argument. In this kernel call:
dijkstras<<<1,N>>>(d_a, d_b, d_n);
d_n had been allocated memory, but never assigned a value, resulting in undefined behaviour within the kernel.
I would contend this proved hard for the original poster to detect because of a poor design decision in the kernel itself. In this prototype:
__global__ void dijkstras(int *a, int *b, int *n)
n was being used as both an input and an output with two completely different meanings, which made it far harder to detect the problem with the call. If the prototype was:
__global__ void dijkstras(int *a, int *b, int n, *int check)
then the role of n and checkwould be far clearer, and likelihood of making a mistake when calling the kernel and missing it when debugging would be lessened.