How to printf the biggest number of some numbers I wrote In Scanf? - printf

public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a;
for(int i = 1; i > 0; ++i) {
a = scanner.nextInt();
if(a <= 0 & i != 1) {
System.out.println("The largest number is ");
break;
}else if(a <= 0 & i == 1){
System.out.println("No Number entered.");
break;
}else if(a <= 0){
System.out.println("No Number entered.");
break;
}else
System.out.println("Number "+i+": "+a);
}
}
}
QUESTION
I want to scanf some numbers, for example, 3, 5 and 6.
after I scanf 0, it should printf the biggest number, in this example, 6.
How do I write the code for that without using arrays (I am not allowed to use arrays)
I wrote the code that if I scanf 0 first, it tells me "No numbers entered".
and after I scanf several numbers, 0 is the number that breaks the loop and ends the program

try this code :
int n;
scanf("%d",&n);
int a,result;
//result=-infiniti
result=-100000000;
for(int i=1;i<=n;i++)
{
scanf("%d",&a);
if(a>result)
{
result=a;
}
}
printf("%d",result);

Related

How to add JSpinner output into array and check for duplicate

I'm working on a code which has a JSpinner, which gives an output and moves it to int = n, I want to save every JSpinner output and add it into an array to check for duplicates and once found the JPanel should close itself or say you lost.
Scanner s = new Scanner(System.in);
int n = (Integer) spinner.getValue();
if (isPrime(n)) {
Input.setText(n + " is a prime number");
score++;
Highscore.setText("Score: " + score);
int[] array = new int[4];
for(int i=0; i<4;i++)
{
array[i]= (Integer) spinner.getValue();
}
for (int i=0; i < 4;i++)
{
System.out.println(array[i]);
}
Spinner output into array but it fills the whole array with one number example: [3,3,3,3].
private <T> boolean duplicate(T... array)
{
for (int i = 0; i < array.length; i++)
{
for (int j = i + 1; j < array.length; j++)
{
if (array[i] != null && array[i].equals(array[j])) {
return true;
dispose();
}
}
}
return false;
}
Duplicate check
I tried adding the user input from the JSpinner into an array and from there to check for duplicates.
Searched Online but could'nt find anything.
This if my first post so if you need anything more you can tell me.

Shorten the process of finding the sum of positive number (users input 6 different intteger)

I nedd to find the fatest and shortest way to calculate the sum of positive integer that the user input in.
else if(num1<0 && num2 >0 && num3>0 && num4>0 && num5>0 &&num6>0){
totalPositiveNumber =num2 + num3 + num4 + num5 + num6;
System.out.println("The sum of positive integer is: " + totalPositiveNumber);
}
You can read the numbers and store them in an array. Later iterate over the array and sum only, when number is greater than 0. Check below for sample code for reading input from System.in using Scanner class.
import java.util.Scanner;
public class Sum {
public static void main(String args[]) {
Scanner read = new Scanner(System.in);
int array[] = new int[6];
int sum = 0;
for (int i = 0; i<6; i++) {
array[i] = read.nextInt();
}
for (int i = 0; i<6; i++) {
if (array[i] > 0) {
sum = sum + array[i];
}
}
System.out.println(sum);
}
}

Reading .hex file in VHDL

I'm trying to read an intel .hex file using the following VHDL code snippet. My synthesizer is having a problem with the part of the code that is supposed to check for and discard the ':' character at the start of a line. The synthesis tool gives this error "Call to procedure without body" (line marked with comment). I have never seen this error and don't know what it means. Is there a solution for this error (or an alternate way to discard the ':' character)?
function Load_Data(constant x: in integer) return ROM_Data is
use std.textio.all;
use ieee.std_logic_textio.all;
file ROMFILE: TEXT open READ_MODE is "IIU_Code.hex";
variable newline: line;
variable newchar: character;
variable newbyte: std_logic_vector(7 downto 0);
variable newword: std_logic_vector(15 downto 0);
variable NextAddr, ByteCount: integer;
variable NewROM: ROM_Data := (others => (others => '0'));
variable valid: boolean := True;
begin
while (valid) loop
readline(ROMFILE, newline);
read(newline,newchar,valid); --ERROR HERE!!!
if (newchar = ':') and (valid = True) then
hread(newline,newbyte);
ByteCount := to_integer(unsigned(newbyte));
hread(newline,newword);
NextAddr := to_integer(unsigned(newword));
hread(newline,newbyte);
if newbyte = X"01" then --check for EOF marker
valid := False;
end if;
for i in 1 to ByteCount loop
hread(newline,newbyte);
NewROM(NextAddr) := newbyte;
NextAddr := NextAddr + 1;
end loop;
end if;
end loop;
file_close(ROMFILE);
return NewROM;
end;
In lieu of trying to force synthesis to initialize ROM from a file I've been known to write C programs that convert data for models to constants, in this case by generating entity/architecture pairs:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_VECTOR 512
void rom_header (rom_name,array_size)
char *rom_name;
int array_size;
{
printf("library ieee;\nuse ieee.std_logic_1164.all;\n");
printf("\nentity %s is\n port (\n",rom_name);
printf("\tindex:\t\tin integer range 0 to %d;\n",array_size*8-1);
printf("\tOE:\t\tin std_logic;\n");
printf("\toutput:\t\tout std_logic_vector (7 downto 0)\n");
printf(" );\nend ;\n");
printf("\narchitecture behave of %s is\n\n",rom_name);
printf(" subtype bytestring is bit_vector( 7 downto 0);\n");
printf(" type bytestream is array (0 to %d) of bytestring;\n\n",
array_size*8-1);
printf(" constant byte_array:\tbytestream := (\n\t ");
}
void rom_tail() {
printf(" begin\n\n");
printf(" output <= To_StdLogicVector(byte_array(index)) ");
printf("when OE = '1' else\n");
printf(" (others => 'Z') ");
printf("when OE = '0' else\n");
printf(" (others => 'X');\n");
printf("\n\nend behave;\n\n");
}
int main (argc,argv)
int argc;
char *argv[];
{
extern char *optarg;
extern int optind, opterr;
extern int getopt();
char *infile;
char key_vector[MAX_VECTOR][16];
char plain_vector[MAX_VECTOR][16];
char cipher_vector[MAX_VECTOR][16];
char testinput[2047];
char testkey[17];
char testplain[17];
char testcipher[17];
int encrypt[MAX_VECTOR];
int i;
int len;
int testcount = 0;
int totalcount = 0;
int linenumber = 0;
int vector = 0;
int encode = 1;
while ( (i=getopt(argc,argv,"i:")) != -1 ) {
switch (i) {
case 'i':
infile = optarg;
if((freopen(optarg,"r",stdin)) == NULL) {
fprintf(stderr,"ERROR:%s, can't open %s for input\n",
argv[0],optarg);
exit(-1);
}
break;
case '?':
fprintf(stderr,"usage: %s [-i infile] \n",argv[0]);
fprintf(stderr,"\ngenerates VHDL arrays for DES test vectors:\n");
fprintf(stderr,"\tcipher_vector.vhdl\n");
fprintf(stderr,"\tencrypt_vector.vhdl\n");
fprintf(stderr,"\tkey_vector.vhdl\n");
fprintf(stderr,"\tplain_vector.vhdl\n");
exit (-1);
break;
}
}
while (fgets(testinput,(sizeof testinput) -1, stdin) != NULL ) {
linenumber++;
if ( strncmp(testinput,"encrypt",7) == 0) { /* mode = encode */
encode = 1;
fprintf(stderr,"%s",testinput);
}
else
if ( strncmp(testinput,"decrypt",7) == 0) { /* mode = decode */
fprintf(stderr,"%s",testinput);
encode = 0;
}
else
if ( strncmp(testinput," ",1) == 0) { /* key, plain & cipher */
testcount++;
len = sscanf(testinput,"%s%s%s*", testkey, testplain, testcipher);
if (len != 3) {
fprintf(stderr,"ERROR: %s, wrong vector count, line %d\n",
argv[0], linenumber);
exit(-1);
}
else if (strlen(testkey) != 16) {
fprintf(stderr,"ERROR: %s wrong byte count testkey, line %d\n",
argv[0],linenumber);
exit(-1);
}
else if (strlen(testplain) != 16) {
fprintf(stderr,"ERROR: %s wrong byte count testplain, line %d\n",
argv[0],linenumber);
exit(-1);
}
else if (strlen(testcipher) != 16) {
fprintf(stderr,"ERROR: %s wrong byte count testcipher, line %d\n",
argv[0],linenumber);
exit(-1);
}
else {
encrypt[vector] = encode;
strncpy( key_vector[vector], testkey,16);
strncpy( plain_vector[vector], testplain,16);
strncpy(cipher_vector[vector],testcipher,16);
for ( i = 0; i < 16; i++) {
if ( !isxdigit(key_vector[vector][i]) ||
!isxdigit(plain_vector[vector][i]) ||
!isxdigit(cipher_vector[vector][i]) ) {
fprintf(stderr,"ERROR: %s, Vector: %d contains nonhex\n",
argv[0], vector+1);
fprintf(stderr,"\t%s\n",testinput);
exit(-1);
}
}
}
vector++;
if (vector == MAX_VECTOR) {
fprintf(stderr,"%s: Maximum number of vectors = %d\n",
argv[0],MAX_VECTOR);
exit(0);
}
}
else { /* nothing but eyewash */
if ( testcount ) {
fprintf(stderr," %d test vectors\n",testcount);
totalcount +=testcount;
testcount = 0;
}
}
}
fprintf(stderr," Total: %d test vectors\n",totalcount);
if (freopen("key_vector.vhdl","w",stdout) == NULL){
fprintf(stderr,"ERROR: %s can write to key_vector.vhdl\n",argv[0]);
exit (-1);
}
rom_header("key_vector",totalcount);
for(vector = 0; vector < totalcount; vector++) {
for ( i = 0; i <= 15; i++) {
if ( !(i & 1)) {
printf("x\"%c",key_vector[vector][i]);
}
else {
if ( i < 15) {
printf("%c\",",key_vector[vector][i]);
}
else {
printf("%c\"",key_vector[vector][i]); // no comma
}
}
}
if (vector != totalcount-1)
printf(",\n\t ");
else
printf("\n\t);\n");
}
rom_tail();
if (freopen("plain_vector.vhdl","w",stdout) == NULL){
fprintf(stderr,"ERROR: %s can write to plain_vector.vhdl\n",argv[0]);
exit (-1);
}
rom_header("plain_vector",totalcount);
for(vector = 0; vector < totalcount; vector++) {
for ( i = 0; i <= 15; i++) {
if ( !(i & 1)) {
printf("x\"%c",plain_vector[vector][i]);
}
else {
if ( i < 15) {
printf("%c\",",plain_vector[vector][i]);
}
else {
printf("%c\"",plain_vector[vector][i]); // no comma
}
}
}
if (vector != totalcount-1)
printf(",\n\t ");
else
printf("\n\t);\n");
}
rom_tail();
if (freopen("cipher_vector.vhdl","w",stdout) == NULL){
fprintf(stderr,"ERROR: %s can write to cipher_vector.vhdl\n",argv[0]);
exit (-1);
}
rom_header("cipher_vector",totalcount);
for(vector = 0; vector < totalcount; vector++) {
for ( i = 0; i <= 15; i++) {
if ( !(i & 1)) {
printf("x\"%c",cipher_vector[vector][i]);
}
else {
if ( i < 15) {
printf("%c\",",cipher_vector[vector][i]);
}
else {
printf("%c\"",cipher_vector[vector][i]); // no comma
}
}
}
if (vector != totalcount-1)
printf(",\n\t ");
else
printf("\n\t);\n");
}
rom_tail();
if (freopen("encrypt_vector.vhdl","w",stdout) == NULL){
fprintf(stderr,"ERROR: %s can write to encrypt_vector.vhdl\n",argv[0]);
exit (-1);
}
printf("library ieee;\nuse ieee.std_logic_1164.all;\n");
printf("\nentity encrypt_vector is\n port (\n");
printf("\tindex:\t\tin integer range 0 to %d;\n",totalcount-1);
printf("\toutput:\t\tout std_logic\n");
printf(" );\nend ;\n");
printf("\narchitecture behave of encrypt_vector is\n\n");
printf(" constant bit_array:\tstd_logic_vector(0 to %d) := (\n\t ",
totalcount-1);
i = 0;
for(vector = 0; vector < totalcount; vector++) {
printf("'%1d'",encrypt[vector]);i++;
if ((i == 16) && (vector != totalcount-1)) {
printf(",\n\t ");
i = 0;
}
else if (vector == totalcount-1)
printf("\n\t);\n");
else
printf(",");
}
printf(" begin\n\n");
printf(" output <= bit_array(index);");
printf("\n\nend behave;\n\n");
exit (0);
}
You could also do this for packages or even subprograms.
This particular conversion software uses a form of valid vectors preceded by an encryption mode switch and having a first column space, providing hex values of the right string length:
#
encrypt
#
0101010101010101 95F8A5E5DD31D900 8000000000000000
0101010101010101 DD7F121CA5015619 4000000000000000
0101010101010101 2E8653104F3834EA 2000000000000000
0101010101010101 4BD388FF6CD81D4F 1000000000000000
0101010101010101 20B9E767B2FB1456 0800000000000000
0101010101010101 55579380D77138EF 0400000000000000
0101010101010101 6CC5DEFAAF04512F 0200000000000000
#
It's the test vectors for a byte wide interfaced DES chip, and in this case only used in a test bench. There's nothing stopping you from embedding something like you want.
This little C program is quite old but I believe I updated it recently enough it would compile and run, it spits out several different 'vector' files for the test bench based on what the values are used for. It wants the input file to be concluded with a comment line ('#' in the first column), followed by a newline.
So the message here is don't count directly on your synthesis tools to initialize data (unless they handle it with explicitly supported routines).
See How to synthesis a rom and load initial data into it ?, for a hint thread in Xilinx, otherwise noting you haven't specified target platform.
addendum
The questioner has been forthcoming with additional information in comments, wherein automated software has exhorted us to Please avoid extended discussions in comments.
The target is a Microsemi ProASIC3, which also prompted another look at the provided Load_Data function, whose input argument x doesn't show up in the function body. While that indicates the author may have been battling uphill restrictions trying to read a file.
Looking at Microsemi's web site we see that a ProASIC3 can have an embedded 1K bit FLASHROM, which may or may not be the ROM in question. I'm an ASIC designer from way back and can appreciate the size range of these devices, intended for among other uses System on Chip applications. You'd expect the vendor would be able to supply information on how to use the FLASHROM.
For other ROM purposes in lieu of vendor supplied method of loading ROM it would seem that creating a synthesis compatible method of embedding an array of constants is in order (analogous to what's shown in the C programming example).
One characteristic of Read Only Memory in programmable devices is that the values are typically included as part of device programming.

Numbers into words issue C

I am trying to write a program that will take an integer input, and then convert it to words. for example: 123, one two three. Also -3908, negative three nine zero eight.
My code works 90% of the time, the only issue coming along when i am putting one or more zeros on the end of the integer. eg. 70800 will come up as seven zero eight. It completely misses the end zeros. I understand why that is happening but does anybody know if there is a way around it.
PS(i am not allowed as a part of this task to accept the input as a string and split it into an array, so it would be best if the answer is based off this code).
int main(int argc, const char * argv[])
{
#autoreleasepool {
float abNumber;
int i = 0;
float number;
float result;
float firstNumber;
printf("type a number: ");
scanf("%f", &firstNumber);
abNumber = abs(firstNumber);
if (firstNumber < 0) {
printf("negative ");
}
number = abNumber;
while (number >= 10) {
number = number / 10;
i++;
}
do {
float countNumber = abNumber;
float power = powf(10, -i);
float powerNo2 = powf(10, i);
countNumber = countNumber * power;
result = floorf(countNumber);
if (result == 9){
printf("nine ");
}
if (result == 8){
printf("eight ");
}
if (result == 7){
printf("seven ");
}
if (result == 6){
printf("six ");
}
if (result == 5){
printf("five ");
}
if (result == 4){
printf("four ");
}
if (result == 3){
printf("three ");
}
if (result == 2){
printf("two ");
}
if (result == 1){
printf("one ");
}
if (result == 0){
printf("zero ");
}
while (abNumber > powerNo2) {
abNumber = abNumber - powerNo2;
}
i--;
} while (i >= 0);
}
return 0;
}
The main error seems to be that
while (abNumber > powerNo2) {
should be
while (abNumber >= powerNo2) {
But I would recommend not to use floating point arithmetic at all, to avoid
possible rounding errors. The same can be achieved with simple integer arithmetic
(I have omitted the "negative case" for simplicity):
int number;
printf("type a number: ");
scanf("%d", &number);
// Determine highest power of 10 that is <= the given number:
int power = 1;
while (10 * power <= number) {
power *= 10;
}
// Extract each digit:
while (power > 0) {
int digit = (number / power) % 10;
/*
* Use switch/case to print 'digit' as a string ...
*/
power /= 10;
}
I would go for recursive solution, like that
int print(int num)
{
if( num )
{
int mod = num%10;
print(num/10);
switch(mod)
{
case 0:printf(" zero");break;
case 1:printf(" one");break;
case 2:printf(" two");break;
case 3:printf(" three");break;
}
}
return 0;
}
Recursivy divide the number untill nothing left of it, on the way back print the mod.
Why don't you just input the number as a string then loop through each character:
Exemple: http://ideone.com/E8QspN
Input:
-12003200
Output:
negative one two zero zero tree two zero zero
Code:
#include <stdio.h>
int main(int argc, char *argv[])
{
char input[25];
scanf("%s", input);
int i = 0;
while (input[i] != '\0') {
switch(input[i]) {
case '-' :
printf("negative");
break;
case '0' :
printf("zero");
break;
case '1' :
printf("one");
break;
case '2' :
printf("two");
break;
case '3' :
printf("tree");
break;
case '4' :
printf("four");
break;
case '5' :
printf("five");
break;
case '6' :
printf("six");
break;
case '7' :
printf("seven");
break;
case '8' :
printf("eight");
break;
case '9' :
printf("nine");
break;
default :
break;
}
printf(" ");
i++;
}
return 0;
}
Consider the following:
Code
#include <stdio.h>
#include <stdlib.h>
const char *numbers[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
void printNum(int num);
int main(void)
{
int num;
printf("Enter a number: ");
scanf("%u", &num);
printNum(num);
printf("\n");
return 0;
}
void printNum(int num)
{
int absNum = abs(num);
if(absNum > 9)
printNum(num / 10);
if((absNum < 10) && (num < 0))
printf("negative");
printf(" %s", numbers[absNum % 10]);
}
Example Output
Enter a number: 2582
two five eight two
Enter a number: -943
negative nine four three
Enter a number: 1000
one zero zero zero
Enter a number: -1000
negative one zero zero zero
Logic
Get an integer from user.
Send to recursive function.
Keep recursing until the least significant digit is left. This is to print in the correct order.
Print digit as a string by using a lookup table.
Keep someone a high five.
To Do
Error checking

arduino enter input from computer to LCD

I want to take input as a char and concatenate them and write LCD. However I can't it. Also, ı want to not show a symbol which is about enter on LCD.
In this code, input does not written by serial monitor.
#include < LiquidCrystal.h >
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
char karakter;
int ksayi;
String yazi = "";
String kaydirilacak = "";
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
lcd.home();
lcd.print("Hello World");
delay(1000);
lcd.clear();
lcd.home();
}
void loop() {
ksayi = Serial.available();
if (ksayi > 0) {
while (Serial.available() > 0) {
karakter = Serial.read();
if (karakter != '/n') {
yazi += karakter;
}
else {
kaydirilacak = yazi;
lcd.clear();
lcd.write(Serial.read(); yazi = "";
}
}
}
Kaydirmaca(kaydirilacak);
}
void Kaydirmaca(String s) {
int i;
for (i = 0; i < 16; i++) {
lcd.scrollDisplayLeft();
delay(275);
}
}
You are printing out Serial.read(), which returns nothing because serial.available() is zero.
Also, your code does not compile. You are missing an end parenthesis.
else {
kaydirilacak=yazi;
lcd.clear();
lcd.write(Serial.read();
yazi="";
}