Is there any way to write this program by only using if-else, else if statements instead of using while.
And I also want all the inputs just in one line, instead of
enter the number1:
enter the number2:
enter the number3:
enter the number4:
enter the number5:
it should be like
Enter 5 numbers: _ _ _ _ _
And when I write the same largest number twice, I want this program to show me the largest number as the second-largest number, too.
For example:
Enter 5 integers: -88 53 41 53 -17
The largest one is: 53
The second largest one is: 53
53 is the multiple of 53
53 and 53 is equal to each other.
53 is an odd number.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int sayi = 0;
int sayac = 1;
printf("Sayiyi Girin:");
scanf("%d", &sayi);
//ilk sayinin en buyuk oldugunu kabul ediyoruz.
int enbuyuk = sayi;
int ikinci_buyuk = sayi;
while (sayac != 5)
{
sayac++;
printf("Sayiyi Girin:");
scanf("%d", &sayi);
/*kitapligi ilk sayinin en buyuk oldugunu farz ediyor
* eger ikinci sayi daha buyukse buyuk olanın yerini alacak
* ayrica ikincisinide kontrol edecek
*/
if (sayi > enbuyuk)
{
ikinci_buyuk = enbuyuk;
enbuyuk = sayi;
}
else if (sayi < enbuyuk)
{
// This to avoid if numbers are arranges descending
if (sayac == 2)
{
ikinci_buyuk = sayi;
}
else if (sayi > ikinci_buyuk)
{
ikinci_buyuk = sayi;
}
//This to avoid if the user entered two equal numbers
else if (enbuyuk == ikinci_buyuk)
{
ikinci_buyuk = enbuyuk;
}
}
}
printf("sayac: %d\n", sayac);
printf("En buyuk sayi: %d\n", enbuyuk);
printf("İkinci en buyuk sayi: %d\n", ikinci_buyuk);
if (enbuyuk % ikinci_buyuk != 0)
{
printf("%d %d nin tam kati degildir. is not the multiple of", enbuyuk, ikinci_buyuk);
}
else
{
printf(" %d %d nin tam katidir. is the multiple of", enbuyuk, ikinci_buyuk);
}
if (enbuyuk != ikinci_buyuk)
{
printf(" %d ve %d birbirine esit degildir. not equal each other", enbuyuk, ikinci_buyuk);
}
else
{
printf(" %d ve %d birbirine esitir. equal each other", enbuyuk, ikinci_buyuk);
}
if (enbuyuk % 2 != 0)
{
printf("%d tek sayidir. odd number", enbuyuk);
}
else
{
printf("%d cift sayidir.even number", enbuyuk);
}
system("pause");
return 0;
}
From the title of your question:
if-else are a conditional code flow structure without any repetition. Without any other instruction (like goto for example) you can't make it a loop like while.
But I think this is not the core of your question. You seem to want to read 5 numbers and check them. For now you do this in a loop and you like to replace that loop with something else.
You can print the one and only prompt and then call a function for each of the 5 numbers to check them.
Since your variables are not translated and your intend is not clear, I'll leave the code inside the function as an exercise for you.
printf("Enter 5 integers: ");
for (int i = 1; i <= 5; ++i)
{
readnumber(/* you might need arguments */);
}
The function will read and check one number. scanf() will read just one number and leave the remainder of the input line for some next call.
void readnumber(/* see above */)
{
if (scanf("%d", &number) == 1)
{
/* handle the number */
}
else
{
/* handle the scan error */
}
}
You can read 5 numbers simply by prompting with a single printf() and reading into 5 variables, or 5 array elements with a single scanf():
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a[5];
int first, second, i, j;
printf("Enter 5 numbers: ");
if (scanf("%d%d%d%d%d", &a[0], &a[1], &a[2], &a[3], &a[4]) != 5) {
printf("Invalid input\n");
return 1;
}
/* I cannot adapt the rest of the code because I cannot understand your language */
/* Here is my quick implementation from the desired output */
/* select the 2 largest numbers */
for (i = 0; i < 2; i++) {
for (j = i + 1; j < 5; j++) {
if (a[i] < a[j]) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
first = a[0];
second = a[1];
printf("The largest one is: %d\n", first);
printf("The second largest one is: %d\n", second);
if (second != 0 && first % second == 0)
printf("%d is a multiple of %d\n", first, second);
if (first == second)
printf("%d and %d are equal\n", first, second);
if (first % 2 != 0)
printf("%d is an odd number.\n", first);
return 0;
}
Related
#include <stdio.h>
main()
{
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
if(i==1) //for 1st
printf("1st value : ");
else if (i<=2) //2nd
printf("2nd value : ");
else if (i<=3) //3rd
printf("3rd value : ");
else //else print th ordinal
printf("%dth value : ", i);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
A program to take out the average of n numbers.
Now, this code does what it should, but if the size of the array goes beyond 20, it prints 21th, 22th, 23th and so on, which is wrong. I can't think of how to fix this problem. Any help would be great. I am new to programming, so pardon my ignorance.
There isn't a standard function that does that. You can write one, or use mine:
ordinal.c
#include "ordinal.h"
#include <stdio.h>
static const char *const suffixes[4] = { "th", "st", "nd", "rd" };
enum { NUM_SUFFIXES = sizeof(suffixes) / sizeof(suffixes[0]) };
static unsigned suffix_index(unsigned n)
{
unsigned x;
x = n % 100;
if (x == 11 || x == 12 || x == 13)
x = 0;
else if ((x = x % 10) > 3)
x = 0;
return x;
}
char *fmt_ordinal(char *buffer, size_t buflen, unsigned n)
{
unsigned x = suffix_index(n);
int len = snprintf(buffer, buflen, "%u%s", n, suffixes[x]);
if (len <= 0 || (size_t)len >= buflen)
return 0;
return(buffer);
}
ordinal.h
/* returns buffer or 0 on failure (implausible unless buffer too small) */
extern char *fmt_ordinal(char *buffer, size_t buflen, unsigned n);
Some of that is overkill on its own, but the source file also contains scn_ordinal() which scans ordinal numbers with greater or lesser strictness, and the header declares it.
int main(void)
{
char buffer[15];
/* Test fmt_ordinal() */
for (unsigned i = 0; i < 35; i++)
printf("%2u => %4s\n", i, fmt_ordinal(buffer, sizeof(buffer), i));
return 0;
}
You can mod by 10 to get the last digit. Then based on that you can use "st", "nd", "rd", or "th". You'll also need special cases for 11, 12, and 13.
if ((i % 10 == 1) && (i % 100 != 11))
printf("%dst value : ", i);
else if ((i % 10 == 2) && (i % 100 != 12))
printf("%dnd value : ", i);
else if ((i % 10 == 3) && (i % 100 != 13))
printf("%drd value : ", i);
else
printf("%dth value : ", i);
I played with this a bit and this was my minimal 'lookup' except, sadly, for the expense of the modulo division. I wasn't fussed about values above 99.
if( i > 20 ) i %= 10; // Change 21-99 to 1-10.
if( i > 3 ) i = 0; // Every other one ends with "th"
// 0 1 2 3
suffix = &"th\0st\0nd\0rd"[ i * 3 ]; // Acknowledge 3byte regions.
You can use 'suffix' as a pointer to a normal null terminated string.
It is okay to be a beginner, no need to apologize. You can solve your problem using a combination of a SWITCH statement and the modulus operator (%). The modulus operator takes two numbers (n1 % n2) and returns the remainder when n1 is divided by n2.
You will want to construct an array of ordinals, like this:
char *ordinalList[] = { "st", "nd", "rd", "th" };
This will allow you to simply reference this array to append the correct ordinal to a number. The next step is to create an algorithm to determine which array index should be referenced. To do this, you can make a new function and call it in your "main".
char *determineOrdinal (char **ordinalList, int numValue)
{
if (3 < numValue && numValue < 21)
return ordinals[3];
switch (numValue % 10) {
case 1 : return ordinalList[0];
break;
case 2 : return ordinalList[1];
break;
case 3 : return ordinalList[2];
break;
default: return ordinalList[3];
break;
}
You can pass a number into this function as the numValue argument. Your "main" function might look something like this:
#include <stdio.h>
int main(void)
{
char *ordinalList[] = { "st", "nd", "rd", "th" };
char *currentdOrdinal;
int i, num, sum=0; //declaration
printf("How many numbers do you want to calculate average of?\n");
scanf("%d", &num); //how many numbers are to be calculated
printf("Enter %d numbers\n", num);
int a[num]; //array to store data
for(i=1;i<=num;i++) //loop to take input
{
currentdOrdinal = determineOrdinal (ordinalList, i)
printf("%d%s value : ", i, currentdOrdinal);
scanf("%d", &a[i]);
}
for(i=1;i<=num;i++)
sum+=a[i];
float avg;
avg=sum/num;
printf("Average : %f", avg);
return 0;
}
I think that code should work for you. I hope this helps.
i want to create a program which prints biggest first number and biggest second number when i enter 5 number.(1.value of the number is=0) .there is no problem when i enter 5 numbers bigger than 0, but when i enter 5 numbers smaller than 0 , program prints first biggest number is 0 and second biggest number is 1.
#include <stdio.h>
int main() {
int number = 0, first, second, numbercounter = 0;
first = number;
while (numbercounter < 5) {
printf("5 tamsayi girin:", ++numbercounter);
scanf("%d", &number);
if (number > first) {
second = first;
first = number;
} else if (number > second)
second=number;
}
printf("En buyuk sayi: %d \n", first);
printf("En buyuk ikinci sayi:%d \n", second);
if (first % second == 0) {
printf("%d, %d'nin tam katidir.\n", first, second);
} else {
printf("%d, %d'nin tam kati degildir.\n", first, second);
}
if (first == second) {
printf("%d ve % esittir.\n", first, second);
} else {
printf("%d ve %d esit degildir.\n", first, second);
}
if (first % 2 != 0) {
printf("%d tektir.\n", first);
} else {
printf("%d cifttir.\n", first);
}
return 0;
}
There are two problems:
first starts out as 0. If number is negative, if (number > first) is false.
second is used uninitialised if number <= first.
Use INT_MIN for your initial values, this is the most negative integer you can have. Use this declaration
#include <stdio.h>
#include <limits.h>
int main()
{
int number = 0, first = INT_MIN, second = INT_MIN, numbercounter = 0;
Also get rid of the line
first = number;
I wanna organize a set of integers by putting prime numbers into one subset.
For example:
Input set:
{2,4,6,7,11,6,3}.
Desired result:
Prime numbers: {2,7,11,3}.
Non prime numbers: {4,6,6}.
This is my reasonable code that ended up with a ridiculous result:
#include <stdio.h>
int main() {
int i,j,n,a=0,b1=0,b2=0;
printf(" Enter the number of elements in the set: ");
scanf("%d",&n);
int integer[n],nonPrime[n],prime[n];
for(i=1;i<=n;i++) {
printf(" Enter #%d element of the set: ",i);
scanf("%d",&integer[i-1]);
}
printf("\n The set is: {");
for(i=1;i<=n;i++) {
printf("%d ",integer[i-1]);
}
printf("}");
for(i=1;i<=n;i++) {
for(j=2;j<=integer[i-1]/2;j++) {
if(integer[i-1]%j==0) {
a=1;
break;
}
}
if(a==1) {
integer[i-1]=nonPrime[i-1];
b1++;
}
else {
integer[i-1]=prime[i-1];
b2++;
}
}
printf("\n Prime numbers: { ");
for(i=1;i<=b2;i++) {
printf("%d ",prime[i-1]);
}
printf("}\n Non prime numbers: { ");
for(i=1;i<=b1;i++) {
printf("%d ",nonPrime[i-1]);
}
printf("} \n");
return 0;
}
//HENG SOK MENG
The output:
Enter the number of elements in the set: 6
Enter #1 element of the set: 1
Enter #2 element of the set: 3
Enter #3 element of the set: 5
Enter #4 element of the set: 7
Enter #5 element of the set: 4
Enter #6 element of the set: 6
The set is: {1 3 5 7 4 6 }
Prime numbers: { 1965421290 1965972381 718360966 32 }
Non prime numbers: { 2686560 718361022 }
Process returned 0 (0x0) execution time : 6.063 s
Press any key to continue.
I think your logic is slightly wrong. This code shows that your loops can be simplified to for (i = 0; i < n; i++), which will allow indexing over [i], instead of [i-1].
You can use a helper function like isprime(int n) to check for prime numbers in the integers[n] array, then add to the other corresponding partitioned arrays accordingly.
This code segment demonstrates this:
#include <stdio.h>
#include <stdlib.h>
int isprime(int n);
int
main(void) {
int n, i, primecnt = 0, nonprimecnt = 0;
printf("Enter the number of elements in the set: ");
if (scanf("%d", &n) != 1) {
printf("Invalid entry\n");
exit(EXIT_FAILURE);
}
int integers[n], prime[n], nonprime[n];
for (i = 0; i < n; i++) {
printf(" Enter #%d element of the set: ",i+1);
if (scanf("%d", &integers[i]) != 1) {
printf("Invalid entry\n");
exit(EXIT_FAILURE);
}
}
printf("\n The set is: {");
for(i = 0;i < n; i++) {
printf("%d ",integers[i]);
}
printf("}");
for (i = 0; i < n; i++) {
if (isprime(integers[i])) {
prime[primecnt++] = integers[i];
} else {
nonprime[nonprimecnt++] = integers[i];
}
}
printf("\n Prime numbers: { ");
for(i = 0; i < primecnt; i++) {
printf("%d ", prime[i]);
}
printf("}\n Non prime numbers: { ");
for(i = 0; i < nonprimecnt; i++) {
printf("%d ",nonprime[i]);
}
printf("} \n");
return 0;
}
int
isprime(int n) {
int divisor;
if (n < 2) {
return 0;
}
for (divisor=2; divisor*divisor<=n; divisor++) {
if (n%divisor==0) {
return 0;
}
}
return 1;
}
Oh, there are some issues in your code:
As says user2052592, you exchanged the left-hand side of the assignment operator = with the right-hand side.
You used the same variable (i) for indexing array integer[] as arrays prime[] and nonPrime[] but they are not synchronized (e. g. the 5th integer may be the 2nd prime).(What about using directly your b1 for nonPrime[] and b2 for prime[]?)
You set your variable a for non-primes (by a = 1) but you never reset it after using it (by a = 0). (Note: You chose very nice name for this variable, as for many others.)
You logic for deciding if the number is prime is simple but incorrect. The inner loop (for j) never executes for numbers 1, 2, and 3.
I did minimal changes in your code to comprise fixes of these issues.
So please replace the second part of your code with this:
for(i=1;i<=n;i++) {
for(j=2;j<=integer[i-1]-1;j++) {
if(integer[i-1]%j==0) {
a=1;
break;
}
}
if(a==1 || integer[i-1] == 1) {
nonPrime[b1]=integer[i-1];
b1++;
}
else {
prime[b2]=integer[i-1];
b2++;
}
a = 0;
}
printf("\n Prime numbers: { ");
for(i=0;i<b2;i++) {
printf("%d ",prime[i]);
}
printf("}\n Non prime numbers: { ");
for(i=0;i<b1;i++) {
printf("%d ",nonPrime[i]);
}
printf("} \n");
return 0;
}
I tested it and now it works OK. In spite of it is ugly - but predominantly yours, so you will understand it.
Check LHS & RHS in
integer[i-1]=nonPrime[i-1]
integer[i-1]=prime[i-1]
I'm self-studying C and I'm trying to make 2 programs for exercise:
the first one takes a number and check if it is even or odd;
This is what I came up with for the first one:
#include <stdio.h>
int main(){
int n;
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
return 0;
}
the second one should take n numbers as input and count the number of even numbers, odd numbers, and zeros among the numbers that were entered. The output should be the number of even numbers, odd numbers, and zeros.
I would like to ask how to implement the loop in this case: how can I set an EOF value if every integer is acceptable (and so I cannot, say, put 0 to end)? Can you show me how to efficiently build this short code?
#include <stdio.h>
int main(void) {
int n, nEven=0, nOdd=0, nZero=0;
for (;;) {
printf("\nEnter a number that you want to check: ");
//Pressing any non-numeric character will break;
if (scanf("%d", &n) != 1) break;
if (n == 0) {
nZero++;
}
else {
if (n % 2) {
nEven++;
}
else {
nOdd++;
}
}
}
printf("There were %d even, %d odd, and %d zero values.", nEven, nOdd, nZero);
return 0;
}
Check the return value of scanf()
1, 1 field was filled (n).
0, 0 fields filled, likely somehtlig like "abc" was entered for a number.
EOF, End-of-file encountered (or rarely IO error).
#include <stdio.h>
int main(void) {
int n;
for (;;) {
printf("Enter a number that you want to check: ");
if (scanf("%d",&n) != 1) break;
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
}
return 0;
}
Or read the count of numbers to subsequently read:
int main(void) {
int n;
printf("Enter the count of numbers that you want to check: ");
if (scanf("%d",&n) != 1) Handle_Error();
while (n > 0) {
n--;
printf("Enter a number that you want to check: ");
int i;
if (scanf("%d",&i) != 1) break;
if((i%2)==0) {
if (i == 0) printf("%d is zero.\n",i);
else printf("%d is even and not 0.\n",i);
}
else
printf("%d is odd.\n",i);
}
return 0;
}
hey look at this
#include<stdio.h>
#include<conio.h>
void main()
{
int nodd,neven,num,digit ;
clrscr();
printf("Count number of odd and even digits in a given integer number ");
scanf("%d",&num);
nodd = neven =0; /* count of odd and even digits */
while (num> 0)
{
digit = num % 10; /* separate LS digit from number */
if (digit % 2 == 1)
nodd++;
else neven++;
num /= 10; /* remove LS digit from num */
}
printf("Odd digits : %d Even digits: %d\n", nodd, neven);
getch();
}
You can do something like this:
#include <stdio.h>
int main(){
int n,evenN=0,oddN=0,zeros=0;
char key;
do{
clrscr();
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if(n==0){
printf("%d is zero.",n);
zeros++;
}
else if((n%2)==0){
printf("%d is even.",n);
evenN++;
}
else{
printf("%d is odd.",n);
oddN++;
}
puts("Press ENTER to enter another number. ESC to exit");
do{
key = getch();
}while(key!=13 || key!=27) //13 is the ascii code fore enter key, and 27 is for escape key
}while(key!=27)
clrscr();
printf("Total even numbers: %d",evenN);
printf("Total odd numbers: %d",oddN);
printf("Total odd numbers: %d",zeros);
return 0;
}
This program ask for a number, evaluate the number and then ask to continue for another number or exit.
I have a problem with a c program I'm trying to write. The program must store integers in array (read from the keyboard). The numbers must be printed out in the order of entering, for example if you enter: 3 2 0 5 5 5 8 9, the ouput should be:
3 2 0 - decreasing
5 5 5 - evenly
8 9 - increasing
The problem for me is, that I can't write an algorithm which to be able to work in all cases.
I was trying to "flag" the elements with another array(using the same index, to save for each integer a value 1-for increasing, -1-for decreasing and 0 for evenly), but this works partly.
Have you any other ideas?
Thanks in advance :)
#include <stdio.h>
#include <stdlib.h>
main() {
int array[100];
int flag[100];
int num, i;
printf("Enter how many numbers you want to type: ");
scanf("%d",&num);
for(i=0;i<num;i++) {
scanf("%d",&array[i]);
}
for(i=0;i<num;i++){
if((array[i]<array[i+1])) {
flag[i]=flag[i+1]=1;
}
if(array[i]>array[i+1]) {
flag[i]=flag[i+1]=-1;
}
}
for(i=0;i<num;i++) {
if(array[i]==array[i+1]) {
flag[i]=flag[i+1]=0;
}
}
for(i=0;i<num;i++){
printf("%d ",flag[i]);
}
printf("\n");
for(i=0;i<num;i++) {
if(flag[i]==1) {
do{
if(flag[i]==1){
printf("%d ",array[i]);
i++;
}
}while(flag[i]==1);
printf(" - increasing\n");
}
if(flag[i]==0) {
do{
if(flag[i]==0){
printf("%d ",array[i]);
i++;
}
}while(flag[i]==0);
printf(" - evenly\n");
}
if(flag[i]==-1) {
do{
if(flag[i]==-1) {
printf("%d ",array[i]);
i++;
}
}while(flag[i]==-1);
printf(" - decreasing\n");
}
}
system("pause");
return 0;
}
Thoughts:
You only know if the 'first' number belongs to a descending, even, or ascending sequence after you see the 'second' number.
The 'third' number either belongs to the same sequence as the first two or is the 'first' number of another sequence.
So: check two numbers and assign a sequence type.
Keep checking numbers in the same sequence.
When you cannot assign the same sequence go back to checking two numbers and assigning a sequence.
Something like
int *n1, *n2, *n3;
n1 = <first element>;
n2 = n1 + 1;
n3 = n2 + 1;
/* some kind of loop */
if ((n3 - n2) HAS_SOME_SIGN_AS (n2 - n1)) /* n3 belongs to the sequence */;
n1++;
n2++;
n3++;
/* end loop */
#include <stdio.h>
int status(a, b){
if(a < b) return 1;
if(a > b) return -1;
return 0;
}
int main() {
int array[100]={0};
int old_status, new_status;
int old_pos;
int num, i, j;
const char* status_message[] = {"decreasing","evenly","increasing", "i don't know"};
printf("Enter how many numbers you want to type: ");
scanf("%d",&num);
for(i=0;i<num;i++)
scanf("%d",&array[i]);
//{num | 1 < num <= 100}
old_status =status(array[0], array[1]);
old_pos = 0;
for(i=1;i<num;++i){
new_status = status(array[i-1], array[i]);
if(old_status != new_status){
for(j=old_pos;j<i;++j)
printf("%d ", array[j]);
printf("- %s\n", status_message[1 + old_status]);
old_status = (i<num-1)? status(array[i], array[i+1]):2;
old_pos = i;
}
}
if(old_pos < num){ //not output section output
for(j=old_pos;j<i;++j)
printf("%d ", array[j]);
printf("- %s\n", status_message[1 + old_status]);
}
return 0;
}