After taking ten numbers as input from the user, I want to add up the ones that are evenly divisible by 2.
I am able to get the input from the user, but I'm not sure how to check which numbers are divisible by two, and add only those.
#include <stdio.h>
#include <ctype.h>
int main(void) {
int i = 0;
int val;
char ch;
int numbers[10];
while(i < 10) {
val = scanf("%d%c", numbers + i, &ch);
if(val != 2 || !isspace(ch)) {
while((ch = getchar()) != '\n') // discard the invalid input
;
printf("Error! Entered number is not an integer.\n");
printf("Please enter an integer again.\n");
continue;
}
++i;
}
printf("%d\n", numbers[0]);
printf("%d\n", numbers[1]);
printf("%d\n", numbers[2]);
printf("%d\n", numbers[3]);
printf("%d\n", numbers[4]);
printf("%d\n", numbers[5]);
printf("%d\n", numbers[6]);
printf("%d\n", numbers[7]);
printf("%d\n", numbers[8]);
printf("%d\n", numbers[9]);
return 0;
}
How about:
int sum = 0;
for (int i = 0; i <= 9; i++)
{
if (numbers[i] % 2 == 0)
sum += numbers[i];
}
completely unnecessary optimization
int sum[2]={0};
for(size_t i = 0; i <=9; ++i) sum[numbers[i]&1]+=numbers[i];
int main(void)
{
int i;
int numbers[10];
int sum = 0;
for(i=0; i<10; ++i)
{
printf("Enter #%d:\n", i+1);
scanf("%d", numbers+i);
if (numbers[i] % 2 == 0) // Then Number is even
{
sum += numbers[i];
}
}
printf("The sum of only the even numbers is %d\n", sum);
getch();
return 0;
}
Related
I want to input an array of integers then print out the even numbers from the inputted numbers..
example is if I input 2466688992,
it will output 24666882;
I have a my code below:
#include<stdio.h>
int main()
{
int a[5],i;
printf("Enter array of numbers: ");
scanf("%d",&a);
for(i=0; i<sizeof(a); i++){
if(a[i]%2==0)
printf("%d",a[i]);
}
getch();
return 0;
}
It resulted into garbage : 2468000075416640419940000004225568000
This is the function that prints even numbers in an integer :
#include<stdio.h>
int main(){
int num,rem,even=0,digit;
printf(" Enter an integer number: ");
scanf("%d",&num);
printf("\n The even digits present in %d are \n",num);
while(num>0){
digit = num % 10;
num = num / 10;
rem = digit % 2;
if(rem == 0)
even++;
printf("\n %d.",digit);
}
return 0;
}
You should scan the array as a string (unless you want to impose the number of items in the array), and then parse the string to store the different numbers:
long a[50];
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
int j = 0;
for (int i = 0; i < len; ) {
long sign = 1;
long n = 0;
if (buf[i] == '+') {
++i;
}
else if (buf[i] == '-') {
sign = -1;
++i;
}
if (isdigit(buf[i])) {
while (isdigit(buf[i])) {
n = 10 * n + buf[i++] - '0';
}
a[j] = n * sign;
}
else
i++;
}
for (int i = 0; i < j; i++)
if (!(a[i] ℅ 2)) // true if even
printf("%ld ", a[i]);
This will store all your digits in your array a of size j.
Edit: if you are talking about digits then its easier:
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
for (int i = 0; i < len; i++)
if (isdigit(buf[i]) && !((buf[i] - '0') ℅ 2)) // true if even, note that '0' equals 0x30 so there is no need to sub it to check for odd/even in reality.
printf("%c ", buf[i]);
I'm trying to make a C program to insert elements into an array until user inputs a 0 or less number, as the title says. But when I print the array out, it doesn't show the numbers I inputted. I have tried using a while as well as do-while loops but without success.
#include <stdio.h>
int main() {
int data[100];
int i;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
int n = sizeof(data[i]);
for (int i = 0; i < n; i++) {
printf("%d ", &data[i]);
}
}
Try this:
#include <stdio.h>
int main() {
int data[100];
int i;
int counter = 0;
for (i = 0; i < 100; i++) {
printf("Input your number:\n");
scanf("%d", &data[i]);
counter++;
if (data[i] <= 0) {
break;
}
}
printf("Your array:");
for (int j = 0; j < counter - 1; j++) {
printf("%d ", data[j]);
}
}
The problem was that you had printf("%d ", &data[i]); instead of printf("%d ", data[i]);.
And also you've trying to get the sizeof() of an element data[i], not the size of the whole array. That's why there's counter in my code.
int n = sizeof(data[i]);
this is wrong, you want
int n = i;
sizeof(data[i]) gives you the size of an int (4 on my machine)
On the other hand, you need to check the result of scanf, if a bad input is entered do not increment the counter, something like:
int i = 0;
while (i < 100)
{
int res = scanf("%d", &data[i]);
if (res == EOF)
{
break;
}
if (res == 1)
{
if (data[i] <= 0)
{
break;
}
i++;
}
else
{
// Sanitize stdin
int c;
while ((c = getchar()) != '\n');
}
}
Finally, scanf wants a pointer to the object, but this is not the case of printf:
printf("%d ", &data[i])
should be
printf("%d ", data[i])
I need to make a program that stores numbers inside of an array. But it must have no duplicate elements.
int x;
int z[8];
for( x = 0; x<8;x++)
printf("number: ");
scanf("%d",&z[x]);
}
for( x=0;x<8;x++) {
printf("%d ",z[x]);
}
First, initialize the array, so that you do not end up reading an uninitialized value and fail the test.
int user_nums[6] = {0};
Next, you need to have another check in the for loop, to read the number again if it is a duplicate.
The code will look like this.
#include<stdio.h>
int main(){
int x,y;
int exists = 0;
int user_nums[6] = {0};
for( x = 0; x<6;x++){//for loop to get the players selected numbers
do {
exists = 0;
printf("Enter a number(from the #'s 1-42): ");
scanf("%d",&user_nums[x]);
for(y =0; y < x; y++) { //to check for duplicates
if (user_nums[x] == user_nums[y])
{
printf("Number already exists\n ");
exists = 1;
break;
}
}
}while (user_nums[x]<1 || user_nums[x]>42 || exists);//accepts only numbers from 1-42 which are not duplicates (continous to ask you for a number until condition is met).
}
printf("Your numbers: \n");
for( x=0;x<6;x++){
printf("%d ",user_nums[x]); // prints the numbers you inputed.
}
return 0;
}
The following code could work in O(n):
#include<stdio.h>
int main()
{
int user_nums[6];
int index[50];
for (int i = 0; i != sizeof(index) / sizeof(index[0]); ++i)
index[i] = -1;
for (int i = 0; i < sizeof(user_nums) / sizeof(user_nums[0]); ++i) {
for (;;) {
printf("Enter a number(from the #'s 1-42): ");
scanf("%d", user_nums + i);
if (user_nums[i] < 1 || user_nums[i] > 42) {
printf("wrong number\n");
continue;
}
if (index[user_nums[i]] != -1) {
printf("dump number\n");
continue;
}
index[user_nums[i]] = i;
break;
}
}
printf("Your numbers: \n");
for(int i = 0; i < 6; ++i)
printf("%d ", user_nums[i]);
return 0;
}
This question already has answers here:
Variable leading zeroes in C99 printf
(1 answer)
printf string, variable length item
(2 answers)
Closed 5 years ago.
I've written a programm for college where I print out all prime number twins between two numbers. (f.e. between 1 and 12000)
In my printing statement i've written %04d for 4 digits. But what i want to do is to make this variable. (I tried %0%dd, but this didnt work.) I dont want to do write just the max digit count of int. I count hte digits of the int with int count = floor(log10(abs(b))) + 1;
Heres my complete code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int isPrime(int a);
void listOfPrimeNumberTwins(int a, int b);
typedef int twins[10000][2];
int main(){
int a;
int b;
printf("Check if prime:\nEnter number: ");
scanf(" %d", &a);
b = isPrime(a);
if (b == 0){
printf("No Prime!");
} else if (b == -1){
printf("Negative number!");
} else {
printf("Prime!");
}
printf("\nPrime Number Twins:\nEnter number 1: ");
scanf(" %d", &a);
printf("Enter number 2: ");
scanf(" %d", &b);
listOfPrimeNumberTwins(a,b);
}
int isPrime(int a){
int i;
int b = 0;
if (a == 1){
return 0;
}
if (a <= 0){
return -1;
}
for (i = 2; i < a; i++){
if (a % i == 0){
return 0;
}
}
return 1;
}
void listOfPrimeNumberTwins(int a, int b){
int count = floor(log10(abs(b))) + 1;
int i;
int j = 0;
twins c;
b -= 1;
for (i = a; i < b; i++){
if (i > 1 && isPrime(i) == 1 && isPrime(i + 2) == 1){
c[j][0] = i;
c[j][1] = i + 2;
j += 1;
}
}
if (j == 0){
printf("No Prime number twins between %d and %d!", a,b);
} else {
printf("Prime number twins between %d and %d:\n", a,b);
for (i = 0;i < j; i++){
printf("%04d\t<-->\t%04d\n", c[i][0],c[i][1]);
}
}
}
How can I achieve what I want? Or is it just impossible like I want it?
I'm having trouble determining if two words entered are anagrams.
#include <stdio.h>
#include <string.h>
int main() {
char ch;
int letter_count[26] = {0};
int i;
int sum = 0;
printf("Enter first word: ");
do
{
scanf("%c", &ch);
letter_count[ch - 'a']++;
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
printf("\n");
printf("Enter second word: ");
do
{
scanf("%c", &ch);
letter_count[ch - 'a']--;
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
for(i = 0; i < 26; i++)
if(letter_count[ch] != 0)
sum++;
if (sum == 0)
printf("anagrams");
else
printf("not anagrams");
}
I have to use the do while part of the code. I can enter the two words, and it prints out the elements in the array, so that "Mattress" and "Smartest" together would have all the elements be zero. However, I'm having trouble with the last part, which is to use a third loop to check whether all the elements are zero.
I figured I could declare an int before hand and have it increment whenever an element wasn't zero, and I could just have any sum greater than zero not be an anagram. However, it always prints out anagram for me.
In your third loop, using letter_count[ch] will not check the entire array. You should iterate through the array using the loop variable i. That part of the code should be:
for (i=0; i<26; i++)
if (letter_count[i] != 0)
sum++;
To handle both upper case and lower case letters, use topper() or to lower() in <ctype.h> to avoid out-of-bound access.
#include <stdio.h>
#include <string.h>
#include <ctype.h> // <---
int main() {
char ch;
int letter_count[26] = {0};
int i;
_Bool bad = 0;
printf("Enter first word: ");
do
{
scanf("%c", &ch);
if(!isalpha(ch)) // <---
{
puts("Not a letter");
continue;
}
letter_count[tolower(ch) - 'a']++; // <---
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
printf("\n");
printf("Enter second word: ");
do
{
scanf("%c", &ch);
if(!isalpha(ch)) // <---
{
puts("Not a letter");
continue;
}
letter_count[tolower(ch) - 'a']--; // <---
} while (ch != '\n');
for(i = 0; i < 26; i++)
printf("%d ", letter_count[i]);
printf("\n"); // <---
for(i = 0; i < 26; i++)
if(letter_count[i] != 0)
{
bad = 1;
break; // <---
}
if (bad == 0)
printf("anagrams");
else
printf("not anagrams");
}
Take a look at all places marked // <---.