Difficulties for printing pyramid pattern of numbers - c++

1
232
34543
I have divided the pattern in two parts. first part is prints increment numbers and second part prints decrement numbers.
1st loop is for printing rows.
2nd loop is for printing spaces. 3rd
loop is for printing increment numbers.
4th loop is for decrement
numbers.
Code works fine up-to the 3rd loop. But the 4th loop is not giving the required output.
#include<stdio.h>
int main()
{
int i,j,n;
scanf("%d",&n);
/*Print row*/
for(i=1;i<=n;i++)
{
/*Printing Spaces*/
for (j = 1; j <= n-i; j++)
{
printf(" ");
}
/*Printing increasing number values*/
for ( int num = i; num <= 2*i-1; num++)
{
printf("%d",num);
}
/*Printing decreasing numbers value*/
for ( int num = 2*i-2; num <= i-1; num++)
{
printf("%d",num);
}
/*New line*/
printf("\n");
}
return 0;
}
Output is :
10
23
345

Welcome to SO.
Your first error was on the your counter on your 4th loop. Your loop should display decreasing numbers but you keep incrementing your counter (that you use to print too).
First error, decrease the counter in the 4th loop.
Second error is your condition on this first loop. You decrease a counter so your condition "While my counter is under a value" can never be false if the counter, at start of the loop, is already before the value. So you have to replace <= by >=.
And after test you will see that i-1 always print one number too far of remove your -1.
Here is your code corrected :
#include<stdio.h>
int main()
{
int i,j,n;
scanf("%d",&n);
/*Print row*/
for(i=1;i<=n;i++)
{
/*Printing Spaces*/
for (j = 1; j <= n-i; j++)
{
printf(" ");
}
/*Printing increasing number values*/
for ( int num = i; num <= 2*i-1; num++)
{
printf("%d",num);
}
/*Printing decreasing numbers value*/
for ( int num = 2*i-2; num >= i; num--)
{
printf("%d",num);
}
/*New line*/
printf("\n");
}
return 0;
}

Related

How to convert a while loop into a for loop?

How do I change this while loop into a for loop?
#include <stdio.h>
int main()
{
int number;
long int factorial = 1;
printf("\nEnter the number:");
scanf("%d", &number);
do {
factorial = factorial * number--;
} while (number > 1);
printf("\nThe factorial is %d",factorial);
}
Suppose you have these parameters:
start value is 0
end value is 42
increase by 2 each loop
Expressed as a while loop:
int counter = 0;
do {
printf("\nCounter is %d", counter);
counter += 2;
} while (counter < 42);
To express as a for loop:
for(int counter = 0; counter < 42; counter += 2) {
// same as inside `while` loop
printf("\nCounter is %d", counter);
}
So it's mostly that all the control stuff - 0, 42, 2 - is in one spot, in the for statement. The rest of your code doesn't need to change, or not change much.

Save first n prime numbers in an array without overwriting it

I'm trying to save first 20 prime numbers that are greater or equal than entered number.
Right now the output is 20 times 997 because values overwrite previous ones. I can't figure out what to do to limit them. When the array is full stop the loop or something so the overwriting won't happen?
bool is_prime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
void fillArr(int arr[20], int num) {
for (int index = num; index <= 1000; index++) { //don't know how to set up
//2nd condition, depends on entered number
if (is_prime(index)) {
//save first 20 prime numbers that are >= num into an array
//Code fills the array with every prime it finds, setting it for all
//values and overwriting any previous primes it has found. Right now
//output would be the same 20 prime numbers closest to index 1000,
//based on second condition
for (int i = 0; i < 20; i++) {
arr[i] = index;
}
}
}
//print test
for (int i = 0; i < 20; i++) {
std::cout << arr[i] << "\t";
}
}
int main() {
int arr[20];
int num;
std::cout << "Enter number: ";
std::cin >> num;
fillArr(arr, num);
return 0;
}
In your code, initialize i to 0 at the beginning. Each time you encounter a prime, add it to your array and increment i. Break when i >= 20.
void fillArr(int arr[20], int num) {
int i = 0;
for (int index = num; index <= 1000 && i < 20; index++) {
if (is_prime(index)) {
arr[i++] = index;
}
}
//print test
for (int i = 0; i < 20; i++) {
std::cout << arr[i] << "\t";
}
}
Also note that this is not the most optimal way to find primes. For finding whether a given number is prime, you only need to check for whether it is divisible by primes uptil square root of the number (and not till n/2). You may also want to read about the Seive of Eratosthenes.
As also specified in the comments, it's better to use std::vector or std::array rather than raw arrays. In that case, you'd simply want to push_back(index) and break when vector's size >= 20.

How to use nested loop using recursion and check the sum of digits in c++

I want to calculate the number of occurence of a particular sum of digits in a k digit number. My code is
long recur(long k, long n)
{
long count = 0;
if(k == 0)
{
return 0;
}
for(long i = 1; i <= 9 ; i++)
{
long c = i + recur(k - 1, n);
if(c == n)
{
count++;
}
}
return count;
}
/* k is the number of digits and n is the sum of digits i want to find. for example, if k is 3, then we can have numbers from 111 to 999 where sum of digits varies from 1+1+1=3 to 9+9+9=27. If I want to find the number of k=3 digit numbers with sum(n)=4, then answer is 3. Because only 112,121 and 211 are possible solutions.*/
It is not giving me correct answer.The output always is 1. Any help would be appreciated.
Try this out
long recur(long k, long n) {
if(k==0) return n==0;
long count=0;
for(long i=1; i<=9; ++i) {
count += recur(k - 1, n - i);
}
return count;
}

C++ finding all prime numbers from 1 to a number entered

So the point is to have the program find and list all prime numbers between 1 and the number you enter. I'm using number_test as the number tested for prime, and divisor and the number to divide by.
I'm not sure what's wrong, as to me it looks functionally the same as the program posted here: Printing prime numbers from 1 through 100
with some minor changes (inputting a number, changing "i" to less than the number entered).
I've been looking for the past three or four days, and I haven't found anything that really answers this question fully, to the degree I need for class. Any help is much appreciated.
#include iostream
#include conio.h
using namespace std;
void main(void){
//Declare variables
int number_entered;
//Get inputs
cout << "This program lists all prime numbers from 1 through a positive number entered."
<< endl;
cout << "Please enter a positive integer."
<< endl;
cin >> number_entered;
cout << "Displaying all numbers from 1 to " << number_entered
<< endl
<< "Press any key to continue..."
<< endl;
getch();
for(int number_test = 2; number_test < number_entered; number_test++){
for(int divisor = 2; divisor < number_test; divisor++){
if(number_test % divisor == 0){
break;
}
else if(number_test % divisor != 0){
cout << number_test << " ";
break;
}
}
}
getch();
}
You should use the Sieve of Eratosthenes to compute the primes less than n. Begin by making a list of all numbers from 2 to the maximum desired prime n. Then, at each iterative step, the smallest remaining number that hasn't yet been considered is output and all of its multiples are crossed off the list.
function primes(n)
sieve := makeArray(2..n, True)
for p from 2 to n step 1
if sieve(p)
output p
for i from p*p to n step p
sieve[i] := False
This O(n log log n) algorithm is very fast; you should be able to compute the 78498 primes less than a million in less than a second.
A simple C++ Program to find the "N" prime numbers.
#include <iostream >
using namespace std;
int main()
{
int N;
cin >> N;
for (int i = 2; N > 0; ++i)
{
bool isPrime = true ;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false ;
break ;
}
}
if (isPrime)
{
--N;
cout << i << "\n";
}
}
return 0;
}
Just a small suggestion. Since prime numbers are odd, even numbers can be left out.
For example, in below loops, i and j increase by 2 (i +=2) instead of by 1 (i ++).
for (int i=3;i<=numberByUser; i+=2){
for (j=3;j<=i;j +=2){
if (i%j==0){
break;
}
}
i think in your answer any way one time the loop will terminated(i am talking about the loop checking the whether it is prime or not)once it comes out you don't know whether it made the break or not.So try to make a flag variable and check outside.I ope that will work
for(n=lower+1; n<upper; n++)
{
prime = 1;
for(i=2; i<n; i++)
if(n%i == 0)
{
prime = 0;
break;
}
if(prime)
printf("\n\n\t\t\t%d", n);
}
for(int number_test = 2; number_test < number_entered; number_test++){
for(int divisor = 2; divisor < number_test; divisor++){
if(number_test % divisor == 0){
break;
}
else if(number_test % divisor != 0){
cout << number_test << " ";
break;
}
}
}
The above code will not show you the prime numbers, it will just show you the number you entered if/when you run into a divisor that is not a factor of the number. For example, if you enter "9", you will start at 2, which is not a factor of 9, so you will show "9" (incorrectly) as a "prime", when it is not.
The easiest method for testing if a number is a prime is by checking all prime numbers below it's square root to see if they are factors of the given number. If none of them are (then none of the non-prime numbers below the given number will be either), the number is a prime number. If it has at least one prime factor less than or equal to it's square root, it is not prime.
Since you are looking to show all primes in a range of [0, X], you can simply check your list of factors as you go along (or do it in reverse, which is effectively what the Sieve of Eratosthenes does).
When my point was like your one, I wrote this code, it worked. Hope it will help you.
#include <cstdio>
#include <vector>
using namespace std;
vector <int> sn;
bool isPrime(int n) {
if (n <= 1) {
return 0;
}
if (n == 2) {
return true;
}
if (!(n % 2)) {
return false;
}
for (int i = 2; i*i <= n; i++) {
if (!(n % i)) {
return 0;
}
}
return 1;
}
void primeNumbers(int k) {
sn.push_back (2);
int i = 3, j = 1;
for ( ; j < k + 1; i += 2 && j++) {
if (isPrime(i)) {
sn.push_back(i);
}
}
}
int main() {
int i, k;
scanf("%d", &k);
primeNumbers(k);
for (i = 0; i < sn.size(); i++) {
printf("%d ", sn[i]);
}
return 0;
}
int getNumberOfPrimes(int N) {
bool *numbers = new bool[N-1]();
for (int i = 2; i <= N/2; ++i) {
if (numbers[i-2] == true) continue;
for (int j = i+i; j <= N; j = j+i) {
numbers[j-2] = true;
}
}
int count = 0;
for (int i = 0; i < (N-1); ++i) {
if (numbers[i] == false) ++count;
}
delete []numbers;
return(count);
}
Man I guess I have the simplest methode of this all. Hope it works for you!
#include < iostream >
using namespace std;
int main()
{
int n, i, j
cin>>n; //The max limith
for(i=2; i<=2; i++)
{
for(j=1; j<=i/2; j++)
if(i%j!=o)
cout<<i;
}
return 0;
}
If a number has divisors, at least one of them must be less than or equal to the square root of the number. When you check divisors, you only need to check up to the square root, not all the way up to the number being tested.

explain this prime number program [C]

#include<stdio.h>
main()
{
int n;
int a,b,flag=1;
scanf("%d",&n);
for(a=2; a<=n; a++)
{
if(n % a == 0)
{
printf("not prime");
flag = 0;
break;
}
}
if(flag == 1)
{
printf("is prime");
}
getch();
}
when you use this for loop
for(a=2; a<=n; a++)
when user will input 2 it will print "not prime:
if you put that if(flag == 1) statement inside the for loop it doesn't print anything when the user inputs 2. Why is that if(flag == 1) outside that for loop
#include<stdio.h>
main()
{
int i, num, flag = 1;
scanf("%d",&num);
for(i=2; i<=sqrt(num); i++)
{
if(num%i==0)
{
printf("not prime");
flag=0;
break;
}
}
if(flag==1)
{
printf("is prime");
}
getch();
}
when you will use square root in for loop
for(i=2; i<=sqrt(num); i++)
then it give correct result
if you enter 2 then it prints 2 is prime number
WHY ?
and what is flag variable how does it work ?
The problem is that this line is wrong:
for(a=2; a<=n; a++)
It should be this:
for(a=2; a<n; a++)
Because n is always divisible by itself it will mean that n % a == 0 when a is n. This does not mean the number is not prime. A prime is exactly divisible by 1 and itself, but no other integer.
When you change the test to a <= sqrt(num) you also happen to fix this bug.
for(a=2; a <= n; a++)
should be
for(a=2; a < n; a++)
//^ difference
Also, when you use sqrt(n), you better write this outside the loop to improve performance:
int m = sqrt(n); //store the result in int type
for(a=2; a <= m ; a++)
In this way, you calculate sqrt(n) just ONCE, instead of in every iteration, and instead of relying on the compiler to optimize this step.